01
Claim a job
master.cron_queue, status ≠ done
created today · priority first
batch of 5 · switch to client DB
02
Mint a token
Google: RS256 JWT, impersonate
Outlook: client credentials, cached
scope gmail.readonly / .default
03
List what is new
q = after: last stored date + 60s
in:anywhere · maxResults 200
oldest first, 40 per run
04
Fetch & split
headers: Subject, From, Date, Message-ID
plain text + HTML parts
strip the quoted reply tail
read labelIds
05
Classify
gemini-2.5-flash · JSON only
503 → wait 30s → retry
still 503 → gemini-2.5-pro
token usage logged
06
Store & link
insert into messages
stamp thread root + reply
add sender to the sender list
bump the fresh-mail counter
On success the job is marked done, then reset to pending so the mailbox is polled again later the same day. On exception it is marked failed and logged.