STATUS: PRODUCTION RESTRICTED_ACCESS

HAYOP.FARM

Marketplace OS for Farmers · Solo-built · Production

Next.js 16 (App Router)React 19TypeScriptSupabase (Postgres / Auth / Realtime)Postgres RPC + JSONBxAI Grok (LLM)Cloudflare R2TailwindCSSnext-intl (i18n)Vercel
[SYSTEM_OVERVIEW]

Hayop is a production-ready, mobile-first marketplace for farmers in the Philippines. The system digitizes the full animal trading cycle: from inventory and listings to negotiations, offers, and deal recording, while payments and handover remain offline.

The product's core value lies in its strictly formalized market logic embedded in the architecture, and an AI assistant that acts as a system operator rather than a chatbot.

Core Loops
AnimalListing (1 active per animal)Offer (Buy / Swap)Chat (Buyer + Listing thread)Deal (immutable record)

/// DEPLOYMENT_SCOPE

  • ::Real users, live production
  • ::Mobile-first, field conditions, one-handed use
  • ::~20–30 screens and states
  • ::Localization: EN / Taglish (UI + AI)
  • ::Adaptability: mobile-first UI + desktop as extended mode

Engineering Architecture

Hybrid Access Model (SDK + RPC)

Simple CRUD operations go through Supabase SDK under RLS (messages, creating offers). Critical operations and market invariants are implemented via Postgres RPC (Security Definer/atomic transactions).

Market Engine: DB-First Search + Filters

get_market_items_animals — the heart of the market: JOIN animals+farmers, filters by JSONB (type/breed/color), ranges (health/rating/price), sorting, and pagination. Heavy search logic is moved to the DB: faster, simpler client, fewer errors.

Boosted Ranking & Injection (Growth Mechanics)

Boost is not just a badge: lots get into the top-carousel and are additionally mixed into the general feed via a formula (e.g., every Nth card). This provides paid acceleration without destroying organic results.

Realtime Without Polling

Realtime subscriptions to animal_chat_threads (personal user channels) and animal_chat_messages (by thread_id). Unread counts and badges update on INSERT/UPDATE events without polling and logic duplication.

Localization & Regional Fit (next-intl)

EN / Taglish localization via next-intl. Not just string translation: UI and AI adapt to the user's locale (market language is part of the product).

Client-Side Privacy Hardening

Canvas re-encode + forced JPEG + compression to ~1MB and resize to ~1200px. EXIF is stripped before upload — metadata never leaks even with a public bucket.

AI Engine

Multi-Agent Medical Flow (Nurse → Doctor)

AI Nurse performs triage and collects anamnesis. AI Doctor provides a differential diagnosis, risk analysis, and treatment plan (pharma + alternatives), adapted to local Philippine conditions.

Streaming + Hidden JSON Protocol (Client-Side)

Responses are streamed as text. Hidden JSON blocks (e.g., [[PREFILL: {...}]]) are embedded in the stream. useHayopChat parses via regex in while(true), extracts payload, dispatches actions (window.dispatchEvent), and leaves clean text for the user.

Stamina Economy (Anti-Abuse)

staminaBalance in farmers + atomic RPC check_and_charge_stamina(p_cost, p_is_image). Deduction occurs BEFORE the LLM call — protection against free spam and expensive attacks.

Operator Layer

Context-Aware AI Operator (Not a Chatbot)

AI in Hayop works as an embedded system operator, not an isolated chat. It always knows: who the user is, what screen they are on, what object they are working with (animal / listing / offer / chat), and the current state of the business flow.

Dynamic System Prompt Injection

On every page and key action, relevant context is dynamically injected into the system prompt: current screen, selected animal/listing/offer, user role (buyer/seller), interface language, and allowed actions. AI never works in a vacuum.

Tool-Driven AI (Actions, Not Text)

AI uses a set of internal tools (LLM functions) allowing it to not only answer with text but also initiate real actions: creating objects, changing states, navigation, and running UI scenarios. The AI response is a potential action in the system.

UI Teleportation & Guided Navigation

AI can guide the user through the interface: suggesting transitions, opening necessary screens, and preparing forms (deep links + prefill). This reduces cognitive load and speeds up complex scenarios.

Screen-Aware Reasoning

AI logic depends on what the user is looking at right now. The same request is processed differently in the context of Market, Animal Passport, Offer, or Chat — without prompt duplication and chaotic instructions.

Strict Capability Boundaries

