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');