All case studies
~/cases/direto-ao-ponto
Applied AIIntelligence and AIOct 2026 → todayIn production

P-04

Direto ao Ponto

An AI assistant that only answers with a source, with spend capped at four layers.

A free public chat that explains a constitutional change to working hours in Brazil. Answers come from 37 fact sheets reviewed in git, with mandatory citations and the legal status of each rule. The site and API run on one Cloudflare Worker, backed by Supabase with RLS on every table, atomic Postgres quotas and an admin panel that runs everything without a deploy.

US$ 0.0006–0.0011
cost per answer
22/22
RAG recall (top-7)
37 / 47
fact sheets / sources
29
evaluation cases
  • cloudflare
  • supabase
  • postgres
  • rls
  • rag
  • llm
  • streaming
  • astro
  • rate-limiting
  • lgpd
architecture.en.svgenlarge ↓

01Overview

Direto ao Ponto ("Straight to the Point") is a free public platform that explains, in plain Portuguese, the end of Brazil's 6-on-1-off work schedule (the "6x1") and the transition to a shorter working week. Its centerpiece is an AI chat. You say whether you're a worker, an employer or just curious, ask your question, and get a short answer that cites an official source for every claim. Each answer also states clearly what is already in force, what has passed but isn't in effect yet, and what still depends on collective bargaining or future regulation.

The chat sits next to a calculator ("What changes for me?") that does its math in deterministic code rather than through the AI, a timeline of the legislative process and a page that explains the editorial method. The same chat can also be dropped into other websites as a single JavaScript file.

The backend was built for a service that is open to the whole internet. Every answer is limited to a curated knowledge base, AI spend has a ceiling at four separate layers, and a small team runs everything from an admin panel with no redeploys.

02The problem

  • Changes to labor law set off a wave of practical questions ("will my pay go down?", "when does it start?", "does it cover domestic workers?"). Meanwhile the information that circulates mixes the approved text with alternative proposals, projections and opinion.
  • A generic chatbot makes this worse. It invents deadlines, rounds numbers and presents rules that are still phasing in as if they were already law.
  • A public AI chat is also a target: anyone can fire off thousands of questions and turn curiosity into an invoice.
  • The team had to update content as events unfolded (the amendment was enacted and published during development) without rewriting the system.

03The solution

  • Knowledge base versioned in git: 37 Markdown fact sheets, one fact each. Every sheet carries a status (in force, approved, scheduled, depends on bargaining, under debate, estimate), sources and a last-updated date, and 47 sources are cataloged. A build step validates everything and fails on a missing status or a reference to an unknown source.
  • Mandatory citations: the model cites sheets by ID ([[salario-mantido]]) and the frontend turns each ID into a numbered reference linked to its source. The model never writes links. Every link comes from the knowledge base.
  • Rich answers: the model writes lean Markdown plus blocks (:::cards, :::numeros, :::linha-do-tempo, :::estudo, :::atencao…). A custom parser that tolerates incomplete input turns them into components while the answer streams.
  • Profiles (worker, employer, just curious) change the angle of the answer without breaking the prompt cache.
  • Demo mode: with no AI key, or with the panel switch on, the chat assembles answers from the knowledge base through keyword matching, at no cost.
  • Calculator for days off, weekly hours and hourly pay, all computed in deterministic code.
  • Embeddable widget: npm run widget produces a single .js file (Preact plus the public knowledge base, about 25 KB gzipped per the README) that any site mounts on a <div data-chat-6x1>.
  • Admin panel with six tabs: AI account balance, usage and cost, conversations, feedback, operations (model, kill switch, demo mode, RAG, quotas, answer length) and admin management.
  • RAG built, measured and switched off on purpose: hybrid search on pgvector is one click away. It stays off while the whole knowledge base still fits in the cached prompt.
  • Locked-down database: RLS on every table, anon/authenticated grants revoked, 9 admin-only policies
  • Spend capped at four layers: native rate limit, atomic fail-closed daily quota in Postgres, credit-limited key and a panel kill switch
  • A ~25k-token prompt kept byte-for-byte stable for caching: US$0.0006–0.0011 per answer measured in production
  • Mandatory citations: the model never writes links; every link comes from fact sheets versioned in git
  • Hybrid RAG (pgvector + FTS + RRF) measured at 22/22 recall and deliberately left off
  • Admin revocation takes effect immediately: the Worker re-checks the current role on every request, not just the JWT
