Esc
projects

Factlock

A knowledge graph that turns email, documents and scans into verified facts and holds suspicious "this has changed" claims, like a vendor's new bank account, until a person has checked them. Built for teams that handle payment and contact details.

  • TypeScript
  • Next.js
  • PostgreSQL
  • Drizzle ORM
  • pg-boss
  • LangGraph
  • better-auth
  • SeaweedFS
  • OpenTelemetry
  • Docker
type
Web app
status
in progress
built
Q4 2026
updated
Q4 2026
by the numbers
1,000 documents, 0 failed (load test)

Why I built this

The README describes the target as a knowledge graph with an immune system: it reads email, documents, images and research, and refuses false “this has changed” claims. The sharpest case in the code is a vendor email that says “our bank account has changed”. Half of the 1,000 documents in the load test are exactly that.

Most document tools extract a value and trust it. I wanted a system where a model can only propose, and a deterministic process decides what becomes a fact.

How it works

A file goes straight from the browser to a quarantine bucket with a presigned link. A virus scan moves clean files to the main bucket. A sandboxed parser turns the file into text sections, and an LLM reads those against the project’s registry of fact types. Every claim has to quote the document word for word, and the value has to sit inside the quote, or it is dropped.

Claims then go through processClaim, a LangGraph graph. One read loads context, six checks run in parallel (sender authentication, independence, change anomaly, consistency, system of record, reputation), and a deterministic rule writes the decision in one transaction. Critical changes, anything touching an IBAN or a contact detail, are always held for a callback and a separate approver.

All the stages are pg-boss queues on Postgres, and tenant isolation is row-level security in the database.

flowchart LR
  U[Browser upload] -->|presigned PUT| Q[(Quarantine bucket)]
  Q --> S[ClamAV scan]
  S -->|clean| F[(Files bucket)]
  F --> P[Sandboxed parser]
  P -->|text sections| X[LLM extraction]
  X -->|quoted claims| R[Entity resolution]
  R --> C[processClaim graph]
  C -->|decision| G[(Postgres facts and audit log)]
  C -->|held| A[Approval inbox]
  A -->|callback and approval| G
  G --> I[Verify API, MCP, webhooks]

Key features

  • Quote-or-drop extraction. Every claim must quote the source word for word with its value inside the quote. Document text is fenced and treated as data, so instructions hidden in a file are not followed.
  • Lookalike and header signals for email. It flags sender domains that imitate a known one (Cyrillic letters, rn for m, another TLD), display names that hide the real address, and Reply-To pointing elsewhere.
  • Held critical changes. A bank or contact change needs a callback to a contact that has been on file for at least 30 days on a different channel, then a different person approving with a fresh MFA code. In teams, whoever brought the change in cannot verify or approve it.
  • Reputation that copies cannot fake. Forwards and near-duplicates (MinHash) share one origin, so repeating a claim does not count as confirmation. A source’s track record only comes from outside confirmation, and a good record never lowers the risk of a critical change.
  • Hardened ingestion. Uploads are quarantined, scanned and extension-checked. Parsers run in a no-network, read-only container, each file in a fresh locked-down Node process, with OCR (Tesseract WASM) inside the same sandbox.
  • Verification API, MCP server and webhooks. Other systems can ask whether a value is verified. There is a read-only MCP server and signed webhooks fed from a transactional outbox.
  • Tamper-evident audit log. It is hash-chained, holds ids only, and survives account erasure, which works by deleting a per-person encryption key.

Project structure and stack

src/
  app/        Next.js pages, server actions and API routes (verify, mcp, health, live)
  core/       pure domain logic: claims checks and decisions, detectors, extraction,
              entity resolution, llm client, registry, research, telemetry
  db/         Drizzle schema, tenant context (RLS), audit chain, trust, rate limits
  server/     application services: approvals, ask, erasure, integrations, inbox
  worker/     pg-boss handlers for every pipeline stage, alerts, fair queues
  parser/     sandboxed parsers (PDF, Word, Excel, CSV, email, OCR) and the socket server
