Fuzzy name matching that never books money on a guess
Short answer. When a name decides where money is booked, fuzzy matching may only ever narrow the choice; it may not make it. In KhataGO the rule is three lines: an exact name books, one confident fuzzy match books the entry held for a person to check, and more than one candidate books nothing and asks the shopkeeper to pick. The hard part was not the matcher. It was making sure the entry could not get booked a second way while the question was open, and a review found two ways it could.
Status, so nobody is misled: this is unreleased work. It lives on a review branch (commits bf8a354 and 5bdf61e), is not merged and is not deployed. Both bugs below were found in review, before the branch shipped anywhere.
The problem: one customer, five spellings
KhataGO is a WhatsApp bookkeeping app. A shopkeeper texts "Ramesh 500 udhaar" and Gemini, through function calling, turns it into a receivable for Ramesh. The tools take the party as free text (the model's partyName), and until this branch the rule was exact-or-create: the name matched a saved contact ignoring case, or a new contact was created.
That rule is safe and wrong. The same customer arrives as Ramesh, Rameshbhai, Rameshe, રમેશ in Gujarati and रमेश in Devanagari, depending on who typed and on which keyboard. Under exact-or-create each spelling becomes its own party, and one customer's dues are split across several ledgers.
The opposite mistake is worse. Most small shops have two Rameshes. A matcher that confidently picks one books a real customer's debt against the wrong real person, and that is a dispute, not a typo.
The matcher, briefly
All of it is in lib/rules/party.ts, it is pure, and it only ever compares against the shop's own contacts (at most 2,000, loaded in memory). Four steps:
- Transliterate. Gujarati and Devanagari letters map to Latin. The Gujarati Unicode block repeats the Devanagari layout 0x180 higher, so one table serves both:
રમેશandरमेशboth read asramesh. - Fold spellings. One spelling per sound: vowel length (
aa→a), aspiration (bh→b),sh/s,w/v, doubled letters. - Drop honorifics, including the ones written glued on:
Rameshbhai,હેતલબેન. - Score tokens with Jaro–Winkler, with guards that make it stricter than the textbook version.
The guards are where the domain lives:
export function tokenScore(a: string, b: string): number {
if (a === b) return 1;
const [short, long] = a.length <= b.length ? [a, b] : [b, a];
// Ram is not Ramesh, Raj is not Rajesh: a name that only starts another is another name.
if (short.length < 2 || long.length - short.length > 2 || long.startsWith(short)) return 0;
if (short.length <= 4 && long.length - short.length > 1) return 0;
// …Jaro–Winkler, with a floor when the consonant skeletons agree (મહેતા / Mehta)
}
Plain Jaro–Winkler rewards a shared prefix, which is exactly backwards for Indian first names: Ram and Ramesh share a prefix and are different people. Two more rules from the first test run: numbers and single letters must agree when both names have them ("Shop 2" is not "Shop 1", the matcher reads letters only, so it would otherwise call them equal), and a longer contact fits by its first word only when exactly one word was typed ("Ramesh" is a candidate for both Ramesh Patel and Ramesh Shah; "Ramesh Shah" is not a candidate for Ramesh Patel).
The rule: exact books, fuzzy holds, several asks
lookupPartyName returns one of four results, and every tool that writes money obeys the same table:
export type PartyLookup =
| { kind: "exact"; contact: ContactRef } // book as before
| { kind: "fuzzy"; contact: ContactRef; score: number } // book HELD, under the saved name
| { kind: "choose"; candidates: ContactRef[] } // write nothing, ask
| { kind: "none" }; // create, and say so
- exact: one contact saved under that name (case, Unicode form and spacing ignored). Booked as before.
- fuzzy: one contact only, every typed word matched at the 0.9 threshold or better, nothing doubtful. The entry is booked but held (
needsReview, or a held proposal for a payment) under the contact's saved name, and the reply names the party it went to. - choose: two or more candidates, or one doubtful one. Nothing is written and no party is created. The tool returns
PARTY_CHOICE. - none: the old behaviour, a new party, and the reply now says "New party created: X" so a typo is visible the moment it happens.
Why hold the single fuzzy match instead of booking it and saying so? Because the shopkeeper reads replies in a hurry, and a wrong party is a dispute with a real customer. A held entry costs one tap on the review desk. If held spelling matches turn out to be most of the desk's work, the switch is one term in the three writers. I would rather turn it down later with evidence than find out from an angry customer.
Reads are different. "What does Ramesh owe?" with two Rameshes does not write anything, so the model just asks which one, in words. Reminders ask too: a reminder is a message to a real person, and it goes to an exact match only.
Picking on WhatsApp, without the model
A PARTY_CHOICE reply is fixed text, not a second model call, with the candidates attached as WhatsApp reply buttons (up to three) or an interactive list (up to ten rows: at most nine parties, best first, each with the last four digits of its phone and what it owes, then "New: Ramesh").
The tap comes back as a webhook, and the model is not involved in answering it. The row id carries the message, the choice index and the contact. The server checks the message is in the tapper's own books, is at most 24 hours old, that the step really is that message's choice, and that the contact really was a candidate. Then it runs the same tool with the original arguments and the picked party, inside an idempotency key:
party-pick:<message id>:<choice index>
A redelivered webhook, a double tap, or a tap on the other row replays the first answer ("Already answered for this entry") instead of booking again. That is the same claim-then-replay pattern as in idempotency keys for payment APIs, with the key inserted first in the same transaction as the write.
I thought that closed it. The review found two more ways to book twice.
Bug 1: the model booked it anyway, and then the list was sent
A plain entry gets the fixed choice text and no second model turn. But take a message that is an entry and a question:
Ramesh ne 500 vechyu, total ketlu?
That is romanised Gujarati for "sold 500 to Ramesh, what's the total?". The model has to answer the question, so it gets a second turn after the tool returns PARTY_CHOICE. The tool result is explicit:
NOT saved yet: "Ramesh" could be Ramesh Patel, Ramesh Shah, or a new party. The user is
sent a list to pick from, and the entry is booked only when they pick. Do not book it any
other way and do not create a party; just say which entry waits for their pick.
The review asked the obvious question: what if the model ignores that and retries under one of the listed names? It scripted the model to do exactly that, calling create_transaction again with party: "Ramesh Patel", and drove it through the real signed webhook against real Postgres. Ramesh Patel is an exact name, so the sale was booked. The run then finished and the pick list was still sent, because the PARTY_CHOICE step was still there. Tapping Ramesh Patel booked a second sale. Both rows were unheld and counted in totals and exports.
The lesson I took: an instruction in a tool result is a request, not a guard. The model usually follows it. "Usually" is not a property you can put on a ledger.
The fix reads the run's own history. Every tool call the model makes in a run is already stored as a step, in order (that design is its own post: each LLM tool call at most once). So when the choices for a message are listed, each one checks whether a later step of the same run already booked the same entry:
/** `later` wrote the same entry (tool, amount) to one of `choice`'s candidates. */
function booksSameEntry(choice: StepRow, later: StepRow): boolean {
if (later.tool !== choice.tool) return false;
if (record(later.result).status !== "success") return false;
if (Number(record(later.args).amount) !== Number(record(choice.args).amount)) return false;
const { candidates } = choice.result as PartyChoiceResult;
return resolveName(typedParty(later.tool, later.args), prepareContacts(candidates)) !== null;
}
A choice that matches is marked bookedBy. No list is sent for it, and a tap on an old list answers "Already answered" with what was saved, booking nothing.
The rule leans one way on purpose. A message that genuinely holds two equal sales to two people who share a first name would have the second one closed rather than offered. The reply says what was saved, so the shopkeeper can type the missing one again. Losing an offer is recoverable from the reply. A second sale nobody meant is only found when a customer disputes the bill.
Bug 2: the typed name went into the ledger
The second bug was quieter. A picked sale stored the typed name as the transaction's party text: Ramesh, for a sale the shopkeeper had just told us was Ramesh Shah. The contact id was right; the text was not.
Two things read that text. The CSV export and the transactions list showed Ramesh for both Rameshes, so the books looked mixed even though the ids were not. And the repeat check, which holds a second identical entry within ten minutes, compares party text, so it could not see that "Ramesh Shah 300" was the same sale as the picked "Ramesh 300".
The fuzzy path already booked under the saved name. The pick path did not, and the fix was one condition in lib/ai/toolHandlers/transactions.ts:
// A spelling match or a pick books under the saved name, so the ledger shows the party it went to.
const partyText =
matched && (partyGuess || ctx.partyPick) ? matched.name : party.trim();
ctx.partyPick is set only by the tap handler. The model has no way to set it.
How the review proved them
Neither bug shows up in a unit test of the matcher, because the matcher was right both times. They live in the seams: between the model's second turn and the pick list, and between the pick and the column the export reads. So both new tests are integration tests in tests/integration/names.db.integration.test.ts: a real Postgres, the real signed WhatsApp webhook, and a scripted model whose later turns are queued in the test.
it("the model books the entry itself after PARTY_CHOICE: no list, and a tap cannot book it twice", async () => {
// …two contacts, Ramesh Patel and Ramesh Shah; turn 1 asks for "Ramesh",
// turn 2 (against the prompt) books "Ramesh Patel"
await deliver(u.phone, text("Ramesh ne 500 vechyu, total ketlu?"));
expect(await prisma.transaction.count({ where: { businessId: u.id } })).toBe(1);
expect(lastReply().interactive).toBeUndefined();
await deliver(u.phone, tap(encodePickId({ messageId: original.id, index: 0, contactId: patel.id }), "Ramesh Patel"));
expect(await prisma.transaction.count({ where: { businessId: u.id } })).toBe(1);
expect(lastReply().body.split("\n")[0]).toBe(gu.partyPick.already);
});
The second test taps the Ramesh Shah button and asserts the row is { contactId: shah.id, party: "Ramesh Shah" }. Each fails when its fix is reverted, and that was checked three times separately: the partyText line, the bookedBy detection, and the tap handler's bookedBy branch. A fix with two halves needs each half shown to matter, or one of them is decoration.
What I would tell someone building the same thing
Let fuzzy matching narrow the choice and let a person make it. A confident single match can still be wrong, so book it where a person will see it, not where it is final.
When you ask a user to choose, look for every other path that could resolve the same question while it is open: a model turn, a retry, a second tap, a redelivered webhook. Each one needs its own answer, and "the prompt says not to" is not one.
And when a choice is made, store what was chosen, not what was typed. Everything downstream reads the text.
This post describes a branch. It reaches the live product when that branch is merged, and if the held matches turn out to be noise in real use, the hold is the first thing I expect to tune.