AI never does anything directly. All actions pass through verifiable backend layers (RPC / API). AI forms an intent, the system decides if it is allowed. This eliminates side effects and uncontrolled behavior.

Future-Proof Operator Model

The AI architecture is laid as the foundation for a future PRO subscription: advanced tools, routine automation, lot marketing management, and advanced user analytics.

Realtime Infrastructure

Realtime Chat Tied to Market Objects

Chats in Hayop are not a separate messenger, but part of the market: a thread is tied to listing/offer and created by the rule '1 buyer + 1 listing = 1 thread'. This preserves negotiation history and removes the chaos of 'switching to FB'.

Realtime Delivery + Live Badges

Supabase Realtime: subscriptions to animal_chat_threads (personal user channel) and animal_chat_messages (by thread_id). Unread counts and nav badges update instantly on INSERT/UPDATE events without polling.

Read Receipts / Seen State

Read status support: mark_*_as_read / mark_thread_as_read. User sees actual states (ticks/seen), and the system correctly maintains unread counters.

Media in Chat (Images) + Privacy Hardening

Chat supports images. Files undergo client-side re-encoding/compression before upload, removing EXIF and reducing size. Result: fast chat, fewer leaks, less traffic.

Ghost Delete (Per-User Archive)

User can 'delete chat for themselves' without destroying history for the other party: deleted_by[] in animal_chat_threads. This correctly solves 'remove from list' UX without losing negotiation evidence.

Admin & Security

Admin Console / Ops Layer (RPC)

Ops layer via Postgres RPC: management of bans (login/chat/AI), limits, PRO, boost credits, system toggles, log viewing, and 'spy' mode for incident resolution.

Moderation & Enforcement

admin_apply_ban / admin_toggle_ban / admin_update_user_usage / admin_toggle_system — centralized control without trusting the client.

Audit & Visibility

admin_get_dashboard_stats + admin_get_user_logs + admin_spy_get_chats/messages — quick analysis of abuse, disputed deals, and bugs.

Business Loop

PRO & Limits Control

admin_manage_pro + usage limits/resets. Prepared for subscription (paywall for AI and premium functions).

Boost Credits & Paid Visibility

apply_boost_animal + admin_add_boosts — paid lot acceleration (carousel + injection into feed), built into market mechanics.

Payments Ledger Ready

payment_transactions — ledger for PRO/boost payments and event analytics. Even if payments are in development, the model is ready.

Reliability Principles

  • Race ConditionsCritical operations protected by RPC and transactions (accept_offer_*).
  • Double Sell / Inconsistent StateMarket invariants enforced in DB: deal created atomically along with status changes.
  • AI Abuse / Cost AttacksCharge-first stamina before every AI call (including image cost).
  • Location LeakageNo GPS + EXIF stripped before upload (metadata never leaves device).
  • Chat Integrity1 thread per Buyer+Listing + ghost delete via deleted_by[] without data loss.

Invariants (Strict Rules)

  • ::1 Animal → max 1 active Listing (enforced via RPC upsert_listing_animal)
  • ::Offer — strictly structured object with state machine (pending → accepted/declined/expired/cancelled)
  • ::Accept Offer = atomic RPC transaction (deal create + listing sold + cancel other offers)
  • ::Deal immutable (no updatedAt — deal history is fixed forever)
  • ::1 Chat Thread per Buyer + Listing pair; repeated contact revives the same thread_id
  • ::Ghost delete via deleted_by[] without removing data for the other party
  • ::No GPS coordinates — city/region only

Data Entities

farmersapp_settingsanimals (attributes JSONB)animal_categoriesmedical_recordsanimal_listingsanimal_offersanimal_dealsanimal_chat_threadsanimal_chat_messagesai_messageslikes (farmer trust)animal_likes (likes_count integrity)payment_transactionssupport_ticketsanimal_chat_threads_with_details (view)animal_offers_with_* (view)

UX Philosophies

  • Lazy-first UX (2–3 taps for key actions)
  • One-hand mobile usage (primary interaction model)
  • Desktop — extended mode for viewing/management
  • Realtime feedback (badges, statuses, unread)
  • No context switching: negotiations and deal within platform
  • i18n by design: EN / Taglish + AI aligned with locale

Future Signals

  • Poultry → Multi-Animal via JSONB attributes
  • Pro subscription centered on AI Doctor + extended scenarios
  • Medical history within animal passport (medical_records)
  • Medical history within animal passport (medical_records)
  • Growth mechanics boosting: boosts + ops tooling