Skip to content

Commit b4c2087

Browse files
mayoalexanderclaude
andcommitted
fix(comms): three ways the log missed real correspondence, all of them silent
A comms log that under-reports is worse than none, because it is wrong in the direction that looks like silence rather than like an error. Three defects, found by pulling one thread — an email I sent that the log never heard about. 1. `iris mail send --from/--cc/--attachment` SENT and RECORDED NOTHING. Those flags have no router path, which is a reason the send cannot be ROUTED — not a reason it cannot be LOGGED. The CLI printed "not logged to comms" and moved on, reintroducing the exact failure CR-8 removed. Transport and bookkeeping are separate: the bridge still carries those sends, `recordDirectSend` books them afterwards. Drafts excluded — nothing was sent, and logging one would put a message on someone's record they never received. A failed record says SENT BUT NOT LOGGED with the reason and the command to fix it. 2. The ingest only searched `lead.email`. Leads have one primary address and any number of alternates in contact_info.emails; everything written from an alternate was invisible. Measured on lead anomalyco#10394: 27 messages on the primary, 43 on the two alternates — 61% of the correspondence missing from a log that returned "1 new, 0 skipped". He is Apple-native and writes from iCloud; we had filed him under his work address. That is the common case for anyone with a work and a personal email, not an edge case. `leadEmails()` is now the one answer to "where is this person reachable", used by both the Apple Mail and iMessage paths. 3. The Apple Mail ingest never sent X-Bridge-Key, so every request 401'd, fell through to the Gmail fallback, and reported that as the whole answer. The Discord ingest twelve lines above has always authenticated; mail simply never did. Failures now print per address with the status code, and a 401 names the fix. Timeout 5s -> 15s, because Mail.app search over a large mailbox is slow and a timeout produced the same silent zero. Fixing #3 immediately exposed the layer beneath it, which is not a code change: the bridge answers 503 because the daemon has no Full Disk Access and cannot read Mail at all — "[mail/search] No permission to read Mail" in its own log. Grant it to ~/.iris/runtime/node-v22.11.0-darwin-arm64/bin/node. Until then the ingest says so on every run instead of returning an empty list that reads as an answer. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01FEVuQjtBdw2Mq3EpE56GFY
1 parent 2252b3d commit b4c2087

3 files changed

Lines changed: 179 additions & 21 deletions

File tree

‎packages/opencode/src/cli/cmd/comms-send.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,3 +121,81 @@ export function describeSend(r: RouterSendResult): string {
121121
const step = r.stepAdvanced ? `, completed step #${r.stepAdvanced}` : ""
122122
return `Sent via ${r.channel} — ${logged}${step}`
123123
}
124+
125+
export interface RecordSendInput {
126+
/** Recipient handle — an email address for apple_mail. Resolved to a lead to find the ledger row. */
127+
toHandle: string
128+
channel: string
129+
subject?: string
130+
message: string
131+
/** Where it went out from, for the record. */
132+
origin?: string
133+
}
134+
135+
export interface RecordSendResult {
136+
ok: boolean
137+
leadId?: number
138+
commId?: number | null
139+
/** Why nothing was written. Always set when ok is false — "it didn't log" is not an answer. */
140+
error?: string
141+
}
142+
143+
/**
144+
* Put a message that has ALREADY been sent onto the record.
145+
*
146+
* routerSend sends and books in one call, but it cannot carry attachments, cc, or a raw --from,
147+
* so those sends go out through the bridge instead. That was treated as a reason not to log them
148+
* — the CLI printed "not logged to comms" and wrote nothing — which quietly reintroduced the
149+
* exact failure CR-8 existed to remove. A send the log does not know about makes every "have we
150+
* contacted them?" answer wrong, and it is wrong in the dangerous direction: it looks like
151+
* silence.
152+
*
153+
* Transport and bookkeeping are separate concerns. The bridge can own the first without taking
154+
* the second with it.
155+
*/
156+
export async function recordDirectSend(input: RecordSendInput): Promise<RecordSendResult> {
157+
let leadId: number | undefined
158+
159+
try {
160+
const res = await irisFetch(`/api/v1/leads?search=${encodeURIComponent(input.toHandle)}&per_page=1`)
161+
if (res.ok) {
162+
const payload = (await res.json().catch(() => null)) as any
163+
const rows = payload?.data?.data ?? payload?.data ?? []
164+
const first = Array.isArray(rows) ? rows[0] : null
165+
if (first?.id) leadId = Number(first.id)
166+
}
167+
} catch (err: any) {
168+
return { ok: false, error: `could not reach the leads API: ${err?.message ?? err}` }
169+
}
170+
171+
// No lead means no ledger row to attach to. Say so plainly — the operator can create the lead
172+
// and re-log. Reporting "recorded" here would be the same lie in a different place.
173+
if (!leadId) {
174+
return { ok: false, error: `no lead matches ${input.toHandle}` }
175+
}
176+
177+
try {
178+
const res = await irisFetch("/api/v1/atlas/comms/log", {
179+
method: "POST",
180+
body: JSON.stringify({
181+
lead_id: leadId,
182+
channel: input.channel,
183+
direction: "outbound",
184+
body: input.message,
185+
subject: input.subject ?? null,
186+
sent_at: new Date().toISOString(),
187+
}),
188+
})
189+
190+
if (!res.ok) {
191+
return { ok: false, leadId, error: `comms/log returned ${res.status}` }
192+
}
193+
194+
const payload = (await res.json().catch(() => null)) as any
195+
const record = payload?.data?.record ?? payload?.data ?? null
196+
197+
return { ok: true, leadId, commId: record?.id ?? null }
198+
} catch (err: any) {
199+
return { ok: false, leadId, error: `could not reach the comms API: ${err?.message ?? err}` }
200+
}
201+
}

