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.

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

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.

  • StatusApproved; grill-reviewed 2026-09-23 (J10–J22 added)
  • Areabackend/go, solidstart/apps/rental, solidstart/apps/panel
  • VendorTypeSafe Jev (jev-latest)
  • Cost~$0.0001 per check
  • DefaultTYPESAFE_RENTAL_ENABLED=false
  • Privacy ownerGremlin (ADR-0064)

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.

TypeAsksReturns
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 (today jev-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

  1. Shared Go client for Jev

    Usable by rental, fieldforce and Digital Worker, in internal/shared/infrastructure/typesafe/.

  2. Call log table

    typesafe_calls records every Jev call, success or failure, kept 90 days.

  3. Rental listing check

    Form warnings for the landlord; check findings for the admin.

Boundaries: rental depends only on its vendor-neutral ListingJudge port; the shared vendor-specific client writes every call to typesafe_calls
Boundaries: rental depends only on its vendor-neutral ListingJudge port; the shared vendor-specific client writes every call to typesafe_calls.

Decisions

#DecisionChoice
J1Where Jev code livesNew shared package, not the AI module
J2On/offOne env switch per app; admin screen later
J3Call logPostgres table typesafe_calls, every call, 90-day retention
J4Scope of first featureAddress checks and listing text checks, one Jev call
J5When a problem is foundWarn in the form; if left unfixed, flag for the admin
J6PrivacySend the full address to TypeSafe
J7Race / gender wordingFlag race and religion; allow gender
J8Jev unavailableRetry in the background 5 times, then mark not_checked
J9Admin while a check is pendingMay approve anyway
J10Package nameVendor-specific (typesafe/), intentional — no interchangeable provider; ListingJudge is the vendor-neutral rental port
J11Privacy trade-offSend the full address under TypeSafe's standard (non-zero) retention; accepted risk, owner Gremlin. See ADR-0064
J12Discrimination scope (v1)Race and religion only; nationality, marital/family status, disability and age out of scope for v1
J13Result namingrental_listing_checks.findings (not "flags"); admin filter has_findings=true, "Live, check findings" — "flag" is reserved for the existing Duplicate Flag
J14Finding display textStatic Paraglide messages keyed by code, owned separately by rental and panel; Jev returns no prose
J15Switch-off mid-sweepSweep 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
J16Sweep batch sizeAt 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
J17Rollout vs Landlord API Slice 2Jev ships first with Submit/resubmit and Property/Listing edit triggers; sync trigger, unit_missing and the is_test skip wait for Slice 2
J18Cross-replica claimAtomic 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
J19Form-check deadline2s total, including retries; on deadline, falls through to no-warnings / submit-allowed
J20Calibration data sourceeval-listing-check defaults to synthetic cases; real listings need an explicit opt-in flag, gated on the J11 Gremlin confirmation
J21Cross-stack code contractGolden-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
J22not_checked recoverySame 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

AlternativeWhy rejected
Client inside the rental moduleFieldforce and Digital Worker also need Jev; each would copy it
New "judge" window in the AI moduleForces an unlike tool into the chat/vision provider shape
Call TypeSafe from the Bun gatewayListing logic is in Go; splits it across two backends
Log only to zapCannot search or sum usage by app, feature or listing
Block submit until the check worksA Jev outage would stop landlords
Disable approve while a check is pendingJev would slow down a human for up to 4 hours
Hide the unit number before sendingLoses the unit checks; the address is not assumed safe just because it isn't an NRIC (J11)
Generic judge/ package nameImplies substitutable providers; ListingJudge already gives rental the neutral port (J10)

Shared client — internal/shared/infrastructure/typesafe/

Configuration

Follows the RENTAL_EMAIL_* pattern in internal/shared/infrastructure/config/config.go.

VariableDefaultMeaning
TYPESAFE_API_KEY""One key for all apps
TYPESAFE_RENTAL_ENABLEDfalseRental's switch
  • TYPESAFE_FIELDFORCE_ENABLED and TYPESAFE_DIGITALWORKER_ENABLED are added with the first Jev feature in each app, not now.
  • An app makes no Jev call when the key is empty or its switch is false. Each app reads its own switch; the client does not know about switches.

Types

Go structs matching the API: Noul, Choice, Score questions; NoulAnswer, ChoiceAnswer, ScoreAnswer results. The client validates before sending: Choice at most 255 options, Score 2–10 levels.

Call

func (c *Client) Judge(ctx context.Context, caller Caller, state any, questions map[string]Question) (*Result, error)

type Caller struct {
    App     string // required: "rental", "fieldforce", "digitalworker"
    Feature string // required: e.g. "listing_check"
    OrgID   string // optional
    RefID   string // optional: the record being judged, e.g. listing id
}
  • Model is jev-latest; the response's exact model is kept.
  • Retries only 429 and 529: 2 retries with exponential backoff, then an error. Long retries belong to the caller (rental's job).
  • Result holds typed answers, input_tokens, model and latency.
  • Honors context cancellation everywhere: each HTTP request uses the caller's ctx, every backoff wait returns early on ctx.Done(), so the caller's deadline bounds the whole call.
Background Judge deadline
30s total (context.WithTimeout), covering all retries and backoff
Form-check deadline
2s total, including retries (J19)
Claim expiry
60s — twice the 30s deadline, so a claim cannot expire mid-call and a crash leaves the row reclaimable within a minute (J18)

Call log — typesafe_calls

Every call writes one row, success or failure.

ColumnTypeNotes
iduuid
apptextRequired
featuretextRequired
org_iduuid nullRental is orgless, so empty there
ref_idtext nullE.g. listing id
inputjsonbState and questions sent
outputjsonb nullAnswers; null on error
errortext nullError code and detail
modeltext nullE.g. jev-1.13.0
input_tokensint null
http_statusint null
attemptsintIncluding retries
latency_msint
created_attimestamptz

Indexes: (app, feature, created_at) and (ref_id).

  • The client depends on a small CallLogRepository port received at construction; the GORM implementation lives next to it.
  • A failed log write never fails the call: the answer is returned and a zap warning is written.
  • A daily job on the shared scheduler deletes rows older than 90 days (input holds private addresses).
  • Migration goes in internal/shared/infrastructure/database/postgresql/migrations/.

Rental listing check

Flow

End-to-end listing check: synchronous form check, then a queued background check that feeds the admin review page
End-to-end listing check: synchronous form check, then a queued background check that feeds the admin review page.
  1. Form check

    On the submit step of rental/src/routes/landlord/[id].tsx, the app calls POST /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 by code (J14). PropertyListingForm is not changed. 2s total deadline (J19); past that, same outcome as a failed check.

  2. The landlord decides

    Fix and re-check, or submit anyway.

  3. Queue the check

    In the same transaction that submits the listing, or changes checked content on a submitted listing, a rental_listing_checks row is saved as pending.

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

  5. Retry

    On failure: after 1 min, 5 min, 15 min, 1 hr, 3 hr. After 5 failures the row becomes not_checked.

  6. not_checked recovery

    Not permanent (J22): reclaimed at lower priority than pending, one retry per day. Success → done; failure → not_checked with next_attempt_at +1 day.

  7. Admin review

    panel/src/routes/admin/rental/listings/[id].tsx shows 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.

Background retry backoff after a failed check: waits of 1 minute, 5 minutes, 15 minutes, 1 hour and 3 hours, about 4.35 hours in total, then the row becomes not_checked. +1m +5m +15m +1h +3h not_checked ≈ 4.35 h total
Retry schedule, position proportional to cumulative wait (1m, 5m, 15m, 1h, 3h). Then daily 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.
Re-check Submit anyway
Landlord submit card mockup — field-named warnings from static Paraglide messages; submit stays enabled. Message wording is illustrative.

When a check is queued

TriggerListing statusCall site
Submit or resubmitdraft or rejected → pending_reviewListingUseCase.Submit write closure, next to UpdateStatus
Property edit of a §6.1 fieldpending_review or livePropertyUseCase.Update → applyReviewedEdit
Listing edit of a §6.1 fieldpending_review or liveListingUseCase.Update → applyReviewedEdit
Landlord API sync of a §6.1 fieldpending_review or live, live mode onlyShips 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).
  • applyReviewedEdit already 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 in pending_review or live. 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

ColumnNotes
listing_idPK and FK; a new check replaces the old row. History is in typesafe_calls
generationint; +1 on every queue. Result saved only if generation still matches
claim_tokenuuid null; set on atomic claim (J18); cleared on save or on a new queue
claim_expires_attimestamptz null; past this the row is reclaimable even if still checking — crash recovery
statuspending, checking, done, not_checked
attempt_count, next_attempt_atRetry state, same pattern as rental_notification_events. Reset on every queue; also drives daily not_checked recovery (J22)
findingsjsonb, e.g. [{"code":"addr_contact_info","field":"address_line","p":0.91}]. Kept on re-queue. Not "flags" (J13)
scoresjsonb, e.g. {"addr_completeness":2.1,"desc_quality":0.8}. Kept on re-queue
checked_atNull 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
rental_listing_checks.status lifecycle. A lost claim or switch-off tick never counts toward the five-failure limit.
Rejected

content_version = listing updated_at

An admin approval also changes updated_at, so every approved listing would look stale.

Selected

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, due not_checked, and checking with an expired claim. pending and expired checking sort before not_checked.
  • SKIP LOCKED: two replicas never claim the same row. Each claim gets its own gen_random_uuid() token.
  • Loop: claim → Judge (30s) → save; stop when the claim returns no row or after 20 claims.
  • Save only when both generation and claim_token match.
  • A queue on a checking row resets the claim (claim_token = NULL, status = pending) and bumps generation — 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).
