-
-
Architecture at a glance
-
Routing Rationale: Deterministic logic prioritizing cashless empanelment over minimal distance differences.
-
Baseline & Records : Secure ingestion of medical documents bound to the patient's verified health history
-
Bounded Payments: Pre-authorized Razorpay mandate enforcing strict per-bill and cumulative spend limits.
-
Routing Rationale: Deterministic logic prioritizing cashless empanelment over minimal distance differences.
-
Policy Coordination: Comprehensive admission brief aggregating patient baseline, Star policy limits, and real-time cashless eligibility.
-
Active Case Overview: Real-time dashboard showing client-side Gemini Nano processing, instant deterministic triage severity.
Inspiration
When an aging parent living in India experiences a sudden medical emergency, their adult child living abroad is forced to coordinate care across time zones in the middle of the night. Messages arrive in mixed Tamil, Hindi, or Tanglish; nobody knows which nearby hospital actually has a cardiac ICU and cashless network empanelment with the parent's insurer; lab reports pile up without baseline context; and families end up paying unexpected out-of-pocket deposits without knowing why.
We built KinGuard to replace frantic phone trees with one accountable rule: agents propose, deterministic guards decide, and a cryptographic receipt chain records every step.
What it does
KinGuard coordinates the full emergency-to-recovery loop for an aging parent using synthetic demo records:
- Privacy-First Hybrid AI Intake (/app): Before text leaves the browser, deterministic client-side redaction (maskPII) masks direct identifiers such as phone numbers, emails, IDs, postal codes, and explicit numbered units. Using Firebase AI Logic (firebase/ai v13.4.0), explicit English requests initialize and prefer on-device Gemini Nano in supported desktop Chrome (InferenceMode.PREFER_ON_DEVICE), while Tamil, Hindi, Tanglish, mixed-language, and unsupported-browser requests route to Cloud Gemini (gemini-3.5-flash-lite) protected by Firebase App Check (ReCaptchaEnterpriseProvider).
- Deterministic Triage and Hospital Routing: AI normalisation stays strictly advisory. Deterministic Python RED_FLAGS rules classify severity (HIGH, MEDIUM, LOW) and rank hospitals by capability, distance, and cashless network match.
- Arrival Brief, Record Deltas, and Multilingual Companion: Families get an authenticated Arrival Brief, lab-report delta tracking against baseline readings (via multimodal Gemini vision), a plain-language companion in English, Tamil, or Hindi, and a Listen (speechSynthesis) read-aloud option for elderly parents.
- Clinician Handoff (/handoff/{token}): Time-bounded, HMAC-signed 1-hour handoff links let bedside clinicians extract structured orders via Firebase Hybrid AI before explicit human confirmation.
- DPDP / Policy Gate, Claims, and Razorpay Test Payments: Code-level guards block clinical lab values from leaking over WhatsApp status templates, assemble pre-authorization packets, enforce per-bill and total mandate caps before creating Razorpay Test Mode (rzp_test_) payment links, and track 14-day post-discharge check-ins.
- Publicly Verifiable Audit Trail (/api/cases/{case_id}/verify): Anyone (family or insurer) can verify the integrity of a case's receipt chain without accessing private clinical data.
How we built it
Architecture: Separating Probabilistic Models from Deterministic Guards
- Client Hybrid AI Layer (firebase/ai + firebase/app-check): Shares a single lifecycle module (hybrid.js) across /app and /handoff/{token}, calling initializeDeviceModel() from the user-click path with download progress and strict request-context guards so stale async responses never bleed across case switches or sign-out.
- Backend Coordination and Guards (FastAPI + Google ADK + Gemini): Five specialized Google ADK sub-agents (onboarding_agent, triage_agent, evidence_agent, insurer_liaison_agent, whatsapp_agent) operate behind deterministic Python policy, mandate, and redaction boundaries.
- Hospital Scoring Math: For each candidate hospital h at Haversine distance d km (R = 6371 km) from the parent's location, KinGuard computes a deterministic weighted score:
P(d) = max(0, 1 - min(d, 15) / 15)
Score(h) = wc * C(h) + wd * P(d) + wn * N(h)
where C(h) in [0, 1] measures specialty and dedicated-unit capability (such as cardiac_icu or stroke_unit), N(h) in {0, 1} indicates cashless network match, and the weights (wc, wd, wn) shift with severity:
- HIGH severity: (0.60, 0.20, 0.20)
- MEDIUM severity: (0.40, 0.35, 0.25)
- LOW severity: (0.15, 0.60, 0.25) This explains why a HIGH-severity cardiac case deliberately accepts a slightly farther hospital when it has a dedicated cardiac ICU and cashless empanelment.
- Tamper-Evident Provenance Ledger: Every action writes a canonical JSON receipt r_k chained to the previous digest H_(k-1) and signed with Ed25519, stored alongside an atomic count/head checkpoint: H_0 = 64 zeros H_k = SHA-256(canonical(r_k) || H_(k-1)) signature_k = Sign_Ed25519(H_k) Any post-hoc payload edit or tail truncation breaks chain verification (verified = false) at the exact tampered sequence index k.
Challenges we ran into
- Async Race Conditions and Client State Isolation: Late-arriving brief, bill, UPI, or Hybrid AI responses from Case A could overwrite Case B after a quick switch or sign-out. We fixed this with request-generation counters, captured authorization contexts, and paired JavaScript VM regression tests.
- First-Run Gemini Nano Activation and Language Routing: Chrome's Prompt API requires user-activation inside the click path (initializeDeviceModel()) and supports English rather than Tamil or Hindi. We split explicit English (PREFER_ON_DEVICE) from Tamil/Hindi/mixed inputs (ONLY_IN_CLOUD) so non-English requests never falsely claim local inference.
- App Check and Cross-Environment Reliability: Configuring Firebase App Check (ReCaptchaEnterpriseProvider), diagnosing 24-hour IndexedDB initial-throttle lockouts during testing, fixing Gemini Developer API minimum 10-second HTTP deadline constraints, and hardening Razorpay API calls against transient TLS resets (URLError) all required end-to-end live testing.
Accomplishments that we're proud of
- 1,299 passing automated tests (Python + Node.js behavioral browser regressions) plus a deterministic end-to-end verification spine (demo_spine.py) that proves tamper detection live.
- Real Firebase AI Logic + App Check + Razorpay Test Mode integration deployed live on Railway (https://kinguard-production-00aa1454.up.railway.app/app) with strict separation between advisory LLM output and code-enforced safety/payment guardrails.
- Zero-PII-exposure public verification (/api/cases/{id}/verify) paired with authenticated clinical records and signed 1-hour clinician handoff links.
What we learned
- Guardrails belong in deterministic code, not prompts: Letting an LLM normalize messy Tanglish into candidate terms is helpful; letting it decide emergency severity, bypass WhatsApp privacy rules, or exceed a payment cap is dangerous.
- Honest provenance matters as much as automation: Explicitly labelling simulated insurer/TPA adjudication, seeded hospital capability snapshots, client-side heuristic PII masking, and actual SDK-reported inference sources (on_device vs in_cloud) makes the system auditable and trustworthy.
What's next for KinGuard
- Live insurer/TPA pre-authorization APIs and ABDM (Ayushman Bharat Digital Mission) health-record integration once regulatory credentials are available.
- Multi-language caregiver notifications and external trust-anchor notarization for database-wide rollback protection.
Prior Work and Prototype Disclosures
- Existing work and contest-period additions: KinGuard builds on an existing renamed local eldercare/insurance codebase (original creation date unknown). During the Firebase Hybrid AI Hackathon window (repo created 24 November 2026), the team added the Firebase AI Logic (13.4.0) hybrid inference and App Check layer, client-side PII masking, companion summaries, bedside handoff extraction, authentication/race-condition/receipt-checkpoint hardening, timeout and Razorpay error-handling fixes, and live deployment/testing (see DISCLOSURE.md and docs/PROVENANCE_EVIDENCE.md).
- Simulations and test scope: All demos use synthetic patient data. Insurer/TPA adjudication uses deterministic local rules (not a live insurer API), hospital capability/empanelment uses a seeded snapshot (while hospital coordinates use Google Places), and payments run strictly in Razorpay Test Mode (rzp_test_).