‎packages/opencode/src/cli/cmd/platform-atlas-comms.ts‎

Lines changed: 75 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -53,13 +53,41 @@ async function resolveLead(idOrQuery: string): Promise<{ id: number; lead: any }
5353
return { id: leadId, lead: data?.data ?? data }
5454
}
5555

56+
/**
57+
* Every email address this lead is reachable at — not just the one in the `email` column.
58+
*
59+
* A lead has ONE primary email and any number of alternates in contact_info.emails, and the
60+
* ingest only ever searched the primary. For anyone who writes from a different address than
61+
* the one we filed them under, most of the relationship was invisible to the comms log, and
62+
* invisible in the direction that looks like silence rather than like an error.
63+
*
64+
* Measured on lead #10394 (2026-09-12): 27 messages on the primary address the ingest reads,
65+
* 43 on the two alternates it did not — 61% of the correspondence missing from a log that
66+
* reported success. He is Apple-native and writes from iCloud; the address we had on file was
67+
* his work one.
68+
*/
69+
function leadEmails(lead: any): string[] {
70+
const ci = lead?.contact_info ?? {}
71+
const raw = [lead?.email, ci?.email, ...(Array.isArray(ci?.emails) ? ci.emails : [])]
72+
73+
const seen = new Set<string>()
74+
const out: string[] = []
75+
for (const e of raw) {
76+
const addr = String(e ?? "").trim().toLowerCase()
77+
if (!addr || !addr.includes("@") || seen.has(addr)) continue
78+
seen.add(addr)
79+
out.push(addr)
80+
}
81+
return out
82+
}
83+
5684
// ── iMessage ingestion (via shared lib) ──
5785

