TypeSafe Jev — Rental Chat Message Check
Every person-typed rental chat message is judged by TypeSafe Jev for scam signs and early off-platform contact while it is sent, with a 2s limit. The message is always delivered; only the receiver sees a warning, and admins get a Chat findings page with review, ban and suspend actions.
- Predecessor Builds on the 2026-09-23 TypeSafe Jev listing check (shared client, J13 naming, J14 display text, J21 code contract)
- New ADR 0066
- Status Approved
Summary
TypeSafe Jev reads every person-typed rental chat message while it is sent, and looks for scams and early off-platform contact. The message is always delivered. Only the receiver sees a warning, and admins get a "Chat findings" page to review, ban or suspend.
- Status
- Approved in brainstorming (2026-09-24); grill reviewed (2026-09-24)
- Builds on
- Jev listing check (
2026-09-23-typesafe-jev-listing-check-design): shared client, J13 naming, J14 display text, J21 code contract - Related
- Slice 2 — Viewings (contact reveal on confirm); ADR-0066 (raw chat text privacy trade-off); CONTEXT.md — Check Finding
Why
Viewing-request threads are free text between a tenant and a landlord. Today SendMessage checks length, sender and thread writability, then saves.
Nothing reads the text and no admin sees it.
Scams (诈骗)
money loss- "Bank in RM300 booking fee first, then I show you."
- "I'm in Singapore, I will courier the keys after payment."
- A victim loses real money.
Leaving the platform early
before confirm- "wasap me 012 345 6789" before the viewing is confirmed.
- Slice 2 promises the platform, not WhatsApp, holds the record.
- A regex misses "wasap", "zero one two…", and numbers split across two messages.
Jev is the second rental use of TypeSafe after the listing check. It reuses the merged shared client
(internal/shared/infrastructure/typesafe/) and call log.
What this change delivers
- Every person-typed chat message is judged by Jev while it is sent, with a 2s limit. The message is always delivered; Jev never blocks.
- The receiver sees a warning under a message with findings. The sender never does.
- Admins get a Chat findings page with thread context and actions: mark reviewed, mark false alarm, ban sender, and suspend listing (landlord senders only).
- A small sweep re-checks messages Jev could not check, for 24 hours.
Decisions
When is the message checked?
Synchronously in the send path, before the insert, with a 2s total deadline (same as J19). On failure the message is saved as not_checked.
Hard rule: the receiver never sees a message before its check attempt ends (done or not_checked).
Any gap between save and check lets the victim read the scam before the warning appears.
Rejected: a background job after send (victim reads first); save first, then check in the request (receiver can load the thread during the 2s call).
| # | Decision | Choice |
|---|---|---|
| M1 | Goal | Catch scams and early off-platform contact (both, one call) |
| M2 | On a finding | Deliver the message; warn the receiver; list it for admins. No hold, no sender-side warning |
| M3 | When to check | Synchronously in the send path, before the insert, 2s total deadline (same as J19); on failure save as not_checked. Hard rule: the receiver never sees a message before its check attempt ends (done or not_checked) |
| M4 | Checks | Three Noul questions: money before viewing, remote landlord, off-platform contact |
| M5 | Context | New message + the last 5 earlier messages in the thread, each with sender role; only the new message is judged |
| M6 | Privacy | Send raw text. Masking digits/emails is deferred until privacy becomes an issue. Launch gate: disclosure must cover raw text to TypeSafe and admin review of messages with findings with up to 5 earlier messages. See ADR-0066 |
| M7 | Admin actions | Mark reviewed, mark false alarm, ban sender (existing Better Auth ban), suspend listing (existing; landlord senders only). Ban/suspend never set review_status |
| M8 | Storage | New columns on rental_messages, not a new table |
| M9 | Switch | New TYPESAFE_RENTAL_CHAT_ENABLED; chat check runs only when it and TYPESAFE_RENTAL_ENABLED are on |
| M10 | Retry | Sweep re-checks not_checked messages younger than 24h; older ones stay not_checked forever |
| M11 | Who sees findings | Receiver only, until an admin marks false_alarm. Sender never (it would teach a scammer what to avoid) |
| M12 | Contact check scope | chat_off_platform_contact is asked only while viewing_stage = not_confirmed |
| M13 | Naming | "Finding", not "flag" (J13), in UI and code. Page title and sidebar link: "Chat findings"; prose: "message with findings". "Flag" stays reserved for Duplicate Flag (CONTEXT.md) |
Rejected alternatives
| Alternative | Why not |
|---|---|
| Hold messages with findings for admin approval | Stops the chat for hours; a false positive hurts an honest user; breaks "Jev warns, never blocks without a human option" |
| Warn the sender before sending | A scammer clicks "send anyway"; adds friction to every honest sender |
| Check after send in a background job | The victim reads the scam before the warning appears |
Save first, then check in the request (not_checked → SaveCheckResult) | Same gap in small: the receiver can load the thread during the 2s call and see the message with no warning. Breaks the M3 hard rule |
New table rental_message_checks | A message never changes, so one result per row forever; a table only adds a join on every thread load |
| One shared table for all Jev checks | Reopens the approved listing-check design |
| Whole thread as context | Cost grows with the thread; long threads hit the 32k token limit |
Reuse TYPESAFE_RENTAL_ENABLED alone | Chat is more private than a listing; it needs its own privacy OK and calibration before it goes on |
| Listing-check queue machinery (claim token, generation, attempt counter) | A message never changes and a duplicate Jev call costs < RM0.0001; a conditional save is enough |
Provisional assumptions
- TypeSafe outages are rare and short, so no circuit breaker (§5.6).
- Concurrent sends on one thread are rare, so no thread lock (§5.6).
- Threads stay small, so loading the whole thread to take the last 5 is cheap (§5.3).
ChatNoulThreshold = 0.7is a starting guess until calibration (§6.3, §6.4).- TypeSafe resists the §6.4 prompt-injection cases; if not, the switch stays off.
Scope — which messages are checked
rental_messages is written from several places. Only person-typed text is checked.
| Writer | Checked? |
|---|---|
ViewingRequestUseCase.SendMessage | ✅ |
ViewingRequestUseCase.Create — the optional first message (in.Message) | ✅ |
System lines in viewing_request.go (Counter, Propose), offer.go, agreement.go | ❌ stay skipped through the repository default (§5.4); no change in these callers |
| Offer lines carrying "Special conditions: …" | ❌ offers ask for deposits legitimately; special-conditions checking is a separate idea (#7) |
Backend
Configuration
Add to the TypeSafe block in internal/shared/infrastructure/config/config.go:
| Variable | Default | Meaning |
|---|---|---|
TYPESAFE_RENTAL_CHAT_ENABLED | false | Rental chat check switch |
TYPESAFE_RENTAL_ENABLED and TYPESAFE_RENTAL_CHAT_ENABLED are true.Port and adapter
New port in application/port/ports.go, beside ListingJudge:
// MessageJudge evaluates one chat message, read with its earlier messages.
type MessageJudge interface {
Judge(ctx context.Context, in MessageJudgeInput) ([]entity.Finding, error)
}
type MessageJudgeInput struct {
MessageID string
NewMessage JudgedMessage
Earlier []JudgedMessage // oldest first, at most 5
ViewingStage string // not_confirmed | confirmed_upcoming | viewing_done
}
type JudgedMessage struct {
SenderRole string // tenant | landlord
Text string
}
Adapter adapter/outbound/typesafe/message_judge.go, beside listing_judge.go:
- Calls
Client.JudgewithCaller{App: "rental", Feature: "message_check", RefID: MessageID}, so every call lands intypesafe_calls. - Builds the state (§6.1) and the questions (§6.2). Omits
chat_off_platform_contactunlessViewingStage == "not_confirmed"(M12). - Returns only answers with p ≥
ChatNoulThreshold(§6.3) asentity.Finding{Code, P}, reusing the listing check'sFindingtype (entity/postcode.go).Fieldstays empty andScorenil for chat findings.
Wiring in module.go follows listingJudge: a WithMessageJudge option for tests; otherwise built from the shared client when both switches and the key are set; else nil (nil = no check).
Send flow
In SendMessage and the first-message branch of Create, after the existing validation and before the insert:
- If the judge is nil (switch off) →
check_status = 'skipped'. - Else load the last 5 messages of the request (
ListByRequestID, take the tail), map sender ids totenant/landlord, deriveviewing_stage, and call the judge undercontext.WithTimeout(ctx, 2s). - Success →
check_status = 'done',check_findings= returned findings (may be empty),checked_at = now. - Error or deadline →
check_status = 'not_checked', empty findings. Log a zap warning. The send still succeeds. - Insert the message as today.
viewing_stage is derived from our data, never from Jev:
viewing_stage | Rule |
|---|---|
not_confirmed | confirmed_time IS NULL |
confirmed_upcoming | confirmed_time > now |
viewing_done | confirmed_time <= now |
Columns on rental_messages
Migration in internal/shared/infrastructure/database/postgresql/migrations/migrator_rental.go (the migrator is the schema source of truth).
| Column | Type | Notes |
|---|---|---|
check_status | text not null default 'skipped' | skipped / not_checked / done. The default covers old rows and direct SQL inserts; new rows, including system lines, get skipped from the repository mapper |
check_findings | jsonb not null default '[]' | [{code, p}] with p ≥ threshold |
checked_at | timestamptz null | When Jev answered |
review_status | text null | null / reviewed / false_alarm |
reviewed_by | text null | Admin user id |
reviewed_at | timestamptz null |
Indexes:
- Partial index for the admin list:
(created_at DESC) WHERE check_findings <> '[]'::jsonb. - Partial index for the sweep:
(created_at DESC) WHERE check_status = 'not_checked'.
entity.Message gains CheckStatus, CheckFindings, CheckedAt, ReviewStatus, ReviewedBy, ReviewedAt.
not_checked rows older than 24h stay not_checked; review applies only to done rows with findings.- One shared entity →
messageModelmapper setscheck_status = 'skipped'whenCheckStatusis empty andcheck_findings = '[]'whenCheckFindingsis nil, and copies all check fields otherwise. - Both insert paths use it:
MessageRepository.Createand the initial-message insert insideViewingRequestRepository.Create(which builds its ownmessageModeltoday and would otherwise drop the first message's check result). - The column defaults still cover older rows and direct SQL inserts.
MessageRepository gains:
SaveCheckResult(ctx, id, findings) (bool, error)UPDATE … SET check_status='done', check_findings=?, checked_at=now() WHERE id=? AND check_status='not_checked'. False = someone else saved first.ListNotChecked(ctx, since time.Time, limit int)- Feeds the retry sweep.
ListWithFindings(ctx, filter)- Feeds the admin Chat findings list.
Review(ctx, id, status, adminID)- Sets
review_status,reviewed_by,reviewed_at.
Retry sweep
MessageCheckSweepUseCase, run on the shared scheduler.RunPeriodic every 5 minutes, started beside the listing-check sweep.
-
Check switches
Each tick checks both switches first (like J15); off → do nothing.
-
Load, newest first
At most 20
not_checkedmessages withcreated_at > now - 24h, newest first. A fresh message matters most: the victim is still in the conversation. -
Rebuild the input
Earlier= the 5 messages withcreated_atbefore this message.viewing_stagecomes from the request's currentconfirmed_timecompared with the message'screated_at. -
Judge one by one
30s deadline each (listing-check background deadline). A judge failure on one row logs a zap warning and continues to the next row. Only a database error ends the tick.
-
Save
With
SaveCheckResult. Thecheck_status='not_checked'guard makes a double save by two replicas harmless. Failure leaves the rownot_checked; the next tick tries again until 24h pass.
| Current state of the request | viewing_stage used by the sweep |
|---|---|
| Not confirmed now | not_confirmed |
Confirmed now and confirmed_time > created_at | confirmed_upcoming |
| Confirmed now, otherwise | viewing_done |
Edge cases
| Case | Behaviour |
|---|---|
Admin marks false_alarm, later a sweep would re-check | Cannot happen: only not_checked rows are swept, and review happens on done rows |
| TypeSafe slow or down | Every chat send waits up to the full 2s, then saves not_checked; the sweep checks it later. No circuit breaker: add one only if logs show real outages |
| Switch turned off mid-flight | An in-flight call may finish and save; no new calls |
| Switch turned on | Old messages stay skipped; nothing is back-filled |
| Message body up to 2000 runes + 5 earlier | ~12k runes max, well under 32k tokens |
| Split number sent as two messages, one after another | Caught: the first send commits before the second send starts, so the second judge sees it in earlier_messages |
| Two sends on the same thread at the same time (two tabs, fast double send) | Known limitation: neither judge sees the other message. No lock, no change to delivery in this slice |
| Prompt injection gets past Jev | A missed finding, not a crash: the message is delivered with no receiver warning. Checked before launch by the §6.4 injection cases; no local keyword filter |
| Sender is also admin | No special case |
| Banned sender | Existing Better Auth ban blocks their next request; old messages stay visible |
Questions and threshold
State
{
"new_message": { "sender": "landlord", "text": "..." },
"earlier_messages": [
{ "sender": "tenant", "text": "..." },
{ "sender": "landlord", "text": "Counter-proposed 2 alternate viewing times" }
],
"viewing_stage": "not_confirmed"
}
No names, user ids, phone numbers from contact records, or listing address are added. The message text itself is sent raw (M6).
Jev questions (all Noul)
| Code | Question | Yes | No (traps) |
|---|---|---|---|
chat_money_before_viewing |
Does new_message, read with earlier_messages, ask the other person to pay or transfer money (deposit, booking fee, holding fee, key fee) before they have seen the unit in person? |
"Bank in RM300 booking fee first, then I show you" | "Deposit is 2+1 after we sign"; "Rent is RM1,800"; tenant asking "how much is the deposit?" |
chat_remote_landlord |
Does new_message say the landlord or agent cannot meet in person or cannot show the unit — for example they are abroad, or keys will be posted or couriered? |
"I'm in Singapore, I will courier the keys" | "My agent will show you on Saturday"; "I'm busy Saturday, can Sunday?" |
chat_off_platform_contact |
Does new_message, read with earlier_messages, share a phone number, WhatsApp, Telegram, WeChat or email, or ask to continue the conversation outside this platform? Count spelled-out or split numbers. |
"wasap me 012 345 6789"; "zero one two…" continuing an earlier "can wasap me" | "I'll reply here tonight"; system lines such as "Tenancy agreement issued." |
Only asked when viewing_stage = not_confirmed: chat_off_platform_contact (M12).
Threshold
Calibration — before the chat switch goes on
- New command
backend/go/cmd/eval-message-check, modelled oncmd/eval-listing-check. - Runs ~30 hand-written synthetic chats by default: English, Malay, Chinese, Manglish; the §6.2 traps; split-number cases. Never reads real chats unless an explicit opt-in flag is passed, gated on the ADR-0066 confirmation.
- Prints each probability for labelling; the threshold is set from the labels.
- If Malay results are poor,
TYPESAFE_RENTAL_CHAT_ENABLEDstays off.
API
| Endpoint | Change |
|---|---|
GET /api/rental/viewing-requests/:id/messages (existing) | Each message gains warnings: string[] (finding codes). Filled only when the caller is not the sender and review_status is not false_alarm; otherwise []. Raw check_* and review_* fields are not exposed to parties |
POST /api/rental/viewing-requests/:id/messages (existing) | Response gains warnings, always []: the caller is the sender |
GET /api/rental/admin/messages?findings=open|all (new, admin group) | Messages with non-empty findings, newest first, paginated like the admin listings list. open = review_status IS NULL. Each row: message, findings with p, sender id + name + role, request id, listing id + title, and the 5 earlier messages |
POST /api/rental/admin/messages/:id/review (new, admin group) | Body {status: "reviewed" | "false_alarm"}; sets reviewed_by, reviewed_at. 404 if the message has no findings |
The admin routes sit on the existing protected.Group("/admin", RequireJWTRole(admin, superadmin)).
Frontend
Rental app — MessageThread.tsx
- Under each message with non-empty
warnings, an amber box with one line per code. - No button; the message is never hidden or collapsed.
- Text is static Paraglide messages keyed by code (J14), in en / ms / zh.
| Code | English |
|---|---|
chat_money_before_viewing | Never pay any money before you have seen the unit in person. |
chat_remote_landlord | Be careful: the other person says they cannot meet you. Don't pay for keys sent by post. |
chat_off_platform_contact | Keep chatting here until the viewing is confirmed. Your messages here are your record. |
An unknown code renders nothing (the golden-vector test prevents this in practice).
Panel — /admin/rental/messages
- New route
apps/panel/src/routes/admin/rental/messages/index.tsx, glassmorphism panel style (panel-ui-style). - Table: time, sender name + role, message text, finding chips with p, listing. Filter toggle Open / All.
- Row click opens a side panel: the 5 earlier messages + the message with findings, and the actions below.
- Sidebar link "Chat findings" with the open count, in
apps/panel/src/app.tsx. - Finding chip text: panel's own Paraglide map (J14).
| Action | Calls |
|---|---|
| Mark reviewed | POST /admin/messages/:id/review {status:"reviewed"} |
| Mark false alarm | POST /admin/messages/:id/review {status:"false_alarm"} |
| Suspend listing | Existing POST /admin/listings/:id/suspend. Shown only when the sender is the landlord; a tenant's message never puts the landlord's listing one click from suspension. UI only, no new backend guard |
| Ban sender | Existing ban modal via useAdminBanUser, reason pre-filled Chat scam: <finding> |
Privacy
Testing
| Area | Test |
|---|---|
| Send | Judge returns findings → done, only p ≥ ChatNoulThreshold stored. Judge exceeds 2s → not_checked, message saved, send returns 200. Either switch off → skipped, judge not called |
| First message | Create with in.Message is judged before the request transaction, with empty earlier messages and not_confirmed; the stored row keeps check_status / check_findings from the judge |
| Split number | Two sequential SendMessage calls ("wasap me 012 345", then "6789"): the second judge input holds the first message in Earlier |
| System lines | Repository round-trip: a message created with no check fields reads back as skipped + []. Thread assertion: after an offer, the offer line is present in ListMessages (callers ignore the insert error, so a failed insert would vanish silently) |
| State | chat_off_platform_contact not asked for confirmed_upcoming / viewing_done. Earlier messages capped at 5, oldest first, with roles |
| Sweep | Re-checks not_checked < 24h; ignores ≥ 24h; no-op when a switch is off; second SaveCheckResult returns false and changes nothing; 20 always-failing old rows + 1 good new row → one tick checks the new row; one row's judge failure does not stop the tick; Earlier = 5 messages before the message's created_at; message sent before confirmation but swept after it → confirmed_upcoming/viewing_done, contact question not asked, scam questions asked |
| Read | Receiver gets warnings; sender gets []; false_alarm gives [] to both. Sender POSTs a message the judge flags → POST response warnings: []; receiver GET → holds the code |
| Admin | open / all filter; review stores who and when; 404 on a message without findings; non-admin gets 403 |
| Code contract | Golden vector (J21): every Go chat finding code has a rental en/ms/zh message and a panel message |
| Frontend | Amber box for receiver only (render test); panel row actions hit the right endpoints; a tenant-sender row has no Suspend listing button; ban modal pre-fills the reason |
| Calibration | eval-message-check runs synthetic cases only by default; the case set includes English and Malay prompt-injection cases |
No test calls the real TypeSafe API in CI. Rental Go tests run with -p 1 against pg-test (see backend/go/AGENTS.md).
Out of scope
- Masking digits and emails before sending (deferred; see ADR-0066)
- Warning the sender before they send
- A new user-ban feature (reuse Better Auth ban)
- Checking offer special-conditions text (idea #7)
- Email or push alerts to admins
- Audit log of admin views of threads with findings (
reviewed_by/reviewed_atrecord actions only; see ADR-0066) - Re-checking messages older than 24h, or back-filling existing messages
- Admin screen for the switches