Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Backend (Edge Functions) v1.0 (frozen on 2026-11-23, commit f026e3b). Switch to Latest →

9. Jarvis AI Assistant

Repository: Backend (planovi-backend) • Rule Prefix: BR-JARVIS • Documented Rules: 7 • Open [TEAM_WHY_NEEDED] Questions: 4

1. Business Purpose & Actors

Multimodal (text + WAV audio) human-in-the-loop AI assistant for the Planovi Flutter app. Uses Google Gemini 2.5 Flash to transcribe voice, run single-hop RAG (QUERY_DB), propose structured confirmation cards (action_widget) saved in jarvis_history, execute user-confirmed actions against Planovi PostgreSQL and Google Workspace (Calendar, Gmail, Docs), optionally synthesize ElevenLabs TTS MP3 replies, and bill monthly per-user AI token quotas.

  • Note on Dead Code: supabase/functions/jarvis/index.ts (950 LOC) is the sole active runtime file. All 9 modular files under jarvis/prompts/, jarvis/services/, and jarvis/tools/ are 100% orphaned dead code (zero imports) left behind by merge 580d691 when the hardened monolith won over an unhardened modular branch.
  • Actors: Authenticated company member (company_members.is_active = true), Flutter jarvis_chat_provider, reminder-scheduler (injecting reminder_alert/reminder_alarm cards), and external APIs (Gemini, ElevenLabs, Google Calendar/Gmail/Docs).

2. All Features & End-to-End Flows

  1. Auth, Parsing & Pre-checks (jarvis/index.ts:74-205):
    • config.toml sets verify_jwt = false; index.ts enforces GoTrue supabaseAdmin.auth.getUser(token) (401).
    • Parses application/json OR multipart/form-data (voice WAV).
    • Resolves googleToken (request googletoken/google_token -> latest user_google_tokens.access_token, no refresh flow) and companyId (unordered .limit(1) active company_members, ignoring body company_id; 403 if none).
    • [SYSTEM_COMMAND]* -> 200 { status: "context_wiped" }.
    • Verifies pending_message_id ownership (id, user_id, company_id) (404 on confirm/reject if missing) and 30 min TTL.
  2. Flow 1A — Confirm Action ([SYSTEM_CONFIRM], index.ts:210-510):
    • Pre-flight DB guard on generic db_action: JARVIS_WRITABLE_TABLES = {calendar_events, client_attachments, client_notes, clients}, non-empty criteria on UPDATE/DELETE, assertCompanyUsers on user_id/assignee_ids.
    • Dedicated branches: reminder_alarm (snoozed -> +10 min, pre_reminder_time = -5m, status = 'pending'; else writes user_action verbatim), Google Calendar sync (fail-safe when calendar_save_pref ∈ {'both','google'}), Gmail send (blocking), set_reminder, create_offer (status: 'draft'), Google Doc creation + 'PENDING_DOC_URL' replacement, and generic Planovi DB INSERT/UPDATE/DELETE (multi-assignee calendar fan-out with shared group_id = crypto.randomUUID()).
    • Marks jarvis_history.action_widget.confirmed = true (200) or confirmed = false + Polish debug error message (400).
  3. Flow 1B — Reject Action ([SYSTEM_REJECT], index.ts:512-516): Hard-deletes jarvis_history row scoped to (id, user_id, company_id) -> 200 { status: "rejected" }.
  4. Flow 2 — AI Parsing, Single-Hop RAG, Quota & TTS (index.ts:518-944):
    • Fetches live PostgREST OpenAPI schema (/rest/v1/ minus 5 excluded tables), up to 50 clients, 50 company_members, 20 calendar_events (unused allEvents), and last 6 jarvis_history rows.
    • Calls get_user_token_status (broken array check — never blocks!) -> Gemini Hop 1 (gemini-2.5-flash, temperature: 0.1, JSON mode) -> if intent === 'QUERY_DB', validates table in JARVIS_READABLE_TABLES = {calendar_events, clients, client_attachments, client_notes, reminders, client_offers} & SAFE_IDENTIFIER column, queries company_id (limit 15), runs Gemini Hop 2.
    • Rewrites [SILENCE] to Polish retry prompt -> bills record_ai_token_usage(companyId, user.id, 'jarvis', prompt, completion) -> runs Flutter crash-prevention pre-flight check (strips malformed calendar_event/send_email widgets) -> saves user message -> optional ElevenLabs TTS (21m00Tcm4TlvDq8ikWAM, eleven_multilingual_v2, uploaded to client_files/jarvis_audio/jarvis_response_${Date.now()}.mp3) -> saves jarvis reply (omitting widget on VOICE_CONFIRM/VOICE_REJECT) -> returns 200 aiContent.