5886
function ingestImessage(lead: any): any[] {
5987
const { searchByHandle, normalizeHandle } = require("../lib/imessage")
6088
const identifiers: string[] = []
6189
if (lead.phone) identifiers.push(normalizeHandle(lead.phone))
62-
if (lead.email) identifiers.push(lead.email)
90+
for (const addr of leadEmails(lead)) identifiers.push(addr)
6391
if (lead.instagram) identifiers.push(lead.instagram.replace("@", ""))
6492

6593
if (identifiers.length === 0) return []
@@ -206,28 +234,57 @@ function ingestWhatsapp(lead: any): any[] {
206234
// ── Gmail ingestion (via bridge or integration) ──
207235

208236
async function ingestGmail(lead: any): Promise<any[]> {
209-
const email = lead.email
210-
if (!email) return []
237+
const emails = leadEmails(lead)
238+
if (emails.length === 0) return []
239+
const email = emails[0]
211240

212241
try {
213-
// Try bridge first (has full body)
214-
const res = await fetch(`${BRIDGE_URL}/api/mail/search?from=${encodeURIComponent(email)}&days=90&limit=50&include_body=1`, {
215-
signal: AbortSignal.timeout(5000),
216-
})
217-
if (res.ok) {
242+
// One search PER ADDRESS. The bridge filters on a single `from`, so a lead with alternates
243+
// needs one call each — searching only the primary is what left 61% of #10394's mail out of
244+
// the log while the command reported success. The server dedups on external_message_id, so
245+
// an address that overlaps another costs a round trip, not a duplicate row.
246+
const collected: any[] = []
247+
let anyOk = false
248+
249+
// AUTHENTICATE. The bridge requires X-Bridge-Key and this call never sent it, so every
250+
// Apple Mail ingest got a 401, fell through to the Gmail fallback, and reported whatever
251+
// that found as the whole answer. The Discord ingest in this same file has always done it
252+
// correctly — mail simply never did. A 401 here is indistinguishable from "no messages"
253+
// downstream, which is how a mailbox with 70 messages in it logged 1 and said "1 new".
254+
const bridgeToken = getBridgeToken()
255+
const bridgeHeaders: Record<string, string> = { Accept: "application/json" }
256+
if (bridgeToken) bridgeHeaders["X-Bridge-Key"] = bridgeToken
257+
258+
for (const addr of emails) {
259+
const res = await fetch(`${BRIDGE_URL}/api/mail/search?from=${encodeURIComponent(addr)}&days=90&limit=50&include_body=1`, {
260+
headers: bridgeHeaders,
261+
signal: AbortSignal.timeout(15000),
262+
})
263+
if (!res.ok) {
264+
// Say which address and why. Falling through to a lesser source without a word is what
265+
// made this invisible for months.
266+
console.log(dim(` apple_mail: ${addr} → bridge returned ${res.status}${res.status === 401 ? " (no/invalid X-Bridge-Key — run: iris bridge status)" : ""}`))
267+
continue
268+
}
269+
anyOk = true
270+
218271
const data = (await res.json()) as any
219272
const messages = data?.messages ?? []
220-
return messages.map((m: any) => ({
221-
direction: "inbound" as const,
222-
from_identifier: m.sender || m.from || email,
223-
subject: m.subject,
224-
body: m.body || m.snippet,
225-
sent_at: m.date,
226-
external_message_id: m.messageId || m.id || `mail_${m.date}_${m.subject}`,
227-
metadata: { source: "apple_mail" },
228-
channel: "apple_mail", // override — this is Apple Mail, not Gmail API
229-
}))
273+
for (const m of messages) {
274+
collected.push({
275+
direction: "inbound" as const,
276+
from_identifier: m.sender || m.from || addr,
277+
subject: m.subject,
278+
body: m.body || m.snippet,
279+
sent_at: m.date,
280+
external_message_id: m.messageId || m.id || `mail_${m.date}_${m.subject}`,
281+
metadata: { source: "apple_mail", matched_address: addr },
282+
channel: "apple_mail", // override — this is Apple Mail, not Gmail API
283+
})
284+
}
230285
}
286+
287+
if (anyOk) return collected
231288
} catch { /* bridge not running */ }
232289

233290
// Fallback: Gmail API via fl-api integration

‎packages/opencode/src/cli/cmd/platform-mail.ts‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { UI } from "../ui"
44
import { printDivider, printKV, dim, bold, success, BRIDGE_URL, bridgeFetch, writeJson } from "./iris-api"
55
import { probeWithHeal, type BridgeProbe, type BridgeHealth } from "./bridge-health"
66
import { mailRows } from "./mail-response"
7-
import { routerSend, describeSend } from "./comms-send"
7+
import { routerSend, describeSend, recordDirectSend } from "./comms-send"
88

99
// macOS Apple Mail integration via the IRIS Bridge (BRIDGE_URL, default localhost:3200)
1010
// Bridge endpoint: GET /api/mail/search?from=X&subject=X&days=N&limit=N&include_body=1&max_body=N
@@ -300,8 +300,8 @@ const MailSendCommand = cmd({
300300

301301
prompts.log.warn(
302302
args.draft
303-
? "Draft mode — composing direct via the bridge (nothing is sent, and nothing is logged to comms)."
304-
: "Attachment/cc/from set — sending direct via the bridge (not logged to comms).",
303+
? "Draft mode — composing direct via the bridge (nothing is sent, so nothing is logged)."
304+
: "Attachment/cc/from set — sending direct via the bridge (transport only; the send is recorded to comms afterwards).",
305305
)
306306

307307
const payload: any = {
@@ -333,6 +333,29 @@ const MailSendCommand = cmd({
333333
// Mail.app sent or merely opened the window.
334334
const body = (await res.json().catch(() => ({}))) as { mode?: string }
335335
const drafted = body.mode === "draft"
336+
337+
// The bridge carried it; the ledger still has to hear about it. Only for a real send — a
338+
// draft has not gone anywhere, and logging one would put a message on a lead's record that
339+
// they never received.
340+
if (!drafted) {
341+
const logged = await recordDirectSend({
342+
toHandle: args.to,
343+
channel: "apple_mail",
344+
subject: args.subject,
345+
message: args.body,
346+
origin: "cli.mail.direct",
347+
})
348+
349+
if (logged.ok) {
350+
prompts.log.info(`Recorded to comms${logged.commId ? ` as comm #${logged.commId}` : ""} on lead #${logged.leadId}`)
351+
} else {
352+
// Loud, and with the reason. The whole point of this path is that a send nobody
353+
// recorded must never again look like a send that went fine.
354+
prompts.log.error(`SENT BUT NOT LOGGED — ${logged.error}`)
355+
prompts.log.warn(`Record it by hand: iris atlas:comms log <lead> --channel apple_mail --direction outbound --message "..." --subject "${args.subject}"`)
356+
}
357+
}
358+
336359
prompts.outro(
337360
drafted
338361
? `${success("✓")} Draft opened in Mail.app for ${args.to}${attachments.length ? ` with ${attachments.length} attachment(s)` : ""} — nothing sent`

0 commit comments

Comments
 (0)