How ThreadWeave Works

A technical deep-dive into the architecture, detection engine, and design decisions.

ThreadWeave is an open-source system that connects to the tools your organization already uses and builds a searchable memory of the knowledge flowing through them. Everything runs on-premises. No cloud dependency. AGPL-licensed.


Architecture

ThreadWeave is a FastAPI server with a modular pipeline. Every piece of content passes through the same stages:

[Connectors: Gmail, Chat, Drive, M365, IMAP, .eml]
              │
              ▼
    POST /api/v1/ingest
              │
    ┌─────────┴──────────┐
    │  1. Dedup           │  SHA-256 of content + subject + sender
    │  2. Detect           │  Regex-first classifier (LLM optional)
    │  3. PII Gate         │  Strip emails, phones, identifiers
    │  4. Store            │  In-memory + MemPalace (ChromaDB + BM25)
    └─────────┴──────────┘
              │
    ┌─────────┼──────────┐
    │  Relevance Rank      │  Semantic + org proximity + freshness + authority
    │  Confidentiality     │  7 sensitivity levels, auto-detected
    │  Audit Log           │  Every read, write, and access decision
    └─────────────────────┘
              │
              ▼
       /api/v1/search
ModulePurpose
detector.pyRegex classifier: ANSWER / DECISION / QUESTION / CHAT / REFERENCE
llm_detector.pyOptional LLM-based classification with regex fallback
mempalace_client.pyHybrid BM25 + vector search via ChromaDB
confidentiality.py7 sensitivity levels, auto-detected, enforced at read
org_model.pyTemporal knowledge graph — who was on which team when
relevance.py4-factor ranking for search results
profiling.pyLatency percentiles, throughput, Prometheus export

The Knowledge Store: MemPalace

ThreadWeave wraps MemPalace — the highest-scoring open-source AI memory system — for hybrid semantic + keyword retrieval and structured storage.

MemPalace organizes knowledge as a building:

The Palace is the entire organization. Wings are departments and teams. Rooms live inside wings — specific projects, regulatory domains, client engagements. Drawers hold raw, verbatim content. Closets hold compressed summaries.

This structure mirrors how people actually think about organizational knowledge. Search isn't a keyword match — it belongs to a specific wing, room, and moment in time.

Search: Four-Factor Relevance

Results are ranked by semantic match, organizational proximity, freshness, and author authority. The result isn't a document list — it's an answer that feels like institutional instinct.

Connections: Hallways and Tunnels

MemPalace tracks relationships automatically — who created what, which project it belonged to, which team was involved, when it happened. Hallways connect knowledge within the same wing. Tunnels connect knowledge across wings — so the tax team's 2018 solution surfaces when M&A encounters the same problem in 2026.

Living Memory

Connections that get used grow stronger. Connections that go unused gradually fade. The knowledge graph is temporal — it knows when things were true.


The Detection Engine: Regex vs LLM

Every piece of content gets classified into one of five types:

TypeExampleSave?
ANSWER"The reason we use Postgres is JSONB support"
DECISION"We decided to migrate to GraphQL for the new API"
QUESTION"Does anyone know why we chose Redis?"
CHAT"ok thanks, sounds good!"
REFERENCENewsletters, HR digests, system notifications

Regex-First by Default

The primary detector uses weighted pattern dictionaries:

ANSWER patterns (+0.15 each):
  "the reason", "because", "due to", "this is why",
  "root cause is", "turned out that"

DECISION patterns (+0.15 each):
  "we decided", "decision:", "we chose", "we will use",
  "applied the fix", "released as", "resolved"

The regex detector outperformed the LLM on real-world test data (88% vs 76% on a 25-email set). It correctly handles technical emails with ticket numbers and version strings — patterns that cause LLMs to over-classify everything as "reference."

External Source Filtering

21 patterns catch newsletters, HR digests, and system notifications before type classification. 3+ matches forces REFERENCE at 0.90 confidence. 1-2 matches halves answer/decision scores.

Optional LLM Mode

THREADWEAVE_LLM_BASE_URL=http://localhost:11434/v1
THREADWEAVE_LLM_MODEL=llama3.1:8b
THREADWEAVE_LLM_PROVIDER=ollama

If the LLM call fails, the system gracefully falls back to regex. Nothing breaks.

Confidence Threshold: 0.35

Carefully tuned. At 0.30, too many borderline saves. At 0.40, legitimate terse technical answers were missed. 0.35 is the sweet spot.


The Ingestion Pipeline

Deduplication

dedup_key = f"{content}|{title}|{author_id}"
content_hash = sha256(dedup_key)

Same email ingested twice → same hash → correctly deduped. Same body, different subject/sender → different hash → both saved. The dedup cache is in-memory; restarting the server clears it.

PII Gate

Strips emails, phone numbers, and personal identifiers before storage. Content triggering PII detection is rejected entirely.

Dual Storage

Entries stored in both an in-memory dict (fast retrieval) and MemPalace/ChromaDB (persistent, vector-enabled). Searches work even if MemPalace is unavailable.


Confidentiality: 7 Levels

LevelDescription
PublicSafe for external sharing
InternalWithin the organization (default)
ConfidentialRestricted to specific teams
RestrictedSenior leadership only
HR-PrivilegedPersonnel matters
Client-ConfidentialSpecific client data
Legal-PrivilegedAttorney-client material

Auto-detected at ingest through pattern matching. Enforced at read — you can only see what your role and team permit.


Connectors

ConnectorHowAuth
IMAPAny email providerPassword or app password
Graph device-codeM365 inbox via GraphBrowser sign-in, MFA supported
Outlook COMClassic OutlookNone (local)
.eml filesBatch importNone
Google WorkspaceGmail, Chat, Drive + offboarding harvesterService account
Graph external connectorPush to Copilot & Microsoft SearchAzure app registration

The Google Workspace connector's offboarding harvester drains institutional knowledge when someone leaves — every decision, process, and client context from their email, chat, and documents.


On-Premises by Design

No data leaves the network perimeter. No vendor lock-in. Air-gapped ready. Bring your own LLM or don't use one at all.

Docker Compose includes an optional Ollama profile that auto-pulls a model on first start. Or point it at any OpenAI-compatible endpoint — vLLM, LiteLLM, corporate API gateway.


Observability

GET /api/v1/metrics           # JSON
GET /api/v1/metrics/prometheus  # Prometheus scrape target

Per-stage latency (p50/p95/p99), dedup hit rate, LLM vs regex ratio, throughput, memory, uptime. Full audit log at /api/v1/audit/recent.


Getting Started

# Docker (recommended)
git clone https://github.com/PowerLooming/ThreadWeave
cd ThreadWeave
docker compose up

# Or native Python
bash setup.sh
threadweave serve

API docs at http://localhost:8000/docs. Health check at /api/v1/health.


View on GitHub