Skip to content

Commit 6b33427

Browse files
mayoalexanderclaude
andcommitted
fix(comms): resolve WHO a send is for before sending it, and never send without recording
A client status email went out correctly and attached to the wrong person. Both send paths resolved the recipient with a blind first-match: the CLI fallback via `?search=<addr>&per_page=1` then `rows[0]`, and the API router via `SOMLeads::findDuplicate()` ending in an unordered `->first()`. The address belonged to two leads — the NCMA record with the relationship, and a Stripe-created duplicate — and it picked the duplicate. Neither path could warn: `per_page=1` means it never learned a second row existed. (#185438, EPIC #185439) Resolution now happens ONCE, in front of the branch, and is allowed to refuse: - `resolveLeadForHandle` asks for 50 rows, filters to an EXACT address match, and returns the tie as a first-class outcome. `decideLeadMatch` is the pure half, tested against the two rows production actually returned. - Ambiguous refuses and prints every candidate with `--lead <id>` beside it. `--force` does NOT break a tie; guessing between two real people is a question only the operator can answer. - No lead refuses unless `--force`, which sends unattributed and says so. - The resolved id is passed to the router as `to_lead_id`, so the API never runs its own resolver. One CLI fix closes both paths — and fixing only the fallback I had blamed would have shipped a change that fixed nothing. And nothing sends without the ledger hearing about it: - `recordDirectSend` takes the resolved id instead of guessing one. - Any send that does not land in lead_comms — a record POST that fails, a router that returns no comm id, a `--force` send with no lead — is appended to ~/.iris/comms-unlogged.jsonl. Printing the failure was not enough: the line scrolls past and the send is then missing from the ledger with nothing anywhere that remembers. - `iris mail audit` lists them and `--backfill` writes them to their leads. It is complete going forward and honest about the past: sends made before the spool existed left no trace, and implying otherwise would be the same false assurance in a new place. Verified against production, not fixtures: the real ambiguous address resolves to `ambiguous` with both leads named; an unknown address resolves to `none`; the spool round-trips; and the backfiller repaired the actual incident, moving the email onto lead anomalyco#10394 as comm anomalyco#5603. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FEVuQjtBdw2Mq3EpE56GFY
1 parent 62c2ef8 commit 6b33427

3 files changed

Lines changed: 438 additions & 33 deletions

File tree

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { decideLeadMatch } from "./comms-send"
3+
4+
/**
5+
* The rows /api/v1/[email protected] actually returned on 2026-09-14.
6+
* Two leads, one address. The old resolvers took rows[0] and a client status email landed on
7+
* the Stripe duplicate instead of the record carrying the relationship (#185438, EPIC #185439).
8+
*/
9+
const ROWS = [
10+
{ id: 21623, name: "Rodney Damond Mayo", email: "[email protected]", source: "stripe_subscription" },
11+
{ id: 10394, name: "Rodney Mayo", email: "[email protected]", source: null },
12+
]
13+
14+
describe("decideLeadMatch", () => {
15+
test("refuses a tie instead of picking the first row", () => {
16+
const r = decideLeadMatch(ROWS, "[email protected]")
17+
expect(r.reason).toBe("ambiguous")
18+
expect(r.ok).toBe(false)
19+
expect(r.leadId).toBeUndefined()
20+
// Both candidates are returned, because the operator is the only one who can break the tie.
21+
expect(r.matches.map((m) => m.id).sort()).toEqual([10394, 21623])
22+
})
23+
24+
test("resolves when exactly one lead owns the address", () => {
25+
const r = decideLeadMatch([ROWS[1]], "[email protected]")
26+
expect(r.reason).toBe("ok")
27+
expect(r.leadId).toBe(10394)
28+
})
29+
30+
test("reports none rather than guessing when nobody owns it", () => {
31+
const r = decideLeadMatch(ROWS, "[email protected]")
32+
expect(r.reason).toBe("none")
33+
expect(r.matches).toHaveLength(0)
34+
})
35+
36+
test("ignores fuzzy search hits that do not actually hold the address", () => {
37+
// ?search= matches names and notes too, so a row can come back without the address on it.
38+
const noisy = [{ id: 999, name: "Rodney's assistant", email: "[email protected]" }, ROWS[1]]
39+
const r = decideLeadMatch(noisy, "[email protected]")
40+
expect(r.reason).toBe("ok")
41+
expect(r.leadId).toBe(10394)
42+
})
43+
44+
test("matches case-insensitively and on contact_info.email", () => {
45+
const rows = [{ id: 77, name: "Alt", contact_info: { email: "[email protected]" } }]
46+
const r = decideLeadMatch(rows, "[email protected]")
47+
expect(r.reason).toBe("ok")
48+
expect(r.leadId).toBe(77)
49+
})
50+
51+
test("an empty result set is 'none', not a crash", () => {
52+
expect(decideLeadMatch([], "[email protected]").reason).toBe("none")
53+
})
54+
})

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

Lines changed: 189 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,17 @@ export function describeSend(r: RouterSendResult): string {
123123
}
124124

125125
export interface RecordSendInput {
126-
/** Recipient handle — an email address for apple_mail. Resolved to a lead to find the ledger row. */
126+
/** Recipient handle — an email address for apple_mail. Kept for the spool, not for resolution. */
127127
toHandle: string
128+
/**
129+
* WHICH lead this belongs to. Required, and resolved by the CALLER before anything is sent.
130+
*
131+
* This used to be discovered here, with `?search=<handle>&per_page=1` and `rows[0]`. On
132+
* 2026-09-14 that put a client email on a Stripe-created duplicate of the client — and it
133+
* could not have warned, because per_page=1 means it never learned a second row existed.
134+
* An instrument that asks for one answer cannot discover that the question was ambiguous.
135+
*/
136+
leadId: number
128137
channel: string
129138
subject?: string
130139
message: string
@@ -154,25 +163,7 @@ export interface RecordSendResult {
154163
* the second with it.
155164
*/
156165
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-
}
166+
const leadId = input.leadId
176167

177168
try {
178169
const res = await irisFetch("/api/v1/atlas/comms/log", {
@@ -199,3 +190,181 @@ export async function recordDirectSend(input: RecordSendInput): Promise<RecordSe
199190
return { ok: false, leadId, error: `could not reach the comms API: ${err?.message ?? err}` }
200191
}
201192
}
193+
194+
// ─────────────────────────────────────────────────────────────────────────────
195+
// WHO is this for — answered ONCE, in front of the send
196+
// ─────────────────────────────────────────────────────────────────────────────
197+
198+
export interface LeadMatch {
199+
id: number
200+
name?: string
201+
email?: string
202+
source?: string
203+
}
204+
205+
export interface LeadResolution {
206+
/** true only when exactly one lead owns this handle. */
207+
ok: boolean
208+
leadId?: number
209+
/** Every exact match found — 0, 1, or the tie that must be broken by hand. */
210+
matches: LeadMatch[]
211+
reason: "ok" | "none" | "ambiguous" | "error"
212+
error?: string
213+
}
214+
215+
/**
216+
* Resolve a recipient handle to exactly one lead, or refuse and show the candidates.
217+
*
218+
* Three things this does that the two resolvers it replaces did not:
219+
*
220+
* 1. Asks for MANY rows. `per_page=1` cannot report a tie; it returns the tie's winner and no
221+
* evidence that there was one.
222+
* 2. Filters to an EXACT address match. `?search=` is fuzzy and matches names and notes, so a
223+
* "match" could be someone who merely mentions the address.
224+
* 3. Returns the ambiguity as a first-class outcome instead of picking. Both previous callers
225+
* ended in an unordered `->first()` / `rows[0]`, which is a coin toss wearing a result's
226+
* clothes.
227+
*/
228+
export async function resolveLeadForHandle(handle: string): Promise<LeadResolution> {
229+
const needle = handle.trim().toLowerCase()
230+
if (!needle) return { ok: false, matches: [], reason: "error", error: "empty recipient" }
231+
232+
let rows: any[] = []
233+
try {
234+
const res = await irisFetch(`/api/v1/leads?search=${encodeURIComponent(handle)}&per_page=50`)
235+
if (!res.ok) {
236+
return { ok: false, matches: [], reason: "error", error: `leads API returned ${res.status}` }
237+
}
238+
const payload = (await res.json().catch(() => null)) as any
239+
const data = payload?.data?.data ?? payload?.data ?? []
240+
rows = Array.isArray(data) ? data : []
241+
} catch (err: any) {
242+
return { ok: false, matches: [], reason: "error", error: `could not reach the leads API: ${err?.message ?? err}` }
243+
}
244+
245+
return decideLeadMatch(rows, handle)
246+
}
247+
248+
/**
249+
* The decision, separated from the fetch so it can be tested with the rows production returned.
250+
*
251+
* This is where the defect lived. Both previous resolvers took the first row of a query — one
252+
* with `per_page=1`, one with an unordered `->first()` — so "which lead?" was answered by sort
253+
* order. The rule now: an EXACT address match, and a count, and a tie is a distinct outcome
254+
* rather than a winner.
255+
*/
256+
export function decideLeadMatch(rows: any[], handle: string): LeadResolution {
257+
const needle = handle.trim().toLowerCase()
258+
259+
const emailsOf = (r: any): string[] =>
260+
[r?.email, r?.contact_info?.email, ...(Array.isArray(r?.contact_info?.emails) ? r.contact_info.emails : [])]
261+
.filter((e: any) => typeof e === "string" && e)
262+
.map((e: string) => e.trim().toLowerCase())
263+
264+
const matches: LeadMatch[] = (Array.isArray(rows) ? rows : [])
265+
.filter((r) => emailsOf(r).includes(needle))
266+
.map((r) => ({ id: Number(r.id), name: r.name, email: r.email, source: r.source }))
267+
268+
if (matches.length === 1) return { ok: true, leadId: matches[0].id, matches, reason: "ok" }
269+
if (matches.length === 0) return { ok: false, matches, reason: "none" }
270+
return { ok: false, matches, reason: "ambiguous" }
271+
}
272+
273+
/**
274+
* The local ledger of sends the remote ledger does not have.
275+
*
276+
* `recordDirectSend` fixed the path forward and could not fix the past: it cannot find sends
277+
* that went out before it existed, or ones where the mail left and the record POST then failed.
278+
* There was no sweep, so the size of that gap was unknown — and an unknown gap in an audit trail
279+
* is indistinguishable from no gap. Every send that goes out without landing in lead_comms now
280+
* writes a line here, and `iris mail audit` is what reads it back.
281+
*/
282+
export interface UnloggedSend {
283+
at: string
284+
channel: string
285+
to: string
286+
subject?: string
287+
message: string
288+
leadId?: number
289+
reason: string
290+
origin?: string
291+
}
292+
293+
export function unloggedSpoolPath(): string {
294+
const home = process.env.HOME || process.env.USERPROFILE || "."
295+
return `${home}/.iris/comms-unlogged.jsonl`
296+
}
297+
298+
export async function spoolUnlogged(entry: UnloggedSend): Promise<string | null> {
299+
try {
300+
const fs = await import("node:fs/promises")
301+
const path = unloggedSpoolPath()
302+
await fs.mkdir(path.replace(/\/[^/]+$/, ""), { recursive: true })
303+
await fs.appendFile(path, JSON.stringify(entry) + "\n", "utf8")
304+
return path
305+
} catch {
306+
// A spool that cannot be written must not swallow the send report; the caller still prints
307+
// the loud SENT BUT NOT LOGGED line, which is the part that matters.
308+
return null
309+
}
310+
}
311+
312+
export async function readUnlogged(): Promise<UnloggedSend[]> {
313+
try {
314+
const fs = await import("node:fs/promises")
315+
const raw = await fs.readFile(unloggedSpoolPath(), "utf8")
316+
return raw
317+
.split("\n")
318+
.filter((l) => l.trim())
319+
.map((l) => {
320+
try {
321+
return JSON.parse(l) as UnloggedSend
322+
} catch {
323+
return null
324+
}
325+
})
326+
.filter((e): e is UnloggedSend => e !== null)
327+
} catch {
328+
return []
329+
}
330+
}
331+
332+
/** Remove spool lines that have since been logged, identified by their `at` timestamps. */
333+
export async function clearUnlogged(timestamps: string[]): Promise<void> {
334+
const keep = (await readUnlogged()).filter((e) => !timestamps.includes(e.at))
335+
try {
336+
const fs = await import("node:fs/promises")
337+
await fs.writeFile(unloggedSpoolPath(), keep.map((e) => JSON.stringify(e)).join("\n") + (keep.length ? "\n" : ""), "utf8")
338+
} catch {
339+
/* best effort — a spool we cannot rewrite still reports correctly, just repeatedly */
340+
}
341+
}
342+
343+
/** Write one comm row against a known lead. Shared by the send path and the backfiller. */
344+
export async function logComm(input: {
345+
leadId: number
346+
channel: string
347+
subject?: string
348+
message: string
349+
sentAt?: string
350+
}): Promise<{ ok: boolean; commId?: number | null; error?: string }> {
351+
try {
352+
const res = await irisFetch("/api/v1/atlas/comms/log", {
353+
method: "POST",
354+
body: JSON.stringify({
355+
lead_id: input.leadId,
356+
channel: input.channel,
357+
direction: "outbound",
358+
body: input.message,
359+
subject: input.subject ?? null,
360+
sent_at: input.sentAt ?? new Date().toISOString(),
361+
}),
362+
})
363+
if (!res.ok) return { ok: false, error: `comms/log returned ${res.status}` }
364+
const payload = (await res.json().catch(() => null)) as any
365+
const record = payload?.data?.record ?? payload?.data ?? null
366+
return { ok: true, commId: record?.id ?? null }
367+
} catch (err: any) {
368+
return { ok: false, error: `could not reach the comms API: ${err?.message ?? err}` }
369+
}
370+
}

0 commit comments

Comments
 (0)