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

View source markdown ↗ generated by claude-opus-5-5 · diagrams mermaid

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.

  • Area backend/go, frontend/solidstart/apps/rental, frontend/solidstart/apps/panel
  • Check timing In the send path, before the insert, 2s total deadline
  • Who sees findings Receiver (amber warning) + admins. Never the sender
  • Switch TYPESAFE_RENTAL_CHAT_ENABLED (default off) + TYPESAFE_RENTAL_ENABLED
  • Storage New columns on rental_messages
  • Privacy Raw chat text to TypeSafe; ADR-0066 launch gate
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.
Send path: the check attempt ends before the message is saved, so the receiver never sees an unchecked-in-progress message
Send path: the check attempt ends before the message is saved, so the receiver never sees an unchecked-in-progress message.

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).

#DecisionChoice
M1GoalCatch scams and early off-platform contact (both, one call)
M2On a findingDeliver the message; warn the receiver; list it for admins. No hold, no sender-side warning
M3When to checkSynchronously 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)
M4ChecksThree Noul questions: money before viewing, remote landlord, off-platform contact
M5ContextNew message + the last 5 earlier messages in the thread, each with sender role; only the new message is judged
M6PrivacySend 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
M7Admin actionsMark reviewed, mark false alarm, ban sender (existing Better Auth ban), suspend listing (existing; landlord senders only). Ban/suspend never set review_status
M8StorageNew columns on rental_messages, not a new table
M9SwitchNew TYPESAFE_RENTAL_CHAT_ENABLED; chat check runs only when it and TYPESAFE_RENTAL_ENABLED are on
M10RetrySweep re-checks not_checked messages younger than 24h; older ones stay not_checked forever
M11Who sees findingsReceiver only, until an admin marks false_alarm. Sender never (it would teach a scammer what to avoid)
M12Contact check scopechat_off_platform_contact is asked only while viewing_stage = not_confirmed
M13Naming"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

AlternativeWhy not
Hold messages with findings for admin approvalStops the chat for hours; a false positive hurts an honest user; breaks "Jev warns, never blocks without a human option"
Warn the sender before sendingA scammer clicks "send anyway"; adds friction to every honest sender
Check after send in a background jobThe 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_checksA 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 checksReopens the approved listing-check design
Whole thread as contextCost grows with the thread; long threads hit the 32k token limit
Reuse TYPESAFE_RENTAL_ENABLED aloneChat 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.7 is 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.

WriterChecked?
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:

VariableDefaultMeaning
TYPESAFE_RENTAL_CHAT_ENABLEDfalseRental chat check switch
Nested gates for a chat Jev call: the API key must be set, inside that the rental switch must be on, inside that the chat switch must be on. Only then is Jev called. API key set Rental switch on Chat switch on Jev call
The chat check calls Jev only when the API key is set and both 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.Judge with Caller{App: "rental", Feature: "message_check", RefID: MessageID}, so every call lands in typesafe_calls.
  • Builds the state (§6.1) and the questions (§6.2). Omits chat_off_platform_contact unless ViewingStage == "not_confirmed" (M12).
  • Returns only answers with p ≥ ChatNoulThreshold (§6.3) as entity.Finding{Code, P}, reusing the listing check's Finding type (entity/postcode.go). Field stays empty and Score nil 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:

  1. If the judge is nil (switch off) → check_status = 'skipped'.
  2. Else load the last 5 messages of the request (ListByRequestID, take the tail), map sender ids to tenant/landlord, derive viewing_stage, and call the judge under context.WithTimeout(ctx, 2s).
  3. Success → check_status = 'done', check_findings = returned findings (may be empty), checked_at = now.
  4. Error or deadline → check_status = 'not_checked', empty findings. Log a zap warning. The send still succeeds.
  5. Insert the message as today.

viewing_stage is derived from our data, never from Jev:

viewing_stageRule
not_confirmedconfirmed_time IS NULL
confirmed_upcomingconfirmed_time > now
viewing_doneconfirmed_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).

ColumnTypeNotes
check_statustext 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_findingsjsonb not null default '[]'[{code, p}] with p ≥ threshold
checked_attimestamptz nullWhen Jev answered
review_statustext nullnull / reviewed / false_alarm
reviewed_bytext nullAdmin user id
reviewed_attimestamptz 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.

Check and review states of one message. not_checked rows older than 24h stay not_checked ; review applies only to done rows with findings
Check and review states of one message. not_checked rows older than 24h stay not_checked; review applies only to done rows with findings.
  • One shared entity → messageModel mapper sets check_status = 'skipped' when CheckStatus is empty and check_findings = '[]' when CheckFindings is nil, and copies all check fields otherwise.
  • Both insert paths use it: MessageRepository.Create and the initial-message insert inside ViewingRequestRepository.Create (which builds its own messageModel today 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.

  1. Check switches

    Each tick checks both switches first (like J15); off → do nothing.

  2. Load, newest first

    At most 20 not_checked messages with created_at > now - 24h, newest first. A fresh message matters most: the victim is still in the conversation.

  3. Rebuild the input

    Earlier = the 5 messages with created_at before this message. viewing_stage comes from the request's current confirmed_time compared with the message's created_at.

  4. 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.

  5. Save

    With SaveCheckResult. The check_status='not_checked' guard makes a double save by two replicas harmless. Failure leaves the row not_checked; the next tick tries again until 24h pass.

Current state of the requestviewing_stage used by the sweep
Not confirmed nownot_confirmed
Confirmed now and confirmed_time > created_atconfirmed_upcoming
Confirmed now, otherwiseviewing_done

Edge cases

CaseBehaviour
Admin marks false_alarm, later a sweep would re-checkCannot happen: only not_checked rows are swept, and review happens on done rows
TypeSafe slow or downEvery 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-flightAn in-flight call may finish and save; no new calls
Switch turned onOld 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 anotherCaught: 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 JevA 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 adminNo special case
Banned senderExisting 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)

CodeQuestionYesNo (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 on cmd/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_ENABLED stays off.

API

EndpointChange
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.
CodeEnglish
chat_money_before_viewingNever pay any money before you have seen the unit in person.
chat_remote_landlordBe careful: the other person says they cannot meet you. Don't pay for keys sent by post.
chat_off_platform_contactKeep 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).
ActionCalls
Mark reviewedPOST /admin/messages/:id/review {status:"reviewed"}
Mark false alarmPOST /admin/messages/:id/review {status:"false_alarm"}
Suspend listingExisting 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 senderExisting ban modal via useAdminBanUser, reason pre-filled Chat scam: <finding>

Privacy

Testing

AreaTest
SendJudge 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 messageCreate 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 numberTwo sequential SendMessage calls ("wasap me 012 345", then "6789"): the second judge input holds the first message in Earlier
System linesRepository 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)
Statechat_off_platform_contact not asked for confirmed_upcoming / viewing_done. Earlier messages capped at 5, oldest first, with roles
SweepRe-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
ReadReceiver gets warnings; sender gets []; false_alarm gives [] to both. Sender POSTs a message the judge flags → POST response warnings: []; receiver GET → holds the code
Adminopen / all filter; review stores who and when; 404 on a message without findings; non-admin gets 403
Code contractGolden vector (J21): every Go chat finding code has a rental en/ms/zh message and a panel message
FrontendAmber 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
Calibrationeval-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_at record actions only; see ADR-0066)
  • Re-checking messages older than 24h, or back-filling existing messages
  • Admin screen for the switches