drizzle/      44 migrations, with row-level security in separate hand-written files
scripts/      infra check, migrations, restore drill, k6 and 1,000-document load test
docs/         load test results and restore drill log
docker/       Postgres image with WAL-G, SeaweedFS, Caddy

Core technologies:

  • Next.js 16 and React 19: the web app, with a nonce-based CSP set in src/proxy.ts.
  • PostgreSQL 17 with pgvector and pg_trgm, behind PgBouncer: facts, claims, audit log, entity similarity and embeddings, row-level security per workspace.
  • Drizzle ORM: schema and migrations.
  • pg-boss: job queues on the same database, with a per-workspace fairness rule.
  • LangGraph: the claim-decision graph, the Ask agent and the web research loop.
  • Any OpenAI-compatible LLM endpoint, plus Voyage embeddings: extraction on a fast, standard and strong model ladder, and merge suggestions.
  • better-auth: sessions and MFA.
  • SeaweedFS (S3 API) and ClamAV: file storage and virus scanning.
  • OpenTelemetry: traces and metrics, with personal data masked before export.
  • Docker, Caddy and WAL-G: one image with four commands, TLS, encrypted continuous backups.

Decisions and tradeoffs

  • The model proposes, rules decide. Extraction output is only ever a proposal, and the final tier and decision come from deterministic code. I gave up a smarter-sounding model judgment, and in return every decision has plain-word reasons stored with the claim.
  • Postgres for almost everything. Queues, rate limits, the outbox and tenancy all live in Postgres. I gave up the throughput of a dedicated queue and cache, and in return one transaction can write a change, its audit row and its webhook together, so nothing goes out for a rollback.
  • Escalate models only on unusable answers. Calls start on the fast model and move up when the answer is empty, refused, cut off, not JSON or mostly invalid claims. Endpoint errors retry instead of escalating. It costs extra calls on hard documents, but keeps routine ones cheap.
  • No vision-model fallback for images. Images and scanned pages go through local OCR with line boxes and confidence, because the configured endpoint does not accept images. Low-confidence text adds risk and a major change that comes only from an image is held.

What was hard

  • The approval inbox fell over at 520 open items. The load test showed 2.7 s and 1.2 MB, and it took 200 items in arbitrary order before sorting, so the riskiest could be missing. I moved ordering into SQL, paged it at 50, and batched the per-item lookups, which brought it to 225 ms (docs/load-test.md).
  • One workspace starved another. A probe document waited 139 s for its virus scan behind a bulk import, because the per-workspace cap only bites when jobs are slow. Setting each job’s priority to minus its workspace’s waiting backlog dropped the probe to 9 s.
  • Invisible characters in source files. The git history has two fixes for bidirectional control characters (fix(uploads), fix(test)), and there is now a source hygiene test that guards against them.

Testing and evals

Tests use Vitest in two projects: 30 unit test files and 28 database test files. The database tests need Docker infra and run against a factlock_test database that is wiped each run. They cover row-level security, the audit chain, approvals, the worker pipeline, fairness between workspaces, erasure and the parser sandbox. There is also a k6 and 1,000-document load test, and a restore drill whose one recorded run passed.

pnpm infra:up      # Postgres, PgBouncer, SeaweedFS
pnpm test          # unit + database tests
pnpm typecheck && pnpm lint

There are no model evals yet. The README says the risk weights are a first version “to be calibrated in the evaluation phase”, and that phase has not been done.

What’s next

  • Evals and calibration. Replace the hand-set risk weights and thresholds in src/core/claims/checks.ts and decide.ts with calibrated ones.
  • Load test with real models. The run used a local stand-in with simulated latency. Real extraction calls are slower and would make the pipeline the limit, not the web tier.
  • Separate web and worker in the test. Everything shared one machine and one worker process, so scaling with replicas is claimed in the docs but not measured.
  • Regular restore drills. The README asks for one at least quarterly, and the log has one entry so far.