Live, while it is happening

The engine room

Every message below is a real send, the moment it happens. The code is the real sender, and the highlight follows the checks each message passes before it is allowed to leave.

—
sent
—
still to go
—
per hour
—
addressed by name
—
refused before sending
—
finishes about
—waiting for the first letter…
—
scripts/outreach/send-gmail.mjswaiting for the next send…
551let nextBreakAt = 12 + Math.floor(Math.random() * 7);
552for (const d of approved) {
553 try {
554 if (stopped()) { console.log(`STOP FILE ${STOP_FILE} present - ending the run before ${d.to_email}`); break; }
555 if (HUMAN) {
556 /* Re-prove THIS address now, not at start: the loaded set is minutes or hours old. */
557 const { rows: [live] } = await sql.query(
558 `select exists (select 1 from v_sendable where lower(email) = lower($1)) ok,
559 exists (select 1 from agent_state where agent_id = $2 and status::text = 'do_not_contact') dnc`, [d.to_email, d.agent_id]);
560 if (!live.ok || live.dnc) okAddr.delete(d.to_email.toLowerCase());
561 }
562 if (!okAddr.has(d.to_email.toLowerCase())) {
563 await sql.query(
564 `update outreach_drafts set status = 'rejected',
565 why_this_company = why_this_company || ' | SKIPPED AT SEND: address no longer in v_sendable'
566 where id = $1`, [d.id]);
567 console.log(` SKIP ${d.company} — ${d.to_email} left v_sendable since approval`);
568 skipped++;
569 continue;
570 }
571 if (Number(d.touch) === 0 && !proven(d.to_email)) {
572 if (REALLY) await sql.query(
573 `update outreach_drafts set status = 'draft',
574 why_this_company = why_this_company || ' | HELD AT SEND ' || to_char(now() at time zone 'Asia/Dubai', 'DD Mon HH24:MI') || ': no mailbox proof in the last 30 days (run /verifyemail, then approve again)'
575 where id = $1 and status = 'approved'`, [d.id]);
576 console.log(` HOLD ${d.company} — ${d.to_email} has no mailbox proof (run /verifyemail first)`);
577 skipped++;
578 continue;
579 }
580
581 if (!REALLY) {
582 console.log(` would send ${d.company.padEnd(40)} -> ${d.to_email} "${d.subject}"`);
583 continue;
584 }
585
586 /* CLAIM IT. Three senders run at once and a keeper restarts any that dies;
587 pgrep is a race, so a twin can exist for an instant. "select approved, then
588 send" is read-then-write with a gap, and in that gap two processes send the
589 same mail to the same partner. Moving approved -> sending in ONE statement
590 closes it: whoever gets the row owns it, the other gets zero rows and walks
591 on. This is the never-mail-twice rule made structural. */
592 const claim = await sql.query(
593 `update outreach_drafts set status = 'sending'
594 where id = $1 and status = 'approved' returning id`, [d.id]);
595 if (!claim.rowCount) {
596 console.log(` claimed by another sender, skipping ${d.company}`);
597 continue;
598 }
599
600 /* Belt and braces: has this exact address already had this touch, under any
601 draft row? The unique index would refuse it at the end anyway, but finding
602 out BEFORE transmitting is the difference between a blocked write and a
603 delivered duplicate. */
604 const dup = await sql.query(
605 `select 1 from outreach_drafts
606 where lower(to_email) = lower($1) and campaign = $2 and touch = $3
607 and status = 'sent' limit 1`, [d.to_email, d.campaign, d.touch]);
608 if (dup.rowCount) {
609 await sql.query(
610 `update outreach_drafts set status = 'rejected',
611 why_this_company = why_this_company || ' | ALREADY SENT to this address for this touch'
612 where id = $1`, [d.id]);
613 console.log(` ALREADY SENT to ${d.to_email} — refusing to send twice`);
614 skipped++;
615 continue;
616 }
617
618 const cc = CC_LIST;
619 // The cross-system double-send guard. The ALREADY SENT check above asks OUR
620 // database; this asks the shared ledger, so a mail a Claude session sent to
621 // this same person an hour ago — which the database knows nothing about —
622 // still stops the campaign writing to them again. Releases the claim first
623 // so the row is not parked in 'sending'. See scripts/mail/mail-guard.mjs.
624 try { await guard({ to: d.to_email, cc, subject: d.subject }); }
625 catch (e) {
626 if (!(e instanceof GuardBlocked)) throw e;
627 await sql.query(`update outreach_drafts set status = 'approved' where id = $1 and status = 'sending'`, [d.id]);
628 console.error(`\n ${d.company}: ${e.message}`);
629 skipped++;
630 continue;
631 }
632 const raw = HUMAN && !CARD
633 ? mime(d.to_email, d.subject, d.body, null, d.campaign, d.touch, cc, null, null)
634 : mime(d.to_email, d.subject, d.body, sigHtml ? htmlBody(d.body) : null,
635 d.campaign, d.touch, cc, ATTACH, INLINE);
636 // A transient ETIMEDOUT on one call must not kill the run (it did, 10 Aug —
637 // 2 of 49 sent, process dead). Retry the network; skip the draft on
638 // persistent failure — it stays approved and the next run picks it up.
639 let res = null;
640 for (let attempt = 1; attempt <= 3; attempt++) {
641 try {
642 // 60s hard timeout: a dead-air connection hung the 10 Aug night run for
643 // 8 hours. A send that times out is treated as NOT sent; reconcile
644 // against the mailbox's real Sent folder before ever assuming otherwise.
645 res = await fetch('https://gmail.googleapis.com/gmail/v1/users/me/messages/send', {
646 method: 'POST',
647 headers: { authorization: `Bearer ${await token()}`, 'content-type': 'application/json' },
648 body: JSON.stringify({ raw: b64url(raw) }),
649 signal: AbortSignal.timeout(60000),
650 });
651 break;
652 } catch (e) {
653 console.error(` network error for ${d.company} (attempt ${attempt}/3): ${e.cause?.code || e.message}`);
654 // THE CONVEYOR LESSON (10 Aug): a send whose response never arrives may
655 // still have TRANSMITTED. Before any retry, ask the mailbox itself.
656 try {
657 const chk = await fetch('https://gmail.googleapis.com/gmail/v1/users/me/messages?' +
658 new URLSearchParams({ q: `in:sent to:${d.to_email} newer_than:1d`, maxResults: '1' }),
659 { headers: { authorization: `Bearer ${await token()}` }, signal: AbortSignal.timeout(30000) });
660 if (chk.ok && ((await chk.json()).resultSizeEstimate || 0) > 0) {
661 console.error(` ${d.company}: found in Sent despite the error — marking sent, NOT retrying`);
662 res = { ok: true, alreadyInSent: true };
663 break;
664 }
665 } catch { /* check itself failed — fall through to retry/backoff */ }
666 if (attempt < 3) await new Promise((r) => setTimeout(r, 15000 * attempt));
667 }
668 }
669 /* Release the claim on a failure we KNOW did not transmit, so the next run
670 picks it up. Both paths below have already asked the mailbox's own Sent
671 folder and been told the message is not there. A claim held by a dead
672 process would otherwise park that partner permanently in 'sending'. */
673 if (!res) {
674 await sql.query(`update outreach_drafts set status = 'approved' where id = $1 and status = 'sending'`, [d.id]);
675 console.error(` GIVING UP on ${d.company} this run — released, next run retries`);
676 continue;
677 }
678 if (!res.ok) {
679 const txt = await res.text();
680 await sql.query(`update outreach_drafts set status = 'approved' where id = $1 and status = 'sending'`, [d.id]);
681 console.error(` FAILED ${d.company}: ${res.status} ${txt} — released, not marked sent`);
682 // A 429 or 403 is Google telling us to slow down or stop. Backing off here
683 // rather than hammering is what keeps the account alive.
684 if (res.status === 429 || res.status === 403) {
685 console.error(` RATE LIMITED on ${SENDER} — pausing 10 minutes`);
686 await new Promise((r) => setTimeout(r, 600000));
687 }
688 continue;
689 }
690
691 await sql.query('begin');
692 try {
693 await sql.query(`update outreach_drafts set status = 'sent', sent_at = now() where id = $1 and status = 'sending'`, [d.id]);
694 await sql.query(
695 `insert into agent_events (agent_id, kind, note, actor_email)
696 values ($1, 'email', $2, $3)`,
697 [d.agent_id, `Touch ${d.touch} sent (${d.campaign}) via Gmail pilot`, SENDER]);
698 await sql.query(
699 `insert into agent_state (agent_id, status, first_emailed_at, last_emailed_at)
700 values ($1, 'emailed', now(), now())
701 on conflict (agent_id) do update
702 set first_emailed_at = coalesce(agent_state.first_emailed_at, now()),
703 last_emailed_at = now(),
704 status = case when agent_state.status = 'new' or agent_state.status = 'researched'
705 then 'emailed' else agent_state.status end`,
706 [d.agent_id]);
707 await sql.query('commit');
The eight checks below run for every single message. Any one of them can stop it.
Sending nowconnecting…
  1. waiting…
Re-prove the address
The never-mail-twice list is checked again at the moment of sending, not at approval. An address that left it since, or a company marked do-not-contact, is skipped and flagged.
Hold a letter without a mailbox proof
A first letter goes only to an address whose mailbox was proved to exist within the last thirty days. Without that proof the draft is put back, not sent. On the same India list, unchecked addresses bounced 13.8% and checked ones 0.3%.
Claim the draft
approved → sending in one statement. When more than one sender runs, whoever gets the row owns it and the other walks on. This is what makes a double send impossible.
Refuse a second send
Has this exact address already had this touch? The database also enforces it with a unique index, but finding out BEFORE transmitting is the difference between a blocked write and a delivered duplicate.
Ask the shared ledger
Our database is not the only thing that writes to partners. Before the message is built, the sender asks the ledger every mail tool here shares, so a letter a colleague sent to the same person an hour ago still stops this one.
Build the message
Plain text and HTML, the signature carried inside the message as a baked card — pixels, because they are the one thing every mail client renders alike.
Hand it to Gmail
A 60-second deadline, three retries — and before any retry it asks the mailbox’s own Sent folder whether the message already went, because a response that never arrives is not the same as a message that never sent.
Record it, or none of it
sent_at, the company timeline entry and the relationship state move together in one transaction, or nothing moves. The record can never claim a mail that did not go.
This run’s supervisor — the code that guarantees the run startsscripts/outreach/run-country.sh, the real file
1#!/bin/bash
2# THE COUNTRY INTRODUCTION SEND - supervisor for one country's campaign
3# (parameterised from run-egypt.sh, 13 Sep 2026). THIS FILE TRANSMITS MAIL when it
4# starts. It refuses to start without his GO in his own words.
5#
6# =========================== MONDAY, PER COUNTRY (Italy shown) ===========================
7# Same for Brazil (br) and Morocco (ma); only the two-letter code changes. Start times
8# are Dubai (this Mac's clock): 09:00 local is Dubai 11:00 Italy, 12:00 Morocco, 16:00 Brazil.
9#
10#   0  (done earlier, not on Monday morning) staged, names resolved, reviewed, approved,
11#      and the sanctions screen recorded fresh (7-day limit):
12#        node scripts/outreach/stage-intro.mjs --country it --approve
13#        node scripts/sanctions-screen.mjs --refresh --country IT --scope all --write
14#
15#   1  where it stands                 node scripts/outreach/country-status.mjs --country it
16#   2  the morning gates (report)      ./scripts/outreach/country-morning-gates.sh it
17#   3  only if gate 1 found new mail   ./scripts/outreach/country-morning-gates.sh it --write
18#                                      ./scripts/outreach/country-morning-gates.sh it    # must now say ALL GATES PASS
19#   4  show him the numbers; get his GO in his own words, with the time he said it
20#   5  arm the send (now, or at a time today):
21#        ./scripts/outreach/run-country.sh it --i-have-his-go "Nisarg 09:05 Mon 14 Sep: go Italy at 11" --start-at 11:00
22#      optional first, one [TEST] message per mailbox to thunga@ (also needs the GO):
23#        ./scripts/outreach/run-country.sh it --rehearse --i-have-his-go "Nisarg 09:05 Mon 14 Sep: rehearse Italy"
24#   6  watch                            tail -f data/outreach/it-$(date +%F)/run.log
25#                                       node scripts/outreach/country-status.mjs --country it
26#   7  stop cleanly                     touch /tmp/it-send-stop
27#   8  after                            pmset -g log | grep -iE 'Entering Sleep|Wake from'
28#                                       node scripts/outreach/count-bounces.mjs
29# ==========================================================================================
30#
31# REFUSES TO START (exit 1, nothing sent) unless ALL of:
32#   · --i-have-his-go "<his words and the time>" is given (contains a HH:MM time). The
33#     words are written to data/build-log/important-<date>.md and to the run log.
34#   · approved, unsent drafts exist for the country's campaign (country-status --remaining)
35#   · every approved mailbox is a known sender identity
36#   · country-morning-gates.sh <cc> --no-power exits 0, and again at the start time if
37#     the run waited ten minutes or more (mail keeps arriving)
38#   · no stop file /tmp/<cc>-send-stop, and no other supervisor for this country
39# There is NO default start time: without --start-at it starts now.
40#
41# Per-sender split: one sender loop per send_as mailbox found on the approved drafts
42# (globalsales@ = account globalsales, thunga@ = account me), each copying the other(s),
43# gap 45s and cap 800/mailbox/day as Egypt. send-gmail.mjs counts the cap per mailbox
44# across ALL campaigns, so two countries on one day share the 800. If another send is
45# live at the start time (another country's supervisor or any send-gmail --send), this
46# one WAITS for it to finish, so a mailbox never sends at double cadence; pass
47# --allow-concurrent to override that knowingly.
48#
49# Logs: data/outreach/<cc>-<date>/run.log (supervisor + sender output), gates.log,
50# heartbeat. It cannot decide to send anything: send-gmail.mjs reads only 'approved'
51# drafts, and approving is a separate, deliberate act.
52#
53# Why the power/lid/heartbeat/restart machinery: see run-egypt.sh. A sleeping Mac looks
54# identical to a healthy one in the morning; a dead sender is restarted in seconds.
55
56set -u
57# The caller's directory, kept across the caffeinate re-exec, so a relative --attach path
58# means what it meant where he typed it.
59: "${WZ_CALLER_PWD:=$PWD}"; export WZ_CALLER_PWD
60cd "$(dirname "$0")/../.." || exit 1
61
62GAP=45
63CAP=80        # 14 Sep: 80 cold letters per mailbox per day, not 800. Pace the domain, not the list.
64GAP_MIN=90    # --human: a random 90-240 s between letters, plus a 6-12 min break every 12-18
65GAP_MAX=240
66WATCH_EVERY=300   # send-watch reads bounces, blocks and complaints every 5 minutes during a run
67REGATE_AFTER=600   # re-run the gates at the start time if we waited at least this long
68
69usage() {
70  cat >&2 <<'EOF'
71usage: run-country.sh <cc> --i-have-his-go "<his words and the time>" [--start-at HH:MM] [--cap N] [--gap-min S] [--gap-max S] [--no-breaks] [--rehearse] [--allow-concurrent] [--keep-cc|--no-cc] [--card|--no-card] [--cc-list a@x,b@y] [--card] [--classic] [--require-charger] [--attach file.pdf]
72   --attach puts one PDF on every letter, the rehearsal included (29 Sep 2026, Morocco: "attach the
73   company profile"). The recipient sees the file's own name, so name the file for them. It needs the
74   signature card: --human without --card sends plain text and would drop the attachment silently.
75   Default since 21 Sep: CC KEPT and the sender's HTML SIGNATURE on (--no-cc / --no-card to switch off,
76   his word only). Human pacing since 14 Sep: no campaign headers, random 90-240 s gaps, cap 80/mailbox/day,
77   and send-watch every 5 min (stops on a spam/reputation block, hard bounces >= 5%, a regulator complaint;
78   suppresses "remove me" replies mid-run). --keep-cc keeps the other mailbox in CC; --classic restores the
79   old HTML card + 45 s gap + cap 800 and needs his word for that too.
80   --cap N lowers the per-mailbox daily cap. Singapore, 21 Sep 2026: the Spam Control Act 2007
81   s 6(1)(a) makes a send "in bulk" at more than 100 messages of the same or similar subject
82   matter in 24 hours, counted against the person who AUTHORISES the send, so splitting across
83   mailboxes does not help. --cap 26 across three mailboxes holds the company under 100 a day
84   and keeps the letters outside the Act's Second Schedule entirely. Run it again the next
85   morning: the sender already leaves the remainder for tomorrow when a cap is reached.
86   e.g. run-country.sh it --i-have-his-go "Nisarg 09:05 Mon 14 Sep: go Italy at 11" --start-at 11:00
87EOF
88}
89
90# ---- arguments ----------------------------------------------------------------
91ORIG_ARGS=("$@")
92CC=$(printf '%s' "${1:-}" | tr 'A-Z' 'a-z')
93case "$CC" in [a-z][a-z]) ;; *) usage; exit 1 ;; esac
94shift
95[ -f "scripts/outreach/countries/$CC.mjs" ] || { echo "REFUSING: no country file scripts/outreach/countries/$CC.mjs" >&2; exit 1; }
96CCU=$(printf '%s' "$CC" | tr 'a-z' 'A-Z')
97
98# 21 Sep 2026, Morocco: Nisarg, "WHY IS THERE NO CC" and "There's no HTML signature". Both are
99# now ON unless switched off by name: every letter copies the other mailbox(es) and carries the
100# sender's HTML signature. --no-cc / --no-card are the only way out, and need his word.
101GO=""; START_AT=""; REHEARSE=0; CONCURRENT=0; KEEP_CC=1; CLASSIC=0; CC_FIXED=""; CARD=1; CAP_SET=0; ATTACH=""; HARD_LIMIT=""
102# 14 Sep 21:34, his words: "make it so that it starts on battery as well". A battery start is
103# the default; caffeinate -i still holds idle sleep off on battery (only -s is ignored), and the
104# battery floor below stops the run cleanly between letters before the Mac can die mid-send.
105# --require-charger restores the old wait-for-AC guard.
106REQUIRE_AC=0; BATTERY_FLOOR=10
107NO_BREAKS=0   # 12 Oct: --no-breaks drops the 6-12 min pause every 12-18 letters (his word); the gap stays
108while [ $# -gt 0 ]; do
109  case "$1" in
110    --require-charger)  REQUIRE_AC=1; shift ;;
111    --i-have-his-go)    [ $# -ge 2 ] || { usage; exit 1; }; GO="$2"; shift 2 ;;
112    --start-at)         [ $# -ge 2 ] || { usage; exit 1; }; START_AT="$2"; shift 2 ;;
113    --rehearse)         REHEARSE=1; shift ;;
114    --allow-concurrent) CONCURRENT=1; shift ;;
115    --keep-cc)          KEEP_CC=1; shift ;;
116    --no-cc)            KEEP_CC=0; shift ;;
117    --card)             CARD=1; shift ;;
118    --no-card)          CARD=0; shift ;;
119    --no-breaks)        NO_BREAKS=1; shift ;;
120    --cc-list)          [ $# -ge 2 ] || { usage; exit 1; }; CC_FIXED=$(printf '%s' "$2" | tr 'A-Z' 'a-z'); shift 2 ;;
121    --gap-min)          [ $# -ge 2 ] || { usage; exit 1; }
122                        case "$2" in ''|*[!0-9]*) echo "--gap-min needs whole seconds" >&2; exit 1 ;; esac
123                        GAP_MIN="$2"; shift 2 ;;
124    --gap-max)          [ $# -ge 2 ] || { usage; exit 1; }
125                        case "$2" in ''|*[!0-9]*) echo "--gap-max needs whole seconds" >&2; exit 1 ;; esac
126                        GAP_MAX="$2"; shift 2 ;;
127    --cap)              [ $# -ge 2 ] || { usage; exit 1; }
128                        case "$2" in ''|*[!0-9]*) echo "--cap needs a whole number of letters per mailbox per day" >&2; exit 1 ;; esac
129                        [ "$2" -ge 1 ] || { echo "--cap must be at least 1" >&2; exit 1; }
130                        CAP="$2"; CAP_SET=1; shift 2 ;;
131    --classic)          CLASSIC=1; [ "${CAP_SET:-0}" -eq 1 ] || CAP=800; shift ;;
132    --attach)           [ $# -ge 2 ] || { usage; exit 1; }; ATTACH="$2"; shift 2 ;;
133    --hard-limit)       [ $# -ge 2 ] || { usage; exit 1; }
134                        case "$2" in ''|*[!0-9]*) echo "--hard-limit needs a whole number" >&2; exit 1 ;; esac
135                        HARD_LIMIT="$2"; shift 2 ;;
136    *) echo "unknown argument: $1" >&2; usage; exit 1 ;;
137  esac
138done
139
140if [ "$GAP_MIN" -ge "$GAP_MAX" ]; then echo "REFUSING: --gap-min ($GAP_MIN) must be below --gap-max ($GAP_MAX)" >&2; exit 1; fi
141
142# ---- the attachment: one real PDF, carried by every letter ---------------------------
143ATTACH_ARGS=()
144if [ -n "$ATTACH" ]; then
145  case "$ATTACH" in /*) ;; *) ATTACH="$WZ_CALLER_PWD/$ATTACH" ;; esac
146  [ -f "$ATTACH" ] || { echo "REFUSING: --attach file not found: $ATTACH. Nothing was sent." >&2; exit 1; }
147  head -c 5 "$ATTACH" | grep -q '^%PDF-' || { echo "REFUSING: --attach must be a PDF (send-gmail labels it application/pdf): $ATTACH" >&2; exit 1; }
148  if [ "$CLASSIC" -eq 0 ] && [ "$CARD" -eq 0 ]; then
149    echo "REFUSING: --attach with --no-card. A plain-text letter carries no attachment, so it would go without the PDF." >&2; exit 1
150  fi
151  ATTACH_ARGS=(--attach "$ATTACH")
152fi
153ATTACH_NOTE=""; [ -n "$ATTACH" ] && ATTACH_NOTE=" · attachment $(basename "$ATTACH") ($(( $(stat -f%z "$ATTACH") / 1024 )) KB)"
154
155# ---- the country's legal daily ceiling ------------------------------------------------
156# A country file may declare dailyCap: the most letters this company may put on the wire for
157# that country in 24 hours. Singapore's is 100 and it is the Spam Control Act 2007 s 6(1)(a)
158# bulk threshold, not a deliverability preference; the reasoning is in countries/sg.mjs.
159# The cap is per MAILBOX, so the ceiling that matters is cap x mailboxes.
160DAILY_CAP=$(node -e "import('./scripts/outreach/stage-intro.mjs').then(async m=>{const{country}=await m.loadCountry('$CC');process.stdout.write(String(country.dailyCap||0))}).catch(()=>process.stdout.write('0'))" 2>/dev/null || echo 0)
161DAILY_WHY=$(node -e "import('./scripts/outreach/stage-intro.mjs').then(async m=>{const{country}=await m.loadCountry('$CC');process.stdout.write(String(country.dailyCapWhy||''))}).catch(()=>process.stdout.write(''))" 2>/dev/null || echo "")
162N_BOXES=$(node -e "import('./scripts/outreach/stage-intro.mjs').then(async m=>{const{country}=await m.loadCountry('$CC');process.stdout.write(String(m.sendersFor(country).length))}).catch(()=>process.stdout.write('2'))" 2>/dev/null || echo 2)
163# 5 Oct 2026, his word: the legal ceiling counts THIS country's letters only. Counting every
164# campaign from the mailbox let India's letters stop Singapore at 35 of 99.
165CAP_SCOPE=(); STATUS_SCOPE=(); CAP_WHAT="across all campaigns"
166if [ "${DAILY_CAP:-0}" -gt 0 ]; then
167  CAP_SCOPE=(--cap-campaign); STATUS_SCOPE=(--this-campaign); CAP_WHAT="for this campaign"
168  MOST=$((CAP * N_BOXES))
169  if [ "$MOST" -gt "$DAILY_CAP" ]; then
170    echo "REFUSING TO START: --cap $CAP across $N_BOXES mailboxes could put $MOST letters on the wire today," >&2
171    echo "                   but $CCU declares a daily ceiling of $DAILY_CAP." >&2
172    echo "                   Why: $DAILY_WHY" >&2
173    echo "                   Use --cap $((DAILY_CAP / N_BOXES)) or lower. Nothing was sent." >&2
174    exit 1
175  fi
176fi
177
178DAY=$(date +%F)
179DIR="data/outreach/$CC-$DAY"
180LOG="$DIR/run.log"
181BEAT="$DIR/heartbeat"
182STOP="/tmp/$CC-send-stop"
183PIDFILE="/tmp/$CC-send-supervisor.pid"
184mkdir -p "$DIR"
185
186say() { echo "$(date '+%F %T %Z')  [$CCU] $*" | tee -a "$LOG"; }
187refuse() { say "REFUSING TO START: $*"; say "                   nothing was sent."; exit 1; }
188
189# ---- guard 1: his GO, in his words ----------------------------------------------
190# Checked first and before anything touches the database or the clock.
191GO_TRIM=$(printf '%s' "$GO" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
192if [ -z "$GO_TRIM" ]; then
193  refuse "no --i-have-his-go \"<his words and the time>\" argument. This send transmits mail; it needs his explicit GO, quoted."
194fi
195case "$GO_TRIM" in
196  *'<'*|*'>'*) refuse "the GO argument still holds a placeholder (<...>). Quote his actual words." ;;
197esac
198if ! printf '%s' "$GO_TRIM" | grep -qE '(^|[^0-9])([01]?[0-9]|2[0-3]):[0-5][0-9]([^0-9]|$)'; then
199  refuse "the GO argument must carry the time he said it (HH:MM), e.g. \"Nisarg 09:05 Mon: go Italy\"."
200fi
201if [ "${#GO_TRIM}" -lt 12 ]; then
202  refuse "the GO argument is too short to be his words: \"$GO_TRIM\"."
203fi
204
205# ---- the start time: today, or now ------------------------------------------------
206NOW_EPOCH=$(date +%s)
207if [ -n "$START_AT" ]; then
208  printf '%s' "$START_AT" | grep -qE '^([01][0-9]|2[0-3]):[0-5][0-9]$' || refuse "--start-at must be HH:MM (24-hour, this Mac's clock), got \"$START_AT\""
209  START_EPOCH=$(date -j -f '%Y-%m-%d %H:%M:%S' "$DAY $START_AT:00" +%s 2>/dev/null) || refuse "could not read --start-at $START_AT"
210  if [ "$START_EPOCH" -lt $((NOW_EPOCH - 900)) ]; then
211    refuse "--start-at $START_AT is more than 15 minutes in the past today. Omit --start-at to start now, with his GO."
212  fi
213  [ "$START_EPOCH" -lt "$NOW_EPOCH" ] && START_EPOCH=$NOW_EPOCH
214else
215  START_EPOCH=$NOW_EPOCH
216fi
217
218# ---- hold a sleep assertion for the whole run (see run-egypt.sh) ------------------
219if [ -z "${WZ_CAFFEINATED:-}" ]; then
220  export WZ_CAFFEINATED=1
221  exec caffeinate -ims "$0" "${ORIG_ARGS[@]}"
222fi
223
224# ---- guard 2: one supervisor per country, and no stale stop file --------------------
225if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE" 2>/dev/null)" 2>/dev/null; then
226  refuse "another $CCU supervisor is already running (pid $(cat "$PIDFILE")). Stop it with: touch $STOP"
227fi
228if [ -f "$STOP" ]; then
229  refuse "stop file $STOP is present. If that stop is old and he has said GO, remove it (rm $STOP) and run again."
230fi
231echo $$ > "$PIDFILE"
232ACTIVE="/tmp/wz-send-active-$CC"
233cleanup() { rm -f "$PIDFILE" "$ACTIVE"; }
234trap cleanup EXIT
235
236CAMPAIGN=$(node --input-type=module -e "
237  const { loadCountry } = await import('./scripts/outreach/stage-intro.mjs');
238  const { country } = await loadCountry('$CC');
239  console.log(country.campaign);" 2>/dev/null | tail -1)
240[ -n "$CAMPAIGN" ] || refuse "could not read the campaign from scripts/outreach/countries/$CC.mjs"
241say "campaign $CAMPAIGN · GO given as: \"$GO_TRIM\""
242
243# ---- guard 3: approved drafts exist ------------------------------------------------
244REMAINING=$(node scripts/outreach/country-status.mjs --country "$CC" --remaining 2>/dev/null | tail -1)
245case "$REMAINING" in
246  ''|*[!0-9]*) refuse "could not read the approved count for $CAMPAIGN from the database" ;;
247esac
248if [ "$REMAINING" -eq 0 ]; then
249  refuse "0 approved and unsent drafts for $CAMPAIGN. Stage and approve first (stage-intro.mjs --country $CC --approve); this script approves nothing."
250fi
251
252# ---- guard 4: the mailboxes are known identities -----------------------------------
253BOXES=$(node scripts/outreach/country-status.mjs --country "$CC" --mailboxes 2>/dev/null)
254[ -n "$BOXES" ] || refuse "no send_as mailbox on the approved drafts of $CAMPAIGN"
255ACCTS=""
256for box in $BOXES; do
257  case "$box" in
258    globalsales@worldzone.ae) acct=globalsales ;;
259    thunga@worldzone.ae)      acct=me ;;
260    pricing5@worldzone.ae)    acct=pricing5 ;;
261    *) refuse "approved drafts are assigned to $box, which send-gmail.mjs has no identity for" ;;
262  esac
263  ACCTS="$ACCTS $acct:$box"
264done
265cc_for() { # 29 Sep 2026, Nisarg: copy thunga@ only; Soumya and Julie never copy each other; thunga@ copies nobody
266  local me="$1"
267  # 17:27 his word "Add Soumya CC for my mails": thunga@ copies globalsales@
268  # 6 Oct 2026 11:19, his word "remove soumya from cc from my emails": thunga@ copies nobody again
269  if [ "$me" = "thunga@worldzone.ae" ]; then printf '%s' ""; else printf '%s' "thunga@worldzone.ae"; fi
270}
271SPLIT=""
272for box in $BOXES; do
273  n=$(node scripts/outreach/country-status.mjs --country "$CC" --remaining --mailbox "$box" 2>/dev/null | tail -1)
274  SPLIT="$SPLIT $box=$n"
275done
276say "$REMAINING approved and unsent ·$SPLIT"
277
278# ---- rehearsal: one [TEST] message per mailbox to thunga@, nothing marked sent ------
279if [ "$REHEARSE" -eq 1 ]; then
280  say "REHEARSAL on his GO - one real [TEST] message per mailbox to thunga@worldzone.ae, nothing marked sent$ATTACH_NOTE"
281  mkdir -p data/build-log
282  printf '\n**%s — [OUTREACH] %s rehearsal on his GO: "%s".** One [TEST] message per mailbox (%s) to thunga@, nothing marked sent. Run log %s.\n' \
283    "$(date '+%H:%M')" "$CCU" "$GO_TRIM" "$(echo $BOXES)" "$LOG" >> "data/build-log/important-$DAY.md"
284  for pair in $ACCTS; do
285    acct="${pair%%:*}"; box="${pair#*:}"
286    # 21 Sep: the rehearsal copies exactly as the real run will (it ignored --cc-list before).
287    if [ -n "$CC_FIXED" ]; then rcc=$(printf '%s' "$CC_FIXED" | tr ',' '\n' | grep -vx "$box" | paste -sd, -)
288    elif [ "$KEEP_CC" -eq 1 ]; then rcc="$(cc_for "$box")"; else rcc=""; fi
289    if [ "$CLASSIC" -eq 1 ]; then HUMANFLAG=""; else HUMANFLAG="--human"; fi
290    say "  rehearsing $box (cc ${rcc:-none}, ${HUMANFLAG:-classic}$ATTACH_NOTE)"
291    caffeinate -dimsu node scripts/outreach/send-gmail.mjs --send $([ "${NO_BREAKS:-0}" -eq 1 ] && echo --no-breaks) $HUMANFLAG $([ "$CARD" -eq 1 ] && echo --card) \
292      --account "$acct" --campaign "$CAMPAIGN" ${ATTACH_ARGS[@]+"${ATTACH_ARGS[@]}"} \
293      --cc "$rcc" --test thunga@worldzone.ae 2>&1 | tee -a "$LOG"
294  done
295  say "REHEARSAL DONE - open every message on phone AND desktop and read them"
296  exit 0
297fi
298
299# ---- guard 5: the morning gates ------------------------------------------------------
300run_gates() {
301  say "running the morning gates (log: $DIR/gates.log)"
302  local out rc
303  # command substitution waits for the gates' own tee to close, so the verdict is this run's
304  out=$(./scripts/outreach/country-morning-gates.sh "$CC" --no-power 2>&1)
305  rc=$?
306  printf '%s\n' "$out" | grep -E "^=== $CCU: (ALL GATES PASS|GATES FAIL)|^    gate 1:" | sed 's/^/                     /' | tee -a "$LOG"
307  return $rc
308}
309run_gates || refuse "the morning gates did not pass. Read $DIR/gates.log, fix, and run again."
310
311# ---- armed: write his words where he reads ------------------------------------------
312START_HM=$(date -r "$START_EPOCH" '+%H:%M')
313IMPORTANT="data/build-log/important-$DAY.md"
314mkdir -p data/build-log
315printf '\n**%s — [OUTREACH] %s send armed on his GO: "%s".** Campaign %s, %s approved (%s), start %s Dubai, gap %ss, cap %s per mailbox per day. Run log %s; stop with touch %s.\n' \
316  "$(date '+%H:%M')" "$CCU" "$GO_TRIM" "$CAMPAIGN" "$REMAINING" "$(echo $SPLIT | sed 's/ /, /g')" "$START_HM" "$GAP" "$CAP" "$LOG" "$STOP" >> "$IMPORTANT"
317say "ARMED on his GO \"$GO_TRIM\" · start $START_HM$ATTACH_NOTE · logged to $IMPORTANT"
318
319# ---- the unattended-run guards: power and lid (wait, then refuse at the start time) --
320battery_pct() { pmset -g batt | grep -o '[0-9]\{1,3\}%' | head -1 | tr -d '%'; }
321if [ "$REQUIRE_AC" -eq 0 ] && ! pmset -g ps | grep -q 'AC Power'; then
322  pct=$(battery_pct)
323  [ -n "$pct" ] && [ "$pct" -le "$BATTERY_FLOOR" ] && refuse "on battery at ${pct}%, at or below the ${BATTERY_FLOOR}% floor. Plug in the charger."
324  say "on BATTERY at ${pct}% - starting anyway; the run stops cleanly at ${BATTERY_FLOOR}% (plug in any time to finish)"
325elif ! pmset -g ps | grep -q 'AC Power'; then
326  say "on BATTERY - waiting for the charger (will continue once plugged in)"
327  while ! pmset -g ps | grep -q 'AC Power'; do
328    if [ -f "$STOP" ]; then say "stop file while waiting for power - exiting"; exit 0; fi
329    if [ "$(date +%s)" -ge "$START_EPOCH" ]; then
330      refuse "start time reached and this Mac is still on battery. caffeinate -s is ignored on battery and it would sleep mid-run."
331    fi
332    date '+%F %T' > "$BEAT"; sleep 30
333  done
334  say "charger detected - continuing"
335fi
336lid_closed() { [ "$(ioreg -r -k AppleClamshellState 2>/dev/null | grep -m1 AppleClamshellState | grep -o 'Yes\|No')" = "Yes" ]; }
337if lid_closed; then
338  say "lid is CLOSED - waiting for it to be opened"
339  while lid_closed; do
340    if [ -f "$STOP" ]; then say "stop file while waiting for the lid - exiting"; exit 0; fi
341    if [ "$(date +%s)" -ge "$START_EPOCH" ]; then
342      refuse "start time reached with the lid CLOSED. This has cost this project two overnight runs already."
343    fi
344    date '+%F %T' > "$BEAT"; sleep 30
345  done
346  say "lid open - continuing"
347fi
348
349# ---- wait for the hour ----------------------------------------------------------------
350ARMED_EPOCH=$(date +%s)
351WAIT=$((START_EPOCH - ARMED_EPOCH))
352if [ "$WAIT" -gt 0 ]; then
353  say "waiting ${WAIT}s until $(date -r "$START_EPOCH" '+%F %T %Z')"
354  while [ "$(date +%s)" -lt "$START_EPOCH" ]; do
355    [ -f "$STOP" ] && { say "stop file during the wait - exiting, nothing sent"; exit 0; }
356    date '+%F %T' > "$BEAT"; sleep 30
357  done
358  if [ "$WAIT" -ge "$REGATE_AFTER" ]; then
359    say "start time reached after ${WAIT}s - re-running the gates, mail kept arriving"
360    run_gates || refuse "the morning gates failed at the start time. Read $DIR/gates.log."
361  fi
362fi
363
364# ---- one mailbox never sends at double cadence ------------------------------------------
365other_sends() { # live send-gmail --send processes for another campaign, and other countries' active flags
366  ps -axo command= 2>/dev/null | grep 'send-gmail.mjs --send' | grep -v grep | grep -v -- "--campaign $CAMPAIGN" | head -3
367  local f p
368  for f in /tmp/wz-send-active-*; do
369    [ -f "$f" ] || continue; [ "$f" = "$ACTIVE" ] && continue
370    p=$(cat "$f" 2>/dev/null); kill -0 "$p" 2>/dev/null && echo "supervisor $f (pid $p)"
371  done
372}
373if [ "$CONCURRENT" -eq 0 ] && [ -n "$(other_sends)" ]; then
374  say "another send is live - waiting for it to finish (--allow-concurrent overrides):"
375  other_sends | sed 's/^/                     /' | tee -a "$LOG"
376  while [ -n "$(other_sends)" ]; do
377    [ -f "$STOP" ] && { say "stop file while waiting for the other send - exiting, nothing sent"; exit 0; }
378    date '+%F %T' > "$BEAT"; sleep 60
379  done
380  say "the other send has finished - re-running the gates"
381  run_gates || refuse "the morning gates failed after waiting for the other send. Read $DIR/gates.log."
382fi
383echo $$ > "$ACTIVE"
384
385# ---- send -------------------------------------------------------------------------------
386if [ "$CLASSIC" -eq 1 ]; then MODE="classic: HTML card, gap ${GAP}s"; else MODE="human: $([ "$CARD" -eq 1 ] && echo "signature card" || echo "plain text"), no campaign headers, gap ${GAP_MIN}-${GAP_MAX}s $([ "$NO_BREAKS" -eq 1 ] && echo 'no breaks' || echo 'with breaks')"; fi
387say "=== starting$SPLIT · $MODE · cap ${CAP}/mailbox/day$ATTACH_NOTE · cc $([ -n "$CC_FIXED" ] && echo "$CC_FIXED minus sender" || { [ "$KEEP_CC" -eq 1 ] && echo kept || echo none; }) · send-watch every ${WATCH_EVERY}s ==="
388
389# ---- the watcher: the run stops itself on a block, a bounce storm or a complaint ----------
390# It also suppresses every "remove me" reply at once; send-gmail --human re-proves each address
391# against do_not_contact immediately before sending. Exit 3 = it wrote the stop file.
392# Exit 2 = it could not read a mailbox: three in a row (15 min blind) stops the run, because a
393# send that cannot see its own bounces is not a safe send.
394# 29 Sep 2026, Morocco: without --since the watch counted bounces from the campaign's FIRST send,
395# so four hard bounces of 21 Sep (recorded and suppressed that day, none on today's list) stopped
396# today's 118 before one letter left, and would have stopped every later batch for ever. It now
397# judges today's sends: a same-day restart still remembers today's bounces, and 3 new ones stop it.
398WATCH_SINCE=$(date -u -r "$(date -j -f '%Y-%m-%d %H:%M:%S' "$DAY 00:00:00" +%s)" '+%Y-%m-%dT%H:%M:%SZ')
399watch_once() {
400  # --hard-limit (his word only) raises today's hard-bounce stop; spam, reputation and complaint stops are unchanged.
401  node scripts/outreach/send-watch.mjs --campaign "$CAMPAIGN" --write --stop-file "$STOP" --since "$WATCH_SINCE" \
402    $([ -n "$HARD_LIMIT" ] && echo --hard-limit "$HARD_LIMIT") >> "$DIR/watch.log" 2>&1
403}
404watch_once; wrc=$?
405if [ "$wrc" -eq 3 ]; then say "send-watch refused the start: $(tail -1 "$STOP")"; exit 0; fi
406( blind=0
407  while [ ! -f "$STOP" ]; do
408    sleep "$WATCH_EVERY"
409    [ -f "$STOP" ] && break
410    watch_once; wrc=$?
411    case "$wrc" in
412      3) say "SEND-WATCH STOPPED THE RUN: $(tail -1 "$STOP")"; break ;;
413      2) blind=$((blind+1)); say "send-watch could not read a mailbox ($blind in a row)"
414         if [ "$blind" -ge 3 ]; then echo "$(date '+%F %T') send-watch blind for 15 min" >> "$STOP"; say "STOPPING: cannot see bounces for 15 minutes"; break; fi ;;
415      *) blind=0 ;;
416    esac
417  done ) &
418WATCH_PID=$!
419
420# ---- the battery floor: on battery at or below the floor, stop between letters ----------------
421( while [ ! -f "$STOP" ]; do
422    sleep 60
423    if ! pmset -g ps | grep -q 'AC Power'; then
424      pct=$(battery_pct)
425      if [ -n "$pct" ] && [ "$pct" -le "$BATTERY_FLOOR" ]; then
426        echo "$(date '+%F %T') battery at ${pct}% on battery power - stopped before the Mac sleeps; the rest stay approved" >> "$STOP"
427        say "BATTERY FLOOR: ${pct}% - stopping cleanly between letters; plug in and re-run to finish"
428        break
429      fi
430    fi
431  done ) &
432BATT_PID=$!
433
434send_loop() {
435  local acct="$1" box="$2" copies="$3" left today rc
436  while true; do
437    [ -f "$STOP" ] && { say "[$box] stop file - exiting"; return 0; }
438    left=$(node scripts/outreach/country-status.mjs --country "$CC" --remaining --mailbox "$box" 2>/dev/null | tail -1)
439    case "$left" in ''|*[!0-9]*) left=-1 ;; esac
440    if [ "$left" -eq 0 ]; then say "[$box] nothing left approved for $CAMPAIGN - done"; return 0; fi
441    today=$(node scripts/outreach/country-status.mjs --country "$CC" --sent-today --mailbox "$box" ${STATUS_SCOPE[@]+"${STATUS_SCOPE[@]}"} 2>/dev/null | tail -1)
442    case "$today" in ''|*[!0-9]*) today=-1 ;; esac
443    if [ "$today" -ge "$CAP" ]; then say "[$box] cap reached ($today sent today $CAP_WHAT, cap $CAP) - $left left for tomorrow"; return 0; fi
444
445    say "[$box] starting sender ($left left in this mailbox, cc ${copies:-none})"
446    if [ "$CLASSIC" -eq 1 ]; then
447      caffeinate -dimsu node scripts/outreach/send-gmail.mjs --send $([ "${NO_BREAKS:-0}" -eq 1 ] && echo --no-breaks) \
448        --account "$acct" --campaign "$CAMPAIGN" ${ATTACH_ARGS[@]+"${ATTACH_ARGS[@]}"} \
449        --cc "$copies" --cap "$CAP" ${CAP_SCOPE[@]+"${CAP_SCOPE[@]}"} --gap "$GAP" --stop-file "$STOP" >> "$LOG" 2>&1
450    else
451      caffeinate -dimsu node scripts/outreach/send-gmail.mjs --send $([ "${NO_BREAKS:-0}" -eq 1 ] && echo --no-breaks) --human $([ "$CARD" -eq 1 ] && echo --card) \
452        --account "$acct" --campaign "$CAMPAIGN" ${ATTACH_ARGS[@]+"${ATTACH_ARGS[@]}"} \
453        --cc "$copies" --cap "$CAP" ${CAP_SCOPE[@]+"${CAP_SCOPE[@]}"} --gap-min "$GAP_MIN" --gap-max "$GAP_MAX" --stop-file "$STOP" >> "$LOG" 2>&1
454    fi
455    rc=$?
456    say "[$box] sender exited rc=$rc"
457    sleep 20
458  done
459}
460
461# Heartbeat, independent of the senders. If this file stops advancing the run is
462# stalled or the Mac is asleep, whatever the log's last line says.
463( while [ ! -f "$STOP" ]; do date '+%F %T' > "$BEAT"; sleep 60; done ) &
464BEAT_PID=$!
465
466PIDS=""
467for pair in $ACCTS; do
468  acct="${pair%%:*}"; box="${pair#*:}"
469  # 14 Sep, Nisarg: "me and Soumya in CC for all". --cc-list is that fixed list, minus the sender.
470  if [ -n "$CC_FIXED" ]; then copies=$(printf '%s' "$CC_FIXED" | tr ',' '\n' | grep -vx "$box" | paste -sd, -)
471  elif [ "$KEEP_CC" -eq 1 ]; then copies="$(cc_for "$box")"; else copies=""; fi
472  send_loop "$acct" "$box" "$copies" &
473  PIDS="$PIDS $!"
474done
475wait $PIDS
476kill $BEAT_PID $WATCH_PID $BATT_PID 2>/dev/null
477watch_once   # one last read after the final letter, so late bounces and replies are counted and suppressed
478
479say "=== all senders finished ==="
480node scripts/outreach/country-status.mjs --country "$CC" 2>&1 | tee -a "$LOG"
481say "Now prove the Mac stayed awake:  pmset -g log | grep -iE 'Entering Sleep|Wake from'"
482
Every guard here is a previous failure made structural. It refuses to start without his GO quoted in his own words with the time he said it, and writes those words to the build log. It refuses if another supervisor is already sending this country, or if a stop file from an earlier run is still there. It runs the morning gates first (the sanctions screen fresh, every approved address proved, the inbox read for replies and bounces) and runs them again if it waited ten minutes or more for its start time, because mail keeps arriving. On battery it starts anyway and stops cleanly at a 10% floor rather than dying mid-letter. It holds the Mac awake, writes a heartbeat so a stalled run cannot impersonate a healthy one, restarts a sender that dies within seconds, and reads bounces, blocks and complaints every five minutes while the run is on. Today's pace is one letter every 30 s from one mailbox, with a 6 to 12 minute break every 12 to 18 letters, under a daily cap per mailbox. It cannot decide to send anything: the sender reads only approved drafts, and approving is a separate, deliberate act. What no software can do: open a closed lid.

How a campaign goes out safely

Sending a thousand emails is easy. The work is in what the system refuses to do — and every refusal below is enforced in code, not in someone remembering. These are the real numbers from this campaign.

6,333
Italian companies on file
Harvested from the Fedespedi, IATA, AEO and WCA registers, the open directories and the companies' own sites. Counted on 12 October 2026.
→
426
never written to, with a mailbox we proved
The never-mailed list crossed with the mailbox ledger: an address counts only when its mailbox answered that it exists. We do not guess one. A blank beats a wrong address, always.
→
212
held back before sending
Every name was read before the count was quoted: sites that are not forwarders, parked domains, shops, couriers and post offices, free-mail addresses, sites the review could not read, and members still owed a personal line. They wait for a site read, not a guess.
→
—
actually sent
— of them opened with a real person's name rather than Dear Sir/Madam.
01

Nobody can be written to twice

Up to three programs send at once (one mailbox today, three for Egypt), and a supervisor restarts any that dies. That creates a window where two copies of the same sender could exist for an instant and both pick up the same company. Rather than trust that the window is small, the rule is enforced twice: the database physically refuses a second send, and each message is claimedin a single statement before it is built.

create unique index outreach_one_send_per_address
  on outreach_drafts (lower(to_email), campaign, touch)
  where status = 'sent';

In plain terms: once a message to an address has been recorded as sent, the database will reject any attempt to record a second one. Not warn — reject. We proved it by trying: it refused.

update outreach_drafts set status = 'sending'
 where id = $1 and status = 'approved'
 returning id;

And this is the claim. Whichever program updates the row first owns that message; the other gets nothing back and moves on. There is no moment where both think it is theirs.

02

Every name has to be earned

A greeting is the first thing anyone reads, so a wrong name is worse than no name. Names come from three sources, in order of how well they are proved: a contact already on file, the company's WCA profile, or the address itself — pankaj.gupta@ is Pankaj, and nobody typed that.

The third source is where a careless version does damage. The first run of it produced "Dear Privacy,", "Dear Hello," and "Dear Cochin,". So a bare word now has to be corroborated against the 1,986 real first names already in the contact record before it counts as a person:

if (parts.length === 1 && !FIRST_NAMES.has(first)) return null;

It also caught the opposite mistake: 42 contacts are stored as "Mr. Sunil Kapoor", which would have opened 42 emails with "Dear Mr.,". Stripping the title properly gained 83 usable names.470 messages carry a name; the rest honestly say Sir/Madam.

03

The pace is arithmetic, not a guess

Google allows 2,000 recipients per account per day. Today every letter goes from one mailbox with nobody on copy, so one message is one recipient, and the day's cap is set far below the limit: pace the domain, not the list.

One letter every 30 seconds, with a 6 to 12 minute break every 12 to 18 letters, is a little over 200 letters in three and a half hours. The breaks are the sender's own rhythm, a person working through a list rather than a metronome, and it sleeps in ten-second steps so a stop file ends the wait, not just the next letter:

const stopped = () => STOP_FILE && existsSync(STOP_FILE);
let nextBreakAt = 12 + Math.floor(Math.random() * 7);
04

It stops itself when it should

A watcher reads the mailbox every five minutes while the run is on and can halt everything: it touches the stop file the sender honours between letters. It separates four failures that look identical in a summary and are not remotely the same thing.

A dead address costs one wasted message and tells Google nothing about us; every scraped list has them. Apolicy rejection is a receiving network saying it does not trust the sender, and that damages the domain the company runs its shipments on. So the thresholds are separate, and read from each bounce's own diagnostic, per recipient, never by counting:

policy    - 5.7.x, 4.7.x, or a diagnostic naming spam, a blocklist or reputation.
            ONE is a stop: a receiving network has started judging the domain.
hard      - the address does not exist. max(3, 5% of sent) is a stop: the list is bad.
soft      - mailbox full, temporary. Counted, never a stop.
complaint - spam / unsolicited / GDPR / a data-protection authority. An authority
            named, or two complaints of any kind, is a stop.

They were split after an Egypt night when one number for everything halted a healthy campaign at 00:26 on a bounce rate of 8%: every failure was a dead address and not a single message had been blocked as spam. Before that, Vietnam bounced 121 of 559 and nothing stopped it at all. That is the version running now.

05

A send that is not recorded did not happen

The moment a message leaves, three things have to be written: the message is marked sent, a dated line is added to that company's timeline, and the relationship state moves to "emailed". They move together in one transaction, or none of them move.

This is why the counter on this page can be trusted. It is not a tally the sender keeps in memory — it is the same rows that were written inside the transmission itself. The record cannot claim a message that did not go, and cannot forget one that did.

06

The failure nobody thinks about

A Google access token lives one hour. This sender was originally written for a 30-message pilot that finished in 22 minutes, so it fetched one token at startup and never thought about it again.

At one message a minute for eight hours, that token dies at message 31 — at half past midnight, with nobody awake, and every send after it failing silently until morning. It now renews itself at the 45-minute mark, before the hour is up:

if (!tokenValue || Date.now() - tokenMintedAt > 45 * 60 * 1000) {
  tokenValue = await gmailToken();   // and it re-proves the mailbox
}

And it re-proves, every time, that the token opens the mailbox it claims to. A sender that quietly writes from the wrong account is a worse outcome than one that stops.