TypeSafe Jev — Shared Client and Rental Listing Check
Adds a shared Go client for TypeSafe Jev, a small typed AI judge, plus a typesafe_calls call log, and uses it to check rental listing addresses and text. Landlords see form warnings and admins see check findings, but Jev never blocks a save or rejects a listing — a person always decides.
- ADRs 0064
- Status Approved
Admins read every rental listing by hand, and Landlord API listings arrive with no human watching the form. This design adds a shared Go client for TypeSafe Jev, a small typed AI judge, and uses it to check listing addresses and text. Landlords get form warnings and admins get check findings, but Jev never blocks a save, never rejects a listing, and never builds the address fingerprint.
Why
Common problems slip past manual review:
- An address that is only "near Mid Valley" or "call me for address".
- A phone number hidden inside the address or description.
- "Chinese only" wording.
- A description that says "fully furnished" while the attribute says unfurnished.
Plain code cannot read text like this. A large language model can, but it is slow, costly, and returns free text to parse. TypeSafe Jev does not write text: we send facts (the state) plus short questions, and it returns typed answers with probabilities.
| Type | Asks | Returns |
|---|---|---|
| Noul | "Is this true?" | noul, 0–1 |
| Choice | "Which option?" | choice, probabilities, confidence |
| Score | "Where on this scale?" | score (can land between levels), probabilities, confidence |
TypeSafe facts (verified 2026-09-23)
- Endpoint
POST https://api.typesafe.ai/v1/systemone,Authorization: Bearer <key>- Model
jev-latest(todayjev-1.13.0)- Price
- $0.042 per 1M input tokens; output free
- Limit
- 32k tokens for state + longest question; 64k per request
- Rate limit
- 250k tokens/s, 1,200 requests/min; 429 or 529 → retry with backoff
- Input
- Text only
- Language
- English best; CJK weaker; Malay not stated
- Retention
- Not trained on customer data; zero retention only on enterprise plans
- Go SDK
- None (Python and JavaScript only)
What this change delivers
- Shared Go client for Jev
Usable by rental, fieldforce and Digital Worker, in
internal/shared/infrastructure/typesafe/. - Call log table
typesafe_callsrecords every Jev call, success or failure, kept 90 days. - Rental listing check
Form warnings for the landlord; check findings for the admin.
ListingJudge port; the shared vendor-specific client writes every call to typesafe_calls.Decisions
| # | Decision | Choice |
|---|---|---|
| J1 | Where Jev code lives | New shared package, not the AI module |
| J2 | On/off | One env switch per app; admin screen later |
| J3 | Call log | Postgres table typesafe_calls, every call, 90-day retention |
| J4 | Scope of first feature | Address checks and listing text checks, one Jev call |
| J5 | When a problem is found | Warn in the form; if left unfixed, flag for the admin |
| J6 | Privacy | Send the full address to TypeSafe |
| J7 | Race / gender wording | Flag race and religion; allow gender |
| J8 | Jev unavailable | Retry in the background 5 times, then mark not_checked |
| J9 | Admin while a check is pending | May approve anyway |
| J10 | Package name | Vendor-specific (typesafe/), intentional — no interchangeable provider; ListingJudge is the vendor-neutral rental port |
| J11 | Privacy trade-off | Send the full address under TypeSafe's standard (non-zero) retention; accepted risk, owner Gremlin. See ADR-0064 |
| J12 | Discrimination scope (v1) | Race and religion only; nationality, marital/family status, disability and age out of scope for v1 |
| J13 | Result naming | rental_listing_checks.findings (not "flags"); admin filter has_findings=true, "Live, check findings" — "flag" is reserved for the existing Duplicate Flag |
| J14 | Finding display text | Static Paraglide messages keyed by code, owned separately by rental and panel; Jev returns no prose |
| J15 | Switch-off mid-sweep | Sweep checks TYPESAFE_RENTAL_ENABLED at the start of every tick; no new calls while off; pending rows and retry counters untouched; an in-flight call may still finish |
| J16 | Sweep batch size | At most 20 rows per tick, sequential. Each row claimed alone (LIMIT 1) right before its Judge call, never 20 upfront; stops when no eligible row remains or after 20 claims |
| J17 | Rollout vs Landlord API Slice 2 | Jev ships first with Submit/resubmit and Property/Listing edit triggers; sync trigger, unit_missing and the is_test skip wait for Slice 2 |
| J18 | Cross-replica claim | Atomic per-row claim (checking + claim token + 60s expiry, twice the 30s Judge deadline); save requires generation and token match; reclaimable after a crash; a new queue resets the claim |
| J19 | Form-check deadline | 2s total, including retries; on deadline, falls through to no-warnings / submit-allowed |
| J20 | Calibration data source | eval-listing-check defaults to synthetic cases; real listings need an explicit opt-in flag, gated on the J11 Gremlin confirmation |
| J21 | Cross-stack code contract | Golden-vector test: Go owns finding-code constants; rental/panel maps ⊆ Go, and every Go-displayable code has a mapping in each screen that renders it |
| J22 | not_checked recovery | Same sweep reclaims due not_checked rows at low priority, one retry/day; success → done; failure → not_checked with next_attempt_at +1 day |
J1 / J10 — Why a shared typesafe/ package, not the AI module
One small client in internal/shared/infrastructure/typesafe/, used by any module through its own port — the same pattern as email/, storage/, cache/.
The AI module is a front desk for chat and vision providers: its value is choosing between OpenAI, Anthropic, Google and others, plus caps and product authorization. Jev takes state plus questions, not chat messages; no other provider does the same thing; a check costs ~$0.0001 so spending caps add nothing. The vendor name is a deliberate exception to capability naming: the client exposes Jev-specific Noul/Choice/Score types, and a name like judge/ would imply substitutability this design does not implement. ListingJudge is the vendor-neutral boundary rental depends on.
Rejected: client inside rental, a "judge" window in the AI module, calling from the Bun gateway, a generic judge/ name (see below).
Rejected alternatives
| Alternative | Why rejected |
|---|---|
| Client inside the rental module | Fieldforce and Digital Worker also need Jev; each would copy it |
| New "judge" window in the AI module | Forces an unlike tool into the chat/vision provider shape |
| Call TypeSafe from the Bun gateway | Listing logic is in Go; splits it across two backends |
| Log only to zap | Cannot search or sum usage by app, feature or listing |
| Block submit until the check works | A Jev outage would stop landlords |
| Disable approve while a check is pending | Jev would slow down a human for up to 4 hours |
| Hide the unit number before sending | Loses the unit checks; the address is not assumed safe just because it isn't an NRIC (J11) |
Generic judge/ package name | Implies substitutable providers; ListingJudge already gives rental the neutral port (J10) |
Rental listing check
Flow
- Form check
On the submit step of
rental/src/routes/landlord/[id].tsx, the app callsPOST /api/rental/listings/{id}/check. Warnings appear as a list in the submit card, each naming its field, rendered from a static Paraglide message keyed bycode(J14).PropertyListingFormis not changed. 2s total deadline (J19); past that, same outcome as a failed check. - The landlord decides
Fix and re-check, or submit anyway.
- Queue the check
In the same transaction that submits the listing, or changes checked content on a submitted listing, a
rental_listing_checksrow is saved aspending. - Background check
Each tick first checks
TYPESAFE_RENTAL_ENABLED(J15). While on: atomically claim one eligible row, call Jev, store findings and scores, claim the next; stop when none remain or after 20 claims (J16). - Retry
On failure: after 1 min, 5 min, 15 min, 1 hr, 3 hr. After 5 failures the row becomes
not_checked. not_checkedrecoveryNot permanent (J22): reclaimed at lower priority than
pending, one retry per day. Success →done; failure →not_checkedwithnext_attempt_at+1 day.- Admin review
panel/src/routes/admin/rental/listings/[id].tsxshows check findings, "check pending", or "not checked". Approve works in every state.
Rental reaches Jev through its own port, ListingJudge, with one adapter over the shared client. Rental logic never sees TypeSafe types — the same boundary ReceiptVision keeps for the AI module.
not_checked recovery (J22).Submit for review
- AddressThe address seems to contain a phone number or contact handle.
- AddressAdd a house or unit number and street.
- DescriptionWording seems to restrict tenants by race or religion.
- DescriptionTip: describe layout, condition, inclusions and transport.
When a check is queued
| Trigger | Listing status | Call site |
|---|---|---|
| Submit or resubmit | draft or rejected → pending_review | ListingUseCase.Submit write closure, next to UpdateStatus |
| Property edit of a §6.1 field | pending_review or live | PropertyUseCase.Update → applyReviewedEdit |
| Listing edit of a §6.1 field | pending_review or live | ListingUseCase.Update → applyReviewedEdit |
| Landlord API sync of a §6.1 field | pending_review or live, live mode only | Ships with Landlord API Slice 2 (J17) |
| Proof upload / verify | — | ProofUseCase → applyReviewedEdit; proofs are not §6.1 content, so it never queues |
- Each trigger upserts the one row per listing inside its own transaction, through one shared helper
queueListingCheck(ctx, repos, listingID). applyReviewedEditalready locks the property's non-terminal listings. It gets one new input,checkedChanged bool, set by the caller when a §6.1 field changed; when true it queues a check for every locked listing inpending_revieworlive. This is the one choke point; no caller queues on its own.- Drafts are never queued — the landlord uses the form check instead.
- v1 Landlord API routes reuse the same property and listing handlers, so API edits already reach this choke point.
- A listing with check findings while live lands in the "Live, check findings" filter. It is not demoted; a person decides.
Check table — rental_listing_checks
| Column | Notes |
|---|---|
listing_id | PK and FK; a new check replaces the old row. History is in typesafe_calls |
generation | int; +1 on every queue. Result saved only if generation still matches |
claim_token | uuid null; set on atomic claim (J18); cleared on save or on a new queue |
claim_expires_at | timestamptz null; past this the row is reclaimable even if still checking — crash recovery |
status | pending, checking, done, not_checked |
attempt_count, next_attempt_at | Retry state, same pattern as rental_notification_events. Reset on every queue; also drives daily not_checked recovery (J22) |
findings | jsonb, e.g. [{"code":"addr_contact_info","field":"address_line","p":0.91}]. Kept on re-queue. Not "flags" (J13) |
scores | jsonb, e.g. {"addr_completeness":2.1,"desc_quality":0.8}. Kept on re-queue |
checked_at | Null until the first done. Kept on re-queue |
rental_listing_checks.status lifecycle. A lost claim or switch-off tick never counts toward the five-failure limit.content_version = listing updated_at
An admin approval also changes updated_at, so every approved listing would look stale.
generation counter
Each queue does generation + 1, status = pending. The job reads generation, then the current listing and property, and saves with WHERE listing_id = ? AND generation = ?. An edit during the call makes the save match no row; the row stays pending. An old result can never overwrite a newer queue.
Claiming across replicas (J16, J18)
The sweep claims one row at a time, right before that row's Judge call — never 20 upfront, because sequential rows would wait behind earlier calls and later claims could expire first. PostgreSQL has no UPDATE … LIMIT, so a CTE picks one row and an UPDATE claims it (following the ClaimReminders viewing-reminder sweep):
WITH due AS (
SELECT listing_id FROM rental_listing_checks
WHERE (status IN ('pending','not_checked') AND next_attempt_at <= now())
OR (status = 'checking' AND claim_expires_at < now())
ORDER BY (status = 'not_checked'), next_attempt_at
LIMIT 1
FOR UPDATE SKIP LOCKED
)
UPDATE rental_listing_checks c
SET status = 'checking', claim_token = gen_random_uuid(),
claim_expires_at = now() + interval '60 seconds'
FROM due WHERE c.listing_id = due.listing_id
RETURNING c.*
- Eligible: due
pending, duenot_checked, andcheckingwith an expired claim.pendingand expiredcheckingsort beforenot_checked. SKIP LOCKED: two replicas never claim the same row. Each claim gets its owngen_random_uuid()token.- Loop: claim →
Judge(30s) → save; stop when the claim returns no row or after 20 claims. - Save only when both
generationandclaim_tokenmatch. - A queue on a
checkingrow resets the claim (claim_token = NULL, status = pending) and bumpsgeneration— a mid-check edit is never lost to a stale in-flight call. - Only actual failed Jev calls count toward the five-failure limit (J8).
Edge cases and error handling
| Case | Behaviour |
|---|---|
| Landlord edits after the check | Queues a new check on the same row. Old findings stay; admin UI shows them as stale while status is pending/checking and checked_at is set |
| Check findings on a live listing | Stays live. Admin "Live, check findings" filter: GET /api/rental/admin/listings?status=live&has_findings=true, a join on non-empty findings. No email for now |
Test-mode API listing (is_test) | No check; test rows never reach an admin (D32). Deferred: column does not exist yet; ships with Slice 2 |
| Switch off, new content | No form warnings, no check row; admin queue unchanged |
Switch off, rows already pending/not_checked | No new calls (checked every tick); rows and counters untouched; resumes on re-enable; an in-flight call may finish |
| Form check abuse | Reuses the IP-keyed RateLimitMiddleware (internal/api/http/middleware). No new per-user limiter |
| Form check fails | No warnings; landlord can submit |
| Form check slow (rate-limited / unavailable) | 2s total deadline incl. retries; same outcome as failure |
not_checked, no further edits | Daily low-priority recovery; success → done, failure → not_checked +1 day |
Questions and thresholds
One Jev call per check carries every question. The form check and background job build the same question set through one function.
State
{
"property": {
"property_type": "", "building_name": "", "address_line": "", "area": "",
"city": "", "state": "", "postcode": "", "bedrooms": 0, "bathrooms": 0,
"furnishing": "", "has_parking": false, "amenities": []
},
"listing": { "description": "", "house_rules": "", "monthly_rent": 0 }
}
No owner name, NRIC or contact fields are sent.
Code checks (no Jev)
| Code | Field | Rule |
|---|---|---|
postcode_invalid | postcode | Not 5 digits |
postcode_state_mismatch | postcode | Prefix does not match state in a Malaysian postcode-range table |
unit_missing | unit_number | High-rise type with empty unit_number. Ships with Slice 2 field (D18) |
Jev questions
| Code | Field | Type | Meaning |
|---|---|---|---|
addr_completeness | address_line | Score, 4 levels | 0 only area, landmark or "contact me"; 1 street or building, no number; 2 house/unit number plus street or building; 3 number, street or building, area and postcode |
addr_contact_info | address_line | Noul | Phone, WhatsApp, email or social handle, including disguised forms |
addr_location_conflict | address_line | Noul | Names a place that conflicts with area, city or state |
addr_unit_in_text | address_line | Noul | Contains a unit number (e.g. "B-12-3"); only when unit_number is empty, to ask the landlord to move it |
text_race_religion | description | Noul | Restricts or prefers tenants by race, ethnicity or religion. Yes: "Chinese only", "Muslim preferred", "Melayu sahaja". No: "female only", "no pork cooking". Out of scope v1 (J12): nationality ("no foreigners", "locals only"), marital/family status ("no unmarried couples", "no kids"), disability, age |
text_contact_info | description | Noul | Description or house rules contain contact details or an outside link |
text_attribute_conflict | description | Noul | Conflicts with bedrooms, bathrooms, furnishing, parking or amenities |
desc_quality | description | Score, 4 levels | 0 empty or a few words; 1 generic; 2 some details about this unit; 3 layout, condition, inclusions, transport and move-in terms |
TypeSafe writing rules: every Noul phrased so high means "problem present"; each question judges one thing; Score levels describe situations and never refer to other levels. Full question text is written during implementation and tuned in calibration.
Thresholds
-
Noulp ≥ 0.7→ form warning and admin finding starting guess 0.7 -
addr_completenessscore < 1.5→ form warning and admin finding starting guess 1.5 -
desc_qualityscore < 1.5→ form tip only; admin sees the score, never a finding 1.5
Thresholds are Go constants in the rental adapter. 0.7 and 1.5 are starting guesses, not measured results.
Calibration — before the switch goes on
- New command
backend/go/cmd/eval-listing-check, modelled oncmd/eval-parse-task. - Default: only ~30 hand-written synthetic cases — Malay, Chinese, Manglish, and traps like "no pork cooking" and "female only". Never reads production listings by default (J20).
- Real listings need an explicit opt-in flag, gated on the J11 Gremlin privacy confirmation. No real address leaves the platform before that, including during calibration.
- Prints each probability for labelling; thresholds are set from the labels.
- Decides whether Jev handles Malay well enough. If not, the affected questions stay off.
Rollout
- Ship dark
Client,
typesafe_calls, check table, Submit + edit triggers.TYPESAFE_RENTAL_ENABLED=false. - Synthetic calibration
eval-listing-checkon ~30 synthetic cases; set thresholds; drop weak Malay questions. - Gremlin privacy gate
Gremlin confirms disclosure and vendor terms (J11 / ADR-0064). Only then real-listing calibration or enabling.
- Enable rental
Turn the switch on for real landlords.
- Landlord API Slice 2
Adds sync trigger (live mode only),
unit_missing,is_testskip and their tests.
Testing
| Area | Test |
|---|---|
| Client | httptest server: request shape, answer decoding, 429/529 retry, validation limits; a cancelled/expired ctx stops the request and any backoff wait at once |
| Call log | Row written on success and failure; answer still returned when the log write fails |
| Retention | Rows older than 90 days deleted, newer kept |
| Triggers | Submit, and a pending/live property or listing edit of a checked field, each leave exactly one pending row; draft save, proof upload and unchecked-field edit leave none. Sync trigger test ships with Slice 2 |
| Job | Fake ListingJudge: success stores findings; retry timing; not_checked after 5 failures |
| Generation | A queue during a running job → the save changes nothing; row stays pending |
| Claim (J18) | Two concurrent claims on one due row: only one succeeds; expired checking row is reclaimable; a lost claim does not count toward the failure limit |
| Sweep bound (J16) | Each claim takes one row right before its call; 25 due rows → 20 claims + 20 calls, 5 wait; 3 due rows → stops after 3; while row N is in its call, rows N+1… stay unclaimed for other replicas |
| Switch off, mid-sweep (J15) | Pending/not_checked rows untouched; no Jev calls; resumes on re-enable |
| Form-check deadline (J19) | Slow/rate-limited Jev past 2s → no warnings, submit allowed |
not_checked recovery (J22) | Reclaimed after daily next_attempt_at; success → done; failure → not_checked with next daily time |
| Stale | Edit after check → findings stale; an admin approval alone does not make them stale |
| Switch off, new content | No call, no row |
| Code checks | Postcode format and postcode-state table |
| Calibration source (J20) | Defaults to synthetic only; real listings need the opt-in flag |
| Cross-stack codes (J21) | Go constants vs rental/panel message maps: client ⊆ Go; every displayable code mapped in each screen that renders it |
| Frontend | Submit card lists field-named warnings and still submits; admin page shows findings, pending, not checked, stale |
Risks and dependencies
Out of scope
- Admin screen for the on/off switches (J2).
- Admin manual "recheck now" button — daily
not_checkedrecovery (J22) covers the dead-end case. - Fieldforce and Digital Worker Jev features.
- Checking that an address exists on a map (needs a geocoding API).
- "Asks for a deposit before a viewing" and other chat checks — belongs to the message-check idea.
- Email notice for "Live, check findings" listings.
- Zero-retention enterprise plan.
- Nationality, marital/family status, disability and age discrimination detection (J12).
- Landlord-facing privacy disclosure / ToS update — owned by Gremlin, gates enabling per J11 / ADR-0064.
References
- Landlord API Slice 2 — Idempotent Sync (
2026-09-22-landlord-api-idempotent-sync-design.md): D18unit_number, D32 test mode. - ADR-0064 — TypeSafe listing address transfer (full-address privacy trade-off).
CONTEXT.md— Check Finding, Duplicate Flag.- TypeSafe privacy policy.