Generation + claim token guard: an edit during an in-flight check discards the stale result
Generation + claim token guard: an edit during an in-flight check discards the stale result.

Edge cases and error handling

CaseBehaviour
Landlord edits after the checkQueues 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 listingStays 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 contentNo form warnings, no check row; admin queue unchanged
Switch off, rows already pending/not_checkedNo new calls (checked every tick); rows and counters untouched; resumes on re-enable; an in-flight call may finish
Form check abuseReuses the IP-keyed RateLimitMiddleware (internal/api/http/middleware). No new per-user limiter
Form check failsNo warnings; landlord can submit
Form check slow (rate-limited / unavailable)2s total deadline incl. retries; same outcome as failure
not_checked, no further editsDaily 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)

CodeFieldRule
postcode_invalidpostcodeNot 5 digits
postcode_state_mismatchpostcodePrefix does not match state in a Malaysian postcode-range table
unit_missingunit_numberHigh-rise type with empty unit_number. Ships with Slice 2 field (D18)

Jev questions

CodeFieldTypeMeaning
addr_completenessaddress_lineScore, 4 levels0 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_infoaddress_lineNoulPhone, WhatsApp, email or social handle, including disguised forms
addr_location_conflictaddress_lineNoulNames a place that conflicts with area, city or state
addr_unit_in_textaddress_lineNoulContains a unit number (e.g. "B-12-3"); only when unit_number is empty, to ask the landlord to move it
text_race_religiondescriptionNoulRestricts 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_infodescriptionNoulDescription or house rules contain contact details or an outside link
text_attribute_conflictdescriptionNoulConflicts with bedrooms, bathrooms, furnishing, parking or amenities
desc_qualitydescriptionScore, 4 levels0 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

  • Noul p ≥ 0.7 → form warning and admin finding starting guess 0.7
  • addr_completeness score < 1.5 → form warning and admin finding starting guess 1.5
  • desc_quality score < 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 on cmd/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

  1. Ship dark

    Client, typesafe_calls, check table, Submit + edit triggers. TYPESAFE_RENTAL_ENABLED=false.

  2. Synthetic calibration

    eval-listing-check on ~30 synthetic cases; set thresholds; drop weak Malay questions.

  3. Gremlin privacy gate

    Gremlin confirms disclosure and vendor terms (J11 / ADR-0064). Only then real-listing calibration or enabling.

  4. Enable rental

    Turn the switch on for real landlords.

  5. Landlord API Slice 2

    Adds sync trigger (live mode only), unit_missing, is_test skip and their tests.

Testing

AreaTest
Clienthttptest server: request shape, answer decoding, 429/529 retry, validation limits; a cancelled/expired ctx stops the request and any backoff wait at once
Call logRow written on success and failure; answer still returned when the log write fails
RetentionRows older than 90 days deleted, newer kept
TriggersSubmit, 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
JobFake ListingJudge: success stores findings; retry timing; not_checked after 5 failures
GenerationA 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
StaleEdit after check → findings stale; an admin approval alone does not make them stale
Switch off, new contentNo call, no row
Code checksPostcode 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
FrontendSubmit 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_checked recovery (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): D18 unit_number, D32 test mode.
  • ADR-0064 — TypeSafe listing address transfer (full-address privacy trade-off).
  • CONTEXT.md — Check Finding, Duplicate Flag.
  • TypeSafe privacy policy.