Skip to content
PT®
The public home page of RitoTech at ritotech.vercel.app, with an illustrative court notice shown on a phone

003 Case study

All work

Legal Intelligence

Ships as RitoTech

Category
Legaltech / AI / Automation
Year
2026
Role
Solo · full stack
Status
Live

Authorship & scope

Authorship
Solo build, started from an empty folder on 4 November 2026.
In production
The web app runs on Vercel (gru1); the worker runs outside Vercel, on a provisional VPS since 12 November 2026. As of that date production ran the DJEN integration only. The Escavador sync and the AI explanations are implemented and tested (Escavador against mocked responses), but nothing shows them running in production.
Deadlines
It never calculates deadlines. Its AI prompt tells the model to quote any deadline text verbatim from the source, and the daily sheet lists the review dates that lawyers set on tasks, flagging overdue ones.
Documents
Its documents are the daily sheet as a PDF, a print view and copied text, plus a summary email with a link. It does not draft legal documents.

Overview

RitoTech is a multi-tenant SaaS that tracks a Brazilian law firm's cases and delivers a daily sheet of what changed. A separate worker reads the national court gazette (DJEN) by the office's bar registration (OAB) and case numbers. It can also pull full case activity from the paid Escavador API and have an LLM (Claude by default) explain each new movement in a schema-validated structure, under a prompt that forbids computing deadlines or inventing decisions. Paid queries and AI calls are costed and checked against a monthly budget the office sets.

Spec · from the code and docs, not live metrics

queue
Postgres + SKIP LOCKED
isolation
RLS per office
AI output
12-field zod schema
budget alerts
70 / 85 / 100%

Problem

Lawyers start the day checking courts case by case to see what moved, and an intimation missed in the official gazette can mean a lost deadline. The free national gazette carries only official communications. Full case activity sits behind a paid API, so complete coverage is billed per query. Software that paraphrases court text also cannot be allowed to invent a deadline or a decision.

Architecture

A Next.js 16 web app and a separate Node worker share one Supabase Postgres database, which also serves as the job queue. Screens enqueue long-running work. The worker claims jobs with FOR UPDATE SKIP LOCKED, calls DJEN, Escavador and the AI provider, and writes results that the app reads under row-level security scoped to each office.

  1. 01 · Client

  2. 02 · Web app · Vercel

  3. 03 · Postgres

  4. 04 · Worker · VPS

  5. 05 · Providers

built by me · tap a node to see its role

Connections in Legal Intelligence architecture:

  • Web UI to Next.js 16: synchronous.
  • Next.js 16 to Postgres: synchronous, RLS.
  • Next.js 16 to Job queue: asynchronous, enqueue.
  • Worker to Postgres: synchronous, results.
  • Worker to Job queue: synchronous, claim.
  • Scheduler to Job queue: asynchronous, enqueue.
  • Worker to DJEN: external integration.
  • Worker to Escavador v2: external integration.
  • Worker to LLM provider: external integration.
  • Worker to Email: external integration.

Layers

  1. Web app

    Next.js 16 App Router with Server Actions and route handlers. The Supabase Auth session lives in cookies, and a proxy rewrites '/' to the sales page for signed-out visitors. Every in-app Server Action checks the user's minimum role, and the browser never queries Supabase directly.

  2. Database

    Supabase Postgres with 8 versioned migrations. RLS is enabled on every table, with office-scoped policies built on user_org_ids(). Audit triggers record field-level diffs, and AES-256-GCM-encrypted API keys sit in a column the app role cannot select.

  3. Job queue

    A sync_jobs table with a partial unique index on dedupe_key for idempotency, ordering by priority then run_at, and exponential backoff with jitter. Jobs whose lock has not been renewed for 10 minutes go back to the queue, unless they have used up their attempts.

  4. Worker

    One Node process bundled with esbuild that runs one job at a time to stay light on 1 vCPU. Its jobs are DJEN sync, Escavador sync and polling, AI analysis, the daily sheet, sharing and retention cleanup. A scheduler checks every minute what is due in each office's time zone.

  5. Integrations

    The DJEN public API (reads rate-limit headers, pauses 60 s on HTTP 429), Escavador API v2 (cost read per call from the Creditos-Utilizados header), and either the Anthropic SDK or any OpenAI-compatible /chat/completions endpoint.

  6. Hosting

    The web app runs on Vercel (gru1). The repo also includes a Docker Compose stack (web, worker, Caddy TLS, memory limits) sized for a 1 vCPU / 4 GB VPS, plus a script that runs the worker as a Windows scheduled task with a DPAPI-encrypted config. Optional Healthchecks.io pings alert when the worker, the DJEN sweep or the daily sheet stops reporting.

Data flow · step by step

  1. The scheduler enqueues a DJEN sweep for each office every few hours (6 by default), deduplicated by key.

  2. The worker queries DJEN by each active OAB and each tracked case number. It stores each communication once under its official hash and records every source that matched it.

  3. A publication addressed to one of the office's OABs registers an unknown case automatically (on by default). A new publication on a tracked case queues an Escavador refresh, unless the case is set to manual or no Escavador token is configured.

  4. New movements are deduplicated across sources and queued for AI. Only movements from clients with a signed AI consent reach the model.

  5. The model returns a schema-validated analysis (category, priority, impact, suggested action and any deadline text quoted from the source). The analysis is cached by input hash and costed per call.

  6. At the configured hour (07:30 by default), the worker freezes an immutable sheet ordered by priority. It includes the open tasks whose review date is due and any alert about gaps in the DJEN capture.

  7. Lawyers read the sheet as a full-screen feed, a PDF or copied text, share a summary by email, and turn items into assigned tasks.

Technical decisions

  1. 01

    Postgres as the queue

    No Redis. A partial unique index on dedupe_key makes enqueueing idempotent, and FOR UPDATE SKIP LOCKED stops two workers from claiming the same job. The whole system runs on one database and is sized for a 1 vCPU / 4 GB VPS, with memory limits set in docker-compose.yml.

  2. 02

    Quote deadlines, never compute them

    The system prompt forbids date arithmetic and forbids asserting that a deadline is running. When the text names a deadline, the model must copy the literal excerpt into prazo_mencionado. Lawyers set review dates on tasks, and each daily sheet lists the open ones due by that day (up to 50), flagging overdue ones.

  3. 03

    Immutable, versioned daily sheets

    Each sheet item stores a JSON snapshot, and each period starts where the previous one ended. Regenerating creates the next version and keeps the old one, so reprocessing a movement never rewrites what a lawyer already read.

  4. 04

    Budget check before paid work

    Escavador cost comes from the Creditos-Utilizados header, and AI cost from token usage priced per model. Before an automatic Escavador sync, the worker adds the 30-day average cost of the calls it will make to the month's spend and skips the sync if the total would cross the limit, unless the office allows overruns. AI analysis stops once spend passes the limit, and AI costs count in reais only once the office sets a dollar rate. Alerts fire once a month at 70, 85 and 100%.

  5. 05

    Consent and data minimization before AI

    Movements from clients without a signed AI consent stay blocked (CFOAB Recommendation 001/2024). The case context sent to the model gives class, subject, area, court and instance, and leaves out party names. Identical inputs reuse a cached analysis at no cost.

Challenges

  1. Challenge 01

    A failed capture must never read as 'no news'

    The DJEN query window advances only when every query succeeds. Three consecutive remote failures, confirmed by a lightweight ping, trip a circuit breaker, and the scheduler retries in an hour. Meanwhile the sheet shows 'capture incomplete' with the last complete query time.

  2. Challenge 02

    Deduplicating sources without hiding an intimation

    The same publication can arrive from DJEN and from Escavador under different titles. A copy is set aside as a duplicate only when its normalized text is identical and the dates are within five days, because PROJUDI intimations to plaintiff and defendant can differ by one word. A visible duplicate beats a hidden deadline.

  3. Challenge 03

    The DJEN 10,000-result ceiling

    Past the cap, the API stops returning pages and the rest would disappear without an error. searchAll halves the date range recursively until each slice fits. A single day still above the cap fails visibly and keeps the window from advancing.

  4. Challenge 04

    A year of history without flooding the sheet

    Registering an OAB imports 12 months in 30-day windows. Anything older than seven days (the default) is stored as history: it shows on the case timeline but stays out of the sheet, the AI queue and paid Escavador calls.

Implementation

  1. DJEN adapter, checked against the official Swagger: 100 items per page, a 3.5-second minimum gap between calls, a 60-second pause on HTTP 429 and no IP rotation. While parsing it removes NUL bytes and repairs lone surrogates, so one malformed item cannot block a sweep.

  2. Escavador v2 adapter: built from the official v2 docs and tested against mocked responses. It requests an asynchronous court refresh and polls its status at growing intervals, and it paginates movements by cursor, stopping at the first page that holds a known movement id. It checks the host, so the bearer token never follows a pagination link to another domain.

  3. AI layer with two providers: Anthropic structured output (zod schema, low effort where the model supports it, prompt caching) or any OpenAI-compatible endpoint validated against the same schema. Refusal, auth, rate-limit and invalid-output errors map to typed errors, and analyses are cached by a SHA-256 key over prompt version, model and input.

  4. Daily sheet: a full-screen feed with J/K navigation, a server-side PDF built with pdfkit (no headless browser), a print view and copied text, plus a summary email with a link for office members. Items are inserted in batches of 1,000 to stay under Postgres's parameter limit.

  5. Security: per-office RLS, a minimum-role check in every in-app Server Action, audit triggers, encrypted credentials, and CSP and HSTS in production. In-memory rate limits cover logins, manual refreshes, AI reprocessing and downloads. Court documents are proxied on demand and never stored.

  6. Tests: 97 Vitest cases across five files. The database suites boot embedded Postgres (PGlite) with the real migrations and a minimal Supabase auth stub. Together they cover RLS isolation, queue locking, DJEN, Escavador, AI caching, consent and sheet snapshots, with the external APIs mocked.

Technologies

  • Next.js 16
  • React 19
  • TypeScript
  • Supabase Auth
  • PostgreSQL (RLS)
  • postgres.js
  • Anthropic SDK (Claude)
  • OpenAI-compatible API
  • Zod
  • pdfkit
  • unpdf
  • Nodemailer
  • Tailwind CSS 4
  • Vitest
  • PGlite
  • esbuild
  • Docker Compose
  • Caddy
  • Vercel
  • DJEN API
  • Escavador API v2

Results

  • Live at ritotech.vercel.app (checked 24 November 2026).

  • 8 versioned SQL migrations in supabase/migrations.

  • 97 Vitest test cases; the database tests run the real migrations on embedded Postgres (PGlite).

  • Deployment files in the repo: a Dockerfile, Docker Compose (web, worker, Caddy) and install, update and backup scripts.

004 Next caseAutomation Infrastructure

Backend / Integrations / Systems

All work

Case 003 of 004

Nothing matches “”.

↑↓ MoveEnter Open0 results

pedro@portfolio: ~

Type help for the commands. Tab completes, ↑ ↓ walk the history, Esc closes.