3. Hard Business Rules, Validations, Calculations & Edge Cases (BR-JARVIS)

  • BR-JARVIS-01 (Strict Auth & Server-Derived Company): GoTrue auth.getUser required (401); companyId derived strictly from active company_members (403).
  • BR-JARVIS-02 (Pending Card Ownership & 30-Min TTL): pending_message_id must match (id, user_id, company_id) in jarvis_history and be <= 30 min old (index.ts:183-205).
  • BR-JARVIS-03 (Read/Write Table & User Allowlists): Generic writes restricted to {calendar_events, client_attachments, client_notes, clients} with non-empty UPDATE/DELETE criteria; RAG reads restricted to {calendar_events, clients, client_attachments, client_notes, reminders, client_offers} (limit 15, company_id-scoped). All target user_id/assignee_ids/assigned_to_user_id validated via assertCompanyUsers.
  • BR-JARVIS-04 (Group Calendar Fan-Out & Save Pref): calendar_save_pref ∈ {'both','google','planovi'} (default 'both'). Multi-assignee inserts fan out 1 row/user with shared group_id. Google Calendar sync is fail-safe; Gmail send is blocking.
  • BR-JARVIS-05 (Reminder Snooze & Short-Horizon Guard): Alarm snooze adds +10 min (pre_reminder_time = -5 min, status='pending'). set_reminder sets pre_reminder_sent = true if pre_reminder_time <= now.
  • BR-JARVIS-06 (Flutter Pre-Flight Guard): Strips action_widget and returns Polish debug error if calendar_event lacks title/start_time/end_time/date_display/google_calendar_payload.attendees (Array) or send_email lacks to/subject/body.
  • BR-JARVIS-07 (Token Billing): Calls record_ai_token_usage (feature='jarvis', billed = ceil((prompt + completion) * margin)). Intended 429 pre-check via get_user_token_status is currently broken (see §8).

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> Proposed : intent=PROPOSE (30m TTL in jarvis_history)
    Proposed --> Confirmed : [SYSTEM_CONFIRM] succeeds (confirmed=true)
    Proposed --> Failed : [SYSTEM_CONFIRM] fails (confirmed=false + debug msg)
    Proposed --> Deleted : [SYSTEM_REJECT] (hard delete row)
    Proposed --> Expired : > 30 minutes elapsed
  • intent: 'CONVERSATION' | 'PROPOSE' | 'QUERY_DB' (internal hop) | 'VOICE_CONFIRM' | 'VOICE_REJECT'.
  • action_widget.type: 'calendar_event', 'send_email', 'create_doc', 'set_reminder', 'add_customer', 'add_client_document', 'dynamic_insert', 'create_offer', 'reminder_alarm'.

