Context and Engineering Challenge
The operational and legal management of complex condominium ecosystems faces a critical bottleneck: inefficiency and decentralization in processing occurrences, violations, and audits of internal regulations. The traditional flow is manual, slow, and highly susceptible to human errors. It requires the administrator to interpret subjective complaints, sift through extensive textual statutes in PDF, consult external macroeconomic indices (such as historical minimum wage), and draft legal notifications at the risk of legal challenges due to incorrect citations.
Camapum was designed to solve this problem end-to-end through a distributed architecture that combines a secure web application and an asynchronous Artificial Intelligence engine. The two non-negotiable engineering pillars of the project are:
- Absolute Logical Isolation (Zero-Trust Data Isolation): Ensuring that multiple tenants (multi-tenancy) share the same database infrastructure without any risk of data leakage between competing condominiums.
- Algorithmic Determinism in AI: Orchestrating LLMs to operate as high-precision legal engines, eliminating hallucinations through dynamic context partitioning and mathematical validation of financial data.
Software Architecture and Layer Division
1. Presentation Layer and Client-Side State (Frontend)
- Single Page Application (SPA): Developed in React 18 and TypeScript, using Vite as the build tool to ensure minimal startup times and efficient hot-reloading.
- Routing and Security Guards: Client route control is managed by React Router DOM v6, implementing higher-order components (HOCs) to encapsulate authorization logic based on RBAC (Role-Based Access Control), strictly separating scopes through
AdminProtectedRoute and SindicoProtectedRoute.
- Asynchronous State Management: Utilizing TanStack React Query v5 to orchestrate the lifecycle of HTTP requests, intelligent network caching, background query invalidation (stale-while-revalidate), and optimistic UI updates.
- Interface and Design System: Built on accessible and agnostic components from Radix UI (via Shadcn UI), styled with Tailwind CSS, enriched with microinteractions via Framer Motion, and rendering statistical data with Recharts.
2. Persistence and Multi-Tenant Isolation (Backend & BaaS)
- Multi-Tenancy at the Data Layer: The ecosystem adopts Supabase (PostgreSQL) as the core of persistence. Data security and logical isolation do not rely on client-side validations; they are enforced natively at the database level through Row-Level Security (RLS) policies.
- Custom PL/pgSQL Policies: Queries and mutations (select, insert, update, delete) are intercepted by the Postgres engine, which dynamically evaluates the context of the authenticated user (
auth.uid()) through authorization functions like has_role and is_sindico_of_condo, ensuring strict partitioning of records.
- Compute and File Storage: The upload of regulations and physical evidence of occurrences is processed in private and structured buckets of Supabase Storage. Critical administrative routes and write privilege logic are isolated in serverless microservices via Supabase Edge Functions.
3. Automatic RAG Pipeline (Retrieval-Augmented Generation)
The system eliminates the need to train or fine-tune heavy models by implementing an automated knowledge ingestion pipeline as soon as a new regulatory document is inserted into the platform:
- Detailed Semantic Segmentation: The processing flow in n8n captures the PDF file and submits it to a Recursive Character Text Splitter (LangChain). The text is broken into structured chunks of 500 characters with a strategic overlap of 100 characters, preserving the conceptual integrity of sections, articles, and paragraphs without abrupt syntax breaks.
- Partitioned Vector Indexing: The textual fragments are converted into dense 1536-dimensional vectors using OpenAI's Embeddings models. These vectors are stored directly in the database's document table, indexed via the
pgvector extension, and must be linked to the metadata of condo_id.
- Hybrid Search with Cohere Reranker: During a cosine similarity search, to avoid textual noise and optimize the LLM's context window, the database retrieves the top 10 vector matches. Then, a Cohere Reranker layer semantically reclassifies the relevance of these excerpts concerning the reported violation, injecting only the 4 most precise fragments into the final AI prompt.
4. Process Orchestration via Multi-Agent Architecture
Decision-making and the generation of the final legal document are distributed among multiple sub-agents specialized in n8n, ensuring that each model performs an atomic and deterministic task:
- Agent A0 (Fact & Normalization): Consumes the raw occurrence report, eliminates descriptive noise, and structures it into a typed JSON payload through modular JavaScript scripts.
- Agent A1 (RAG Retrieval): Solely responsible for scanning the restricted vector database of that specific
condo_id, extracting the literal excerpts of the violated regulations, acting as a safeguard against LLM hallucinations.
- Agent A2 (Financial Calculation and OData Integration): Consumes real-time macroeconomic indices through the IpeaData OData API to retrieve the exact value of the current minimum wage. Equipped with a mathematical calculator tool from LangChain, the agent executes the decimal conversion equation for the penalty (e.g., applying a percentage over the regulatory ceiling), ensuring absolute financial accuracy and immunity to logical inference failures from text.
- Agent A3 (Deadline, Defense, and Legal Resolution): Isolates and formats the clauses of contradiction, clearly specifying the deliberative instances and legal deadlines for the notified resident to file administrative appeals.
Technical Highlights and Challenges Overcome
- Decentralization and Data Shielding: Success in architecting a multi-tenant ecosystem where security is applied at the database level (RLS), mitigating impersonation attacks or security bypass failures in frontend routes.
- Absolute Mitigation of Hallucinations: The combination of segmentation by LangChain, isolated indexing via
pgvector by metadata, and secondary filtering through semantic re-ranking ensured a surgical accuracy rate in citations of articles and penalties.
- Automatic Closure of the Operational Cycle: n8n manages data persistence transactions to record history in the
agente_execucoes table, updates row statuses in Supabase, and interacts with the Google Drive and Google Docs APIs to generate standardized official documents ready for signature and legal submission.
Results and Impact
The integration of the web platform with the intelligent workflow engine transformed a complex administrative process that used to take days into an automated operation of under 60 seconds. The ecosystem provides total transparency and auditability to condominium management (as every generated notification explicitly cites the legal evidence and the actual calculation), under a highly scalable, decoupled, and resilient serverless architecture.