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 underjarvis/prompts/,jarvis/services/, andjarvis/tools/are 100% orphaned dead code (zero imports) left behind by merge580d691when the hardened monolith won over an unhardened modular branch. - Actors: Authenticated company member (
company_members.is_active = true), Flutterjarvis_chat_provider,reminder-scheduler(injectingreminder_alert/reminder_alarmcards), and external APIs (Gemini, ElevenLabs, Google Calendar/Gmail/Docs).
2. All Features & End-to-End Flows
- Auth, Parsing & Pre-checks (
jarvis/index.ts:74-205):config.tomlsetsverify_jwt = false;index.tsenforces GoTruesupabaseAdmin.auth.getUser(token)(401).- Parses
application/jsonORmultipart/form-data(voice WAV). - Resolves
googleToken(requestgoogletoken/google_token-> latestuser_google_tokens.access_token, no refresh flow) andcompanyId(unordered.limit(1)activecompany_members, ignoring bodycompany_id;403if none). [SYSTEM_COMMAND]*->200 { status: "context_wiped" }.- Verifies
pending_message_idownership(id, user_id, company_id)(404on confirm/reject if missing) and30 minTTL.
- 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-emptycriteriaonUPDATE/DELETE,assertCompanyUsersonuser_id/assignee_ids. - Dedicated branches:
reminder_alarm(snoozed->+10 min,pre_reminder_time = -5m,status = 'pending'; else writesuser_actionverbatim), Google Calendar sync (fail-safe whencalendar_save_pref ∈ {'both','google'}), Gmail send (blocking),set_reminder,create_offer(status: 'draft'), Google Doc creation +'PENDING_DOC_URL'replacement, and generic Planovi DBINSERT/UPDATE/DELETE(multi-assignee calendar fan-out with sharedgroup_id = crypto.randomUUID()). - Marks
jarvis_history.action_widget.confirmed = true(200) orconfirmed = false+ Polish debug error message (400).
- Pre-flight DB guard on generic
- Flow 1B — Reject Action (
[SYSTEM_REJECT],index.ts:512-516): Hard-deletesjarvis_historyrow scoped to(id, user_id, company_id)->200 { status: "rejected" }. - 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 50clients, 50company_members, 20calendar_events(unusedallEvents), and last 6jarvis_historyrows. - Calls
get_user_token_status(broken array check — never blocks!) -> Gemini Hop 1 (gemini-2.5-flash,temperature: 0.1, JSON mode) -> ifintent === 'QUERY_DB', validates table inJARVIS_READABLE_TABLES={calendar_events, clients, client_attachments, client_notes, reminders, client_offers}&SAFE_IDENTIFIERcolumn, queriescompany_id(limit 15), runs Gemini Hop 2. - Rewrites
[SILENCE]to Polish retry prompt -> billsrecord_ai_token_usage(companyId, user.id, 'jarvis', prompt, completion)-> runs Flutter crash-prevention pre-flight check (strips malformedcalendar_event/send_emailwidgets) -> savesusermessage -> optional ElevenLabs TTS (21m00Tcm4TlvDq8ikWAM,eleven_multilingual_v2, uploaded toclient_files/jarvis_audio/jarvis_response_${Date.now()}.mp3) -> savesjarvisreply (omitting widget onVOICE_CONFIRM/VOICE_REJECT) -> returns200 aiContent.
- Fetches live PostgREST OpenAPI schema (
3. Hard Business Rules, Validations, Calculations & Edge Cases (BR-JARVIS)
BR-JARVIS-01(Strict Auth & Server-Derived Company): GoTrueauth.getUserrequired (401);companyIdderived strictly from activecompany_members(403).BR-JARVIS-02(Pending Card Ownership & 30-Min TTL):pending_message_idmust match(id, user_id, company_id)injarvis_historyand be<= 30 minold (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-emptyUPDATE/DELETEcriteria; RAG reads restricted to{calendar_events, clients, client_attachments, client_notes, reminders, client_offers}(limit 15,company_id-scoped). All targetuser_id/assignee_ids/assigned_to_user_idvalidated viaassertCompanyUsers.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 sharedgroup_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_remindersetspre_reminder_sent = trueifpre_reminder_time <= now.BR-JARVIS-06(Flutter Pre-Flight Guard): Stripsaction_widgetand returns Polish debug error ifcalendar_eventlackstitle/start_time/end_time/date_display/google_calendar_payload.attendees(Array) orsend_emaillacksto/subject/body.BR-JARVIS-07(Token Billing): Callsrecord_ai_token_usage(feature='jarvis',billed = ceil((prompt + completion) * margin)). Intended429pre-check viaget_user_token_statusis 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/jsonormultipart/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; RPCsget_user_token_status,record_ai_token_usage; Storageclient_files/jarvis_audio/*.mp3. - External APIs: Gemini
gemini-2.5-flash, ElevenLabseleven_multilingual_v2(voice21m00Tcm4TlvDq8ikWAM), Google Calendar v3, Gmail v1, Google Docs v1.
6. Cross-Repository Dependencies
| Caller -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
planovi-flutter-app (jarvis_chat_provider) -> jarvis/index.ts | HTTPS POST / User JWT + optional Google OAuth token | Strict action_widget schema, VOICE_CONFIRM/VOICE_REJECT -> [SYSTEM_CONFIRM]/[SYSTEM_REJECT], elevenlabs_audio_url |
reminder-scheduler <-> jarvis/index.ts | Shared 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 merge580d691preserveddevelop’s security-hardened monolith while leaving an older unhardened refactor (24d6cfc) orphaned inprompts/,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 Message | Root Cause in Code | How to Verify / Exact Query or Log | Fix |
|---|---|---|---|
Users exceed monthly AI token quota and never get HTTP 429 | get_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 /jarvis | Unwrap const status = Array.isArray(tokenStatus) ? tokenStatus[0] : tokenStatus; (or .single()) |
| Starter-tier or unauthorized users invoke Jarvis & burn Gemini/ElevenLabs spend | jarvis/index.ts never checks company_has_module(companyId, 'jarvis') (min_plan = 2) or has_permission() | Call /jarvis with Starter-plan user JWT | Enforce company_has_module & has_permission(companyId, 'jarvis', 'VIEW') |
Crafted [SYSTEM_CONFIRM] executes arbitrary allowed-table writes/emails | jarvis/index.ts:210-212 parses pending_action from client request body instead of reading stored jarvis_history.action_widget | Send modified pending_action with any recent pending_message_id | Load canonical action_widget from jarvis_history (or whitelist editable fields) |
Confirming/rejecting a card > 30 min old sends "[SYSTEM_CONFIRM]" to Gemini | jarvis/index.ts:198-204 clears pendingActionStr without returning early, falling into Flow 2 | Confirm a card older than 30 min | Return 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 event | Default google_calendar_payload.attendees = [] in prompt & validator |
Missing googleToken writes literal "PENDING_DOC_URL" to DB or silently drops Google-only calendar events | Branch 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 confirmed | Confirm create_doc or Google-only event with expired/missing token | Return explicit 400 error when googleToken is required |
Pre-reminder reminder_alert cards unhandled; non-calendar inserts fail if table has no user_id | index.ts:239 handles only reminder_alarm; index.ts:473 forces insertPayload.user_id = user.id on all non-calendar tables | Confirm a reminder_alert or insert into table lacking user_id | Handle reminder_alert and only set user_id on tables that have it |