5. Technical Contract

  • Endpoint: POST /functions/v1/jarvis (application/json or multipart/form-data, Authorization: Bearer <jwt>).
  • Tables & RPCs: jarvis_history, user_google_tokens, company_members, user_profiles, clients, calendar_events, client_attachments, client_notes, reminders, client_offers; RPCs get_user_token_status, record_ai_token_usage; Storage client_files/jarvis_audio/*.mp3.
  • External APIs: Gemini gemini-2.5-flash, ElevenLabs eleven_multilingual_v2 (voice 21m00Tcm4TlvDq8ikWAM), Google Calendar v3, Gmail v1, Google Docs v1.

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
planovi-flutter-app (jarvis_chat_provider) -> jarvis/index.tsHTTPS POST / User JWT + optional Google OAuth tokenStrict action_widget schema, VOICE_CONFIRM/VOICE_REJECT -> [SYSTEM_CONFIRM]/[SYSTEM_REJECT], elevenlabs_audio_url
reminder-scheduler <-> jarvis/index.tsShared DB (reminders, jarvis_history)Jarvis creates reminders; scheduler writes reminder_alarm/reminder_alert to jarvis_history; Jarvis actions reminder_alarm

7. Why It Works This Way

  • Monolith index.ts + 9 orphaned modular files: Git merge 580d691 preserved develop’s security-hardened monolith while leaving an older unhardened refactor (24d6cfc) orphaned in prompts/, services/, tools/.
  • Human-in-the-loop action_widget: Prevents unreviewed LLM mutations to DB, Gmail, or Calendar while enabling voice confirmation.
  • [TEAM_WHY_NEEDED: Why does jarvis upload TTS MP3s to public client_files/jarvis_audio/ (untracked by storage quotas, no company prefix, no TTL) instead of a private bucket with signed URLs?]
  • [TEAM_WHY_NEEDED: Why does index.ts inject the entire PostgREST OpenAPI schema into every Gemini prompt and mention dynamic_insert when JARVIS_WRITABLE_TABLES hard-blocks all but 4 tables?]
  • [TEAM_WHY_NEEDED: How should multi-company users select their active company in Jarvis (currently unordered .limit(1))?]
  • [TEAM_WHY_NEEDED: Why is ElevenLabs voice 21m00Tcm4TlvDq8ikWAM (Rachel) hardcoded for all locales?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact Query or LogFix
Users exceed monthly AI token quota and never get HTTP 429get_user_token_status returns TABLE (PostgREST array [{allowed: false}]), but jarvis/index.ts:725 reads tokenStatus.allowed (undefined) instead of tokenStatus[0]?.allowed!Exhaust quota in user_token_quotas and call /jarvisUnwrap const status = Array.isArray(tokenStatus) ? tokenStatus[0] : tokenStatus; (or .single())
Starter-tier or unauthorized users invoke Jarvis & burn Gemini/ElevenLabs spendjarvis/index.ts never checks company_has_module(companyId, 'jarvis') (min_plan = 2) or has_permission()Call /jarvis with Starter-plan user JWTEnforce company_has_module & has_permission(companyId, 'jarvis', 'VIEW')
Crafted [SYSTEM_CONFIRM] executes arbitrary allowed-table writes/emailsjarvis/index.ts:210-212 parses pending_action from client request body instead of reading stored jarvis_history.action_widgetSend modified pending_action with any recent pending_message_idLoad canonical action_widget from jarvis_history (or whitelist editable fields)
Confirming/rejecting a card > 30 min old sends "[SYSTEM_CONFIRM]" to Geminijarvis/index.ts:198-204 clears pendingActionStr without returning early, falling into Flow 2Confirm a card older than 30 minReturn HTTP 410 / 400 immediately when expired
Solo meetings stripped with "BŁĄD WIDŻETU (FLUTTER CRASH PREVENTED)"System prompt Rule 6[B] (index.ts:665) omits attendees for solo meetings, while pre-flight validator (index.ts:858) requires Array.isArray(google_calendar_payload.attendees)Ask Jarvis to book a solo calendar eventDefault google_calendar_payload.attendees = [] in prompt & validator
Missing googleToken writes literal "PENDING_DOC_URL" to DB or silently drops Google-only calendar eventsBranch 1f (index.ts:383) falls through to Branch 1g when !googleToken; Branch 1g skips Planovi when calendar_save_pref === 'google' (index.ts:425) and still returns 200 confirmedConfirm create_doc or Google-only event with expired/missing tokenReturn explicit 400 error when googleToken is required
Pre-reminder reminder_alert cards unhandled; non-calendar inserts fail if table has no user_idindex.ts:239 handles only reminder_alarm; index.ts:473 forces insertPayload.user_id = user.id on all non-calendar tablesConfirm a reminder_alert or insert into table lacking user_idHandle reminder_alert and only set user_id on tables that have it