Direto ao Ponto home page with the chat window and suggested questions
Direto ao Ponto home page with the chat window and suggested questions
Assistant answer with numbered citations and the "Where this answer comes from" panel
Demo mode: answer assembled from the fact sheets, without AI
Calculator comparing the current work week with the new rule
Calculator comparing the current work week with the new rule
Timeline of the amendment, from Congress to publication
Timeline of the amendment, from Congress to publication

04Architecture

real architecture · hover over the nodes
Read the diagram as a list (14 components, 16 connections)

Components

  • Clients: Browser<br>Astro + Preact site, Embedded widget<br>partner sites, CORS allowlist, /admin panel<br>email OTP login
  • Cloudflare Worker: site + API on the same origin: Static assets<br>Astro dist/, /api/chat · /api/feedback<br>/api/saude · /api/admin/*, Native rate limit<br>20 questions/min per IP hash, kb.json bundled at build<br>37 fact sheets + cacheable prompt, Hourly cron<br>balance + alert, Workers AI<br>bge-m3 embeddings
  • Supabase: Postgres + pgvector + pg_cron<br>RLS on every table, consumir_cota()<br>daily quota per person and global, Supabase Auth<br>closed signup · app_metadata.role

Connections

  • Browser<br>Astro + Preact site → Static assets<br>Astro dist/
  • Browser<br>Astro + Preact site → /api/chat · /api/feedback<br>/api/saude · /api/admin/* (POST, streamed text)
  • Embedded widget<br>partner sites, CORS allowlist → /api/chat · /api/feedback<br>/api/saude · /api/admin/* (POST, streamed text)
  • /admin panel<br>email OTP login → /api/chat · /api/feedback<br>/api/saude · /api/admin/* (JWT Bearer)
  • /admin panel<br>email OTP login → Postgres + pgvector + pg_cron<br>RLS on every table (reads via PostgREST + RLS)
  • /api/chat · /api/feedback<br>/api/saude · /api/admin/* → Native rate limit<br>20 questions/min per IP hash
  • Native rate limit<br>20 questions/min per IP hash → consumir_cota()<br>daily quota per person and global
  • /api/chat · /api/feedback<br>/api/saude · /api/admin/* → kb.json bundled at build<br>37 fact sheets + cacheable prompt
  • /api/chat · /api/feedback<br>/api/saude · /api/admin/* → Workers AI<br>bge-m3 embeddings (optional RAG mode)
  • /api/chat · /api/feedback<br>/api/saude · /api/admin/* → Postgres + pgvector + pg_cron<br>RLS on every table (secret key)
  • /api/chat · /api/feedback<br>/api/saude · /api/admin/* → OpenRouter<br>Claude Haiku with prompt cache (SSE)
  • /api/chat · /api/feedback<br>/api/saude · /api/admin/* → Supabase Auth<br>closed signup · app_metadata.role (getClaims + current role)
  • Hourly cron<br>balance + alert → OpenRouter<br>Claude Haiku with prompt cache (/credits)
  • Hourly cron<br>balance + alert → Postgres + pgvector + pg_cron<br>RLS on every table
  • kb/ in git<br>editorial source of truth → kb.json bundled at build<br>37 fact sheets + cacheable prompt (build-kb)
  • kb/ in git<br>editorial source of truth → Postgres + pgvector + pg_cron<br>RLS on every table (sincronizar-kb: embeddings only for what changed)

The design rests on three decisions:

  • Site and API share one Worker. run_worker_first = ["/api/*"] serves pages straight from the asset cache and runs code only for the API. Because the main site is same-origin, it needs no CORS.
  • The prompt comes from the build, not the database. The Worker ships the same kb.json the site uses to render citations, so the model never sees a sheet the frontend can't resolve. The database holds a copy for search, metrics, quotas and configuration.
  • Git is the source of truth and the database is a copy. Editorial content is never edited in Postgres. The sync script re-embeds only the sheets that changed.

05Under the hood

Backend and data
  • TypeScript Cloudflare Worker (src/worker/, 16 modules): routing, chat, quotas, validation, feedback, admin, admin management, model catalog, an OpenRouter client with a custom SSE parser, RAG and balance collection.
  • 12 API routes: 4 public (/api/chat, /api/feedback, /api/saude, /api/config-publica) and 8 admin (/api/admin/eu, openrouter, saldo/coletar, config, modelos, admins GET/POST, admins/remover).
  • End-to-end streaming: the Worker consumes OpenRouter's SSE and re-emits plain text through a TransformStream. Each conversation is logged inside ctx.waitUntil once the response has gone out: tokens, cache hits, real cost, latency, cited vs. retrieved sheets and stop reason.
  • Supabase Postgres: 6 migrations, 8 tables, 4 security_invoker views and 3 pg_cron retention jobs.
  • Hybrid RAG: vector(1024) with a cosine HNSW index, a Portuguese tsvector with a GIN index, and a buscar_fichas function that merges both rankings with Reciprocal Rank Fusion. Embeddings come from the multilingual @cf/baai/bge-m3 model through the Workers AI binding, so there is no extra vendor. Each query uses the last two user questions so follow-ups still retrieve the right sheets.
  • Live configuration: a config jsonb table holds the model, the kill switch, quotas and limits. Each isolate caches it for 30 s, so a panel change reaches every server within 30 seconds without a deploy.
  • Prompt caching: the instructions and every sheet form a stable system block marked cache_control: ephemeral, with the provider pinned to Anthropic (allow_fallbacks: false). Date, profile and origin are appended to the last user message and never to the system prompt, so the cache stays intact.
Frontend
  • Astro 7 + Preact 11: static pages (home with chat, calculator, timeline, method, 404, admin) with interactive islands.
  • Streaming answer parser (src/lib/formato.ts, unit-tested) that interprets Markdown and blocks as tokens arrive and tolerates broken syntax. Everything renders as JSX; the codebase has no innerHTML or dangerouslySetInnerHTML.
  • Custom design system with tokens, View Transitions between pages and motion that respects prefers-reduced-motion.
  • Admin panel in Preact. It authenticates with Supabase Auth (8-digit email OTP), reads data directly through PostgREST under RLS and writes only through the Worker.
  • Widget (src/widget/) bundled as a single file. The host site owns the styling (cx-* classes); the script only emits markup.
Infrastructure and deploy
  • Cloudflare Workers with static assets, the Rate Limiting and Workers AI bindings, an hourly Cron Trigger, version_metadata (the version shows up in /api/saude) and observability enabled.
  • Managed Supabase (São Paulo region) with pgvector and pg_cron. The full stack also runs locally through supabase start (Docker), with Mailpit catching login emails.
  • Deploy pipeline: supabase db push → knowledge-base sync → wrangler deploy → HTTP contract test against production. The docs spell out the order for adding versus removing sheets, because the frontend only resolves citations that were in its build.
  • Three levels of rollback: wrangler rollback for the Worker, demo mode or the kill switch for the chat alone, and additive migrations with documented undo steps.
  • OpenRouter simulator (scripts/testes/mock-openrouter.mjs) for exercising AI mode locally, including 402, 429 and 5xx errors, without spending anything.

06Security

8 attacks considered, 8 defenses in production.

attackdefense
API shortcut

Skipping the interface to talk straight to the database or API with the public key in hand.

  • Read conversations or feedback straight from the database API using the public key

    RLS on every table with anon/authenticated grants revoked; only admins (app_metadata.role) can read, and a script tests the access matrix

Privilege escalation

Someone with some access trying to get more: becoming admin, reading what they shouldn't, keeping revoked access.

  • Keep using the panel after admin access is revoked

    Besides verifying the JWT against the JWKS, the Worker re-reads the user's current role on every request; public signup is closed and the role lives only in app_metadata

Forged origin and requests

CSRF, fake webhooks, reused tokens, signed links and open redirects.

  • Call the chat API from any website

    CORS only for an allowlist of embedding origins; the rest of the API is same-origin

Injection and hostile content

XSS, iframes, CSV formulas, disguised uploads and AI prompt manipulation.

  • Send an oversized payload or a forged history to manipulate the prompt

    Body read with a real byte cap (413), questions up to 1,000 chars, a 12-message window, protocol markers stripped, profile and origin allowlisted

  • Get the model to inject links or HTML into the page

    The model cites sheet IDs only; links come from the versioned base and answers render as JSX components, never innerHTML

Cost and availability abuse

Blowing up the bill, exhausting quotas, flooding logs and knocking functions down with load.

  • Fire thousands of questions to run up the AI bill

    Native 20/min rate limit, per-person and global daily quotas checked in Postgres before the model is called (fail-closed), a credit-capped key and a kill switch

Data leakage and tracking

Enumerating who is in the base, scraping personal data, tying questions to people, extracting secrets.

  • Trace who asked what from the logs

    IPs are never stored: quotas key on sha256(IP + day + salt); the conversation log has no IP or session ID and pg_cron deletes it after 90 days

Tampering and audit trail

Fiddling with counts, wiping the base, editing history or denying what was authorized.

  • A compromised admin writes arbitrary config or a nonexistent model

    Typed, range-checked validators on write and again on read; model changes limited to catalog IDs; column-level update grant

Access model: the public never talks to the database.

  • RLS is on for every table. The base migration revokes all grants from anon and authenticated and grants access explicitly to service_role alone, which only the Worker uses.
  • Admins are Supabase Auth users with app_metadata.role = 'admin'. eh_admin() reads the role from the JWT. Only the server writes app_metadata, never user_metadata, which the user can edit.
  • There are 9 policies, all gated on eh_admin(): read access on 8 tables, plus update on config limited by a column-level grant to valor, atualizado_em and atualizado_por. An admin can't rename a config key, insert feedback or delete a knowledge sheet.
  • EXECUTE on consumir_cota and buscar_fichas is revoked from public, anon and authenticated. Every function is security invoker with search_path = '', and every view is created with security_invoker = true so the RLS of the underlying tables still applies.
  • scripts/testes/acesso-banco.sh checks an anonymous × regular user × admin matrix across 12 objects through PostgREST, along with closed signup and RPC access.

Admin authentication.

  • Passwordless login uses an 8-digit OTP that expires after 600 s, and public signup is disabled. The login screen shows the same message for any email, so it never reveals who is an admin.
  • The Worker verifies the JWT with auth.getClaims() (ES256 signature checked against the JWKS) and requires aud = authenticated and the admin role. Because a token lives up to an hour, the Worker also re-reads the user's current role through the Admin API on every request. Revoking an admin therefore takes effect immediately for everything that goes through the Worker.
  • Nobody can revoke their own access, and the last admin can't be removed.

Cost and abuse: a ceiling at four layers.

  1. Cloudflare's native rate limit: 20 questions and 30 feedback posts per minute per person.
  2. Daily quotas per person (150 by default) and site-wide (5,000) in Postgres. A single atomic statement (insert … on conflict do update … returning count <= limit) enforces them before the model is called.
  3. A credit limit on the OpenRouter key itself.
  4. A kill switch and demo mode in the panel, with no deploy needed.

The daily quota fails closed: if the database is down, the chat answers 429 rather than spend without a meter. The per-minute limiter deliberately fails open because the Postgres layer still applies.

Privacy (Brazil's LGPD).

  • In the quota tables a "person" is sha256(IP + day + salt). The IP is never stored, and the key rotates daily. Rotating the salt resets every quota.
  • conversas_log keeps the question text for 90 days (pg_cron) with no IP, user ID or session ID. Quotas are kept for 30 days and balance snapshots for a year.
  • The calculator keeps the salary a user types inside the browser.

API validation and hardening.

  • Request bodies are read as a stream with a byte cap that doesn't trust content-length alone (50 KB for chat, 16 KB for feedback, 2–4 KB for admin) and return 413 when exceeded.
  • Chat history is strictly validated: only allowed roles, questions up to 1,000 characters, a 12-message window that always starts with the user, and earlier answers stripped of protocol markers and capped at 4,000 characters. Profile and origin values must be on an allowlist.
  • Every config write goes through typed, range-checked validators (max_tokens 500–8000, rag_top_k 3–15…). A model change is accepted only if the ID exists in OpenRouter's catalog, and config read back from the database is validated again before use.
  • CORS on /api/chat and /api/feedback is limited to an allowlist of origins that embed the widget.
  • Headers: nosniff, X-Frame-Options: DENY, Referrer-Policy, and a Permissions-Policy that blocks camera, microphone and geolocation. /admin is served with noindex and no-store.

Secrets. The OpenRouter key has a credit cap. A separate management key, created with an expiry date, can only read the balance. The Supabase secret key exists only as a Worker secret. Rotation steps are documented for each secret, and wrangler.toml holds only values that are public by design.

Content safety. The model answers only from the knowledge base, under explicit rules on neutrality and on separating fact, projection and opinion. Links come only from the knowledge base, and answers render as components, never as model-supplied HTML. The avaliar.mjs suite (29 cases) checks for the expected citations and for forbidden patterns, including a who-should-I-vote-for question that must be declined.

07Technical challenges

Streaming that arrived all at once

With compression on, both Cloudflare and the local runtime buffered the whole answer, so it appeared fully formed instead of streaming. The fix was to serve /api/chat with cache-control: no-store, no-transform and content-encoding: identity, and to use a custom SSE parser that re-emits plain text.

Predictable cost with a ~25k-token prompt

Sending the whole knowledge base with every question is expensive without caching, and any change to the system prompt invalidates the cache. The prompt is byte-for-byte stable: date, profile and origin go into the last message, and the provider is pinned so caching is guaranteed. Measured production cost was US$0.0006–0.0011 per cached answer, and the panel tracks the cache-hit rate to catch regressions.

Answers cut off by reasoning tokens

Answers with rich blocks (cards, tables, timelines) were being truncated. The conversation log showed stop = length: the model's reasoning tokens count against the same max_tokens budget. The limit became a panel setting, a migration raised it to 6,000, and the log now records reasoning tokens.

RAG: measure before switching it on

The hybrid search was built and evaluated (22/22 recall at top-7 over 22 cases) and then left off. With 37 sheets the whole base fits in the cached prompt, so there is no risk of retrieval missing the right sheet. The evaluation also caught a paraphrase that RRF pushed out of the top 7, which is now documented as a gate before enabling RAG. If search or embedding fails, the Worker falls back to the full base.

08Results

  • 16 commits between Oct 15 and Oct 21, 2026, covering the MVP, the Workers backend, the post-enactment content update and the embeddable widget.
  • Running in production on Cloudflare, with the model switchable from the panel without a deploy.
  • Measured cost of US$0.0006–0.0011 per cached answer (about US$0.0035 when the cache has to be written), per the operations docs dated Oct 15, 2026.
  • Hybrid search recall of 22/22 on the evaluation cases (top-7).
  • 37 unit tests (answer parser, SSE, validation, publication), plus an HTTP contract test, a quota test and a database access matrix.
16
commits
how we measured

git log --oneline | wc -l (HEAD 5c317d4)

Oct 15 → Oct 21, 2026
timeframe
how we measured

dates of the first and last commit in git log

6
migrations
how we measured

supabase/migrations/ at HEAD

8 / 4
tables / views
how we measured

create table / create view in the migrations

9
RLS policies
how we measured

create policy in the migrations (8 admin_le + 1 admin_edita)

3
pg_cron jobs
how we measured

cron.schedule in 20261015190000_operacao.sql

12
API routes
how we measured

src/worker/index.ts and src/worker/admin.ts (4 public + 8 admin)

37 / 47
fact sheets / sources
how we measured

node scripts/build-kb.mjs --check

37
unit tests
how we measured

test()/it() in *.test.ts at commit HEAD

29
evaluation cases
how we measured

CASOS array in scripts/avaliar.mjs

22/22
RAG recall (top-7)
how we measured

docs/backend/RAG.md, measured on 2026-10-15

US$ 0.0006–0.0011
cost per answer
how we measured

docs/backend/OPERACAO.md, measured in production on 2026-10-15 (with cache)

5,739
TS/TSX lines
how we measured

wc -l at HEAD: .ts 2,634 (30 files) + .tsx 3,105 (16), no generated types

2,603 / 2,067 / 558
Astro/CSS/SQL lines
how we measured

wc -l at HEAD; SQL from the migrations only

09Timeline

  1. 15 Oct 2026

    MVP: site, chat and knowledge base

  2. 16 Oct 2026

    Cloudflare Workers backend: chat, pgvector RAG, admin panel and operations

  3. 16 Oct 2026

    Knowledge-base source dossier

  4. 16 Oct 2026

    Content updated after the amendment was enacted

  5. 16 Oct 2026

    Rich answers: Markdown and blocks rendered as components

  6. 16 Oct 2026

    Max_tokens raised to 6000 after tracing truncation to reasoning tokens

  7. 21 Oct 2026

    Chat embeddable on partner sites

10Stack

Frontend
  • Astro 7
  • Preact 11
  • TypeScript
  • CSS com tokens
  • View Transitions
Backend
  • Cloudflare Workers
  • TypeScript
  • SSE streaming
  • Cron Triggers
  • Rate Limiting binding
Data
  • Supabase Postgres
  • pgvector (HNSW)
  • Full-text search (portuguese)
  • pg_cron
  • PostgREST
Infra
  • Cloudflare Workers static assets
  • Supabase gerenciado
  • Wrangler
  • Supabase CLI
  • Docker (local)
Security
  • Row Level Security
  • Supabase Auth OTP
  • JWT via JWKS
  • Cotas atômicas em Postgres
  • IP hasheado com sal diário
  • Retenção via pg_cron
  • CORS por allowlist
AI
  • OpenRouter
  • Claude Haiku
  • Prompt caching
  • Workers AI bge-m3
  • RAG híbrido (RRF)

11Tech sheet

node@direto-ao-ponto: ~/cases/direto-ao-ponto
node@direto-ao-ponto ─────────────
type
public AI assistant
stack
Astro · Preact · CF Workers
db
Postgres + pgvector (RLS on all)
auth
Supabase OTP · app_metadata.role
ai
Claude Haiku · prompt cache · hybrid RAG
guard
4-layer cost cap · fail-closed
deploy
wrangler deploy · edge
status
in production
$ node scripts/build-kb.mjs --check
✓ Base de conhecimento: 37 fichas, 47 fontes, 11 marcos.
$ npm test
✔ validar: janela começa pelo usuário e tem no máximo 12
✔ validar: recusas do contrato
✔ feedback: valida voto e corta tamanhos
ℹ tests 37
ℹ pass 37
ℹ fail 0
$ bash scripts/testes/acesso-banco.sh
cadastro público:
ok signup fechado
conversas_log:
ok anon não lê
ok comum vê 0 linhas
escrita:
ok admin não altera coluna chave
ok anon não chama consumir_cota
TUDO OK
$ curl -s localhost:8787/api/saude
{"ok":true,"modo":"ia","banco":true,"rag":false,"modelo":"anthropic/claude-haiku-5.5","fichas":37,"versao":"local"}

© 2026 NODE. All rights reserved.