contextd

contextd is a local-first, privacy-preserving semantic context daemon for AI coding agents. It watches your local workspaces, chunks source code and documents with Tree-sitter and PDF/plugin extractors, generates ONNX embeddings locally, stores vectors and full-text indexes in SQLite WAL (sqlite-vec + FTS5), and exposes hybrid retrieval over MCP stdio, HTTP REST, and CLI.

Why contextd?

  • 100% Local — Your code and embeddings never leave your machine
  • MCP Native (2025-06-18) — One-command auto-setup (contextd connect --all) for 9 AI tools including Claude Desktop, Claude Code, Cursor, VS Code Copilot, Codex, OpenCode, Continue, Copilot CLI, and Antigravity
  • Hybrid Search — Combines sqlite-vec KNN vector similarity with tokenized SQLite FTS5 keyword search via normalized Reciprocal Rank Fusion (RRF)
  • Concurrent WAL Storage — Dedicated 8-connection read-only r2d2 reader pool, transactional writes, blake3 incremental change detection, and batched ONNX inference
  • Polyglot Smart Chunking — Tree-sitter AST splitting for Rust, Python, JS/JSX, TS/TSX, and Go, plus Markdown headers, built-in PDF extraction, and timeout- and output-capped external format parser subprocesses
  • Hardened by Default — Loopback DNS-rebinding checks, mandatory Bearer auth on non-loopback binds, untrusted workspace config isolation, O_NOFOLLOW reads, secret/binary exclusions, and SHA-256 verified model downloads

Getting Started

Install

One-line installer (Linux/macOS, SHA-256 verified)

curl -fsSL https://raw.githubusercontent.com/sandy-sachin7/contextd/main/scripts/install.sh | bash

Cargo (Crates.io, Rust 1.95+)

cargo install contextd --locked

Windows (PowerShell, SHA-256 verified)

irm https://raw.githubusercontent.com/sandy-sachin7/contextd/main/scripts/install.ps1 | iex

Homebrew (macOS/Linux)

brew install --HEAD --build-from-source ./homebrew/contextd.rb

Docker

The container binds 0.0.0.0:3030 inside the container, so CONTEXTD_AUTH_TOKEN is required:

docker run --rm -p 127.0.0.1:3030:3030 \
  -e CONTEXTD_AUTH_TOKEN=replace-with-strong-token \
  -v "$PWD:/workspace:ro" \
  ghcr.io/sandy-sachin7/contextd

From source

git clone https://github.com/sandy-sachin7/contextd.git
cd contextd
cargo build --release --locked
./target/release/contextd setup

Run as Daemon

# Download and verify the default embedding model
contextd setup

# Start the daemon (watches your configured directories and serves HTTP on 127.0.0.1:3030)
contextd daemon

# Or run one-off hybrid queries from the CLI
contextd query "authentication system" --limit 10 --context 2

Connect your AI Tool

Auto-configure all detected AI tools (Claude Desktop, Claude Code, Cursor, VS Code Copilot, Copilot CLI, OpenCode, Continue, Antigravity, Codex):

contextd connect --all

See the Integrations section for manual setup guides.

Configuration

contextd uses a TOML configuration file. Resolution order:

  1. Explicit --config <path> CLI flag (global across all subcommands)
  2. Workspace-local ./contextd.toml
  3. User-global config (~/.config/contextd/contextd.toml on Linux, ~/Library/Application Support/contextd/contextd.toml on macOS)
  4. Platform defaults (~/.local/share/contextd/contextd.db and ~/.local/share/contextd/models)

Workspace config trust

A workspace-local ./contextd.toml is untrusted. Only [watch] and [chunking] apply from it. The [server] and [storage] sections come from the user-global config, or from platform defaults when no user-global config exists. [plugins] requires allow_workspace_plugins = true in the user-global config or the --trust-workspace-plugins CLI flag.

To change network or storage settings, use the user-global config or an environment override below. An explicit --config <path> outside the user config directory is also treated as untrusted for those sections unless you explicitly pass --trust-config (which allows [server], [storage], and [plugins] from that file).

Environment Variable Overrides

VariableDescription
CONTEXTD_HOSTHTTP API bind host (default 127.0.0.1)
CONTEXTD_PORTHTTP API bind port (default 3030)
CONTEXTD_AUTH_TOKENBearer token (required when binding non-loopback hosts)
CONTEXTD_DB_PATHSQLite database path
CONTEXTD_MODEL_PATHRoot directory for model-specific cache folders
CONTEXTD_MODEL_TYPEall-minilm-l6-v2, all-mpnet-base-v2, or bge-small-en-v1.5
CONTEXTD_WATCH_PATHSColon/semicolon/comma-separated list of directories to watch
CONTEXTD_MAX_FILE_SIZEMaximum file size in bytes (default 2097152)

Example

[server]
host = "127.0.0.1"
port = 3030

[storage]
db_path = "~/.local/share/contextd/contextd.db"
model_path = "~/.local/share/contextd/models"
model_type = "all-minilm-l6-v2"

[watch]
paths = ["."]
debounce_ms = 500
max_file_size = 2097152

[chunking]
max_chunk_size = 1500
overlap = 150

[security]
allow_workspace_plugins = false

[plugins]
docx = ["pandoc", "-t", "plain"]

Ignoring Files

contextd automatically excludes secrets (.env*, *.pem, *.key, id_rsa), binary files, and heavy build directories (.git/, node_modules/, target/, .venv/, __pycache__/, dist/, build/). It also respects .gitignore and .contextignore.

Usage

contextd provides six subcommands: daemon, mcp, setup, query, connect, and completions.

  • daemon (default) — Runs as a background service, watches configured paths, maintains the SQLite WAL index, and serves the hardened HTTP REST API.
  • mcp — Runs as an async JSON-RPC 2.0 / MCP stdio server for AI tool integrations.
  • setup — Downloads and SHA-256 verifies the configured ONNX embedding model.
  • query — Executes one-off hybrid semantic + FTS5 searches directly from the terminal.
  • connect — Auto-detects and configures MCP settings for 9 AI tools with .bak backups.
  • completions — Generates bash, zsh, or fish shell completion scripts.

Global Flags

These flags work before or after any subcommand:

  • -c, --config <PATH> — Explicit TOML configuration file path.
  • --trust-config — Explicitly trust a --config file located outside the user config directory (allows [server], [storage], and [plugins]).
  • --trust-workspace-plugins — Explicitly trust and execute [plugins] from a workspace-local ./contextd.toml.

CLI

Daemon Mode (Background Service)

contextd daemon
contextd daemon --config /path/to/contextd.toml --trust-config
# Optional: exit when stdin closes (useful when spawned by an editor extension)
contextd daemon --exit-on-stdin-eof

Query Mode (One-off Hybrid Queries)

contextd query "authentication"
contextd query "database schema" --limit 10 --min-score 0.5 --file-types rs,sql --context 2
contextd query "API changes" --paths src/,docs/ --after 2025-01-01 --before 2026-12-31

Setup Mode

Downloads and SHA-256 verifies the configured embedding model from pinned HuggingFace revisions:

contextd setup

Supports all-minilm-l6-v2 (default, 384d), all-mpnet-base-v2 (768d), and bge-small-en-v1.5 (384d).

Connect Mode (AI Tool Auto-Configuration)

contextd connect --all
contextd connect --all --scope project
contextd connect --tool claude-desktop

Shell Completions

contextd completions bash > ~/.local/share/bash-completion/completions/contextd
contextd completions zsh  > ~/.zfunc/_contextd
contextd completions fish > ~/.config/fish/completions/contextd.fish

REST API

The REST API is served by the daemon on the configured host:port (default 127.0.0.1:3030).

Security & Limits

  • Loopback DNS-Rebinding Protection: In unauthenticated loopback mode, requests must include a loopback Host header (localhost, 127.0.0.1, or [::1]).
  • Bearer Authentication: Binding a non-loopback host (e.g., 0.0.0.0) requires server.auth_token or CONTEXTD_AUTH_TOKEN. When configured, pass Authorization: Bearer <token> on /status and /query (loopback /health remains open for healthchecks).
  • Resource Caps: 64 KiB max request body, 16 KiB max query string, 30-second request timeout, and 64 max concurrent requests.

Health

curl http://127.0.0.1:3030/health

Response:

{
  "status": "ok",
  "uptime_secs": 3600
}

Status

curl http://127.0.0.1:3030/status

Response:

{
  "status": "ok",
  "uptime_secs": 3600,
  "indexed_files": 1500,
  "total_chunks": 45000,
  "database_size_bytes": 52428800
}

Query

curl -X POST http://127.0.0.1:3030/query \
  -H "Content-Type: application/json" \
  -d '{
    "query": "How does auth work?",
    "limit": 5,
    "min_score": 0.5,
    "file_types": ["rs", "py"],
    "context_lines": 2
  }'

Parameters:

NameTypeRequiredDescription
querystringYesSearch query (max 16 KiB)
limitnumberNoMax results (default: 5, max: 100)
max_resultsnumberNoAdditional response cap (min(limit, max_results), max: 100)
min_scorenumberNoMinimum relevance score (0.0-1.0, finite)
file_typesstring[]NoFilter by file extensions (e.g., ["rs", "py"])
pathsstring[]NoFilter by file path substrings
start_timenumberNoFilter by earliest modification time (UNIX seconds)
end_timenumberNoFilter by latest modification time (UNIX seconds)
context_linesnumberNoSurrounding source lines to include (0-20)

MCP Server

Run contextd as an async JSON-RPC 2.0 / Model Context Protocol stdio server:

# Uses trusted user-global config (~/.config/contextd/contextd.toml) or platform defaults
contextd mcp

# Or point to an explicit config outside the user config dir
contextd mcp --config /path/to/contextd.toml --trust-config

contextd mcp writes protocol diagnostics exclusively to stderr (never stdout) and never logs indexed source code or search result contents.

Protocol & Hardening

  • Negotiated Versions: 2025-06-18 (latest), 2025-03-26, 2024-11-05
  • Frame Cap: 16 MiB max line length on stdin
  • Cancellation: Honors notifications/cancelled via in-flight abort handles
  • Tool Annotations: Read-only (readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false)

Available Tools

search_context

Hybrid semantic (sqlite-vec KNN) + keyword (FTS5) search over your indexed codebase.

Parameters:

NameTypeRequiredDescription
querystringYesNatural language or keyword search query
limitintegerNoMax results (default: 5, max: 100)
file_typesstring[]NoFilter by file extensions (e.g., ["rs", "py"])
pathsstring[]NoFilter by file path substrings
min_scorenumberNoMinimum relevance score (0.0-1.0)
start_timeintegerNoFilter files modified at or after UNIX timestamp (seconds)
end_timeintegerNoFilter files modified at or before UNIX timestamp (seconds)
context_linesintegerNoSurrounding source lines to include (0-20)

get_status

Get the current indexing status (indexed_files, total_chunks, database_size_bytes).

Integrations

contextd works with any tool that supports the Model Context Protocol (MCP).

Claude Desktop Integration

Add contextd to your claude_desktop_config.json:

{
  "mcpServers": {
    "contextd": {
      "command": "/path/to/contextd",
      "args": ["mcp"],
      "env": {}
    }
  }
}

Or run contextd connect --tool claude-desktop to configure this automatically. When --config is omitted, contextd mcp loads config, database, and models from platform XDG directories (~/.config/contextd/contextd.toml). If you pass a custom config path outside that directory and want its [server]/[storage] settings honored, add "--config", "/path/to/contextd.toml", "--trust-config".

Config locations:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Linux: ~/.config/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json

Usage in Claude

"Search contextd for functions that handle file indexing" "Find code related to embedding generation, only in Rust files" "Use contextd to get the indexing status"

Cline / Roo Code (VSCode)

  1. Open the MCP Servers settings (via the "MCP Servers" tab or command palette).
  2. Add a new server:
    • Name: contextd
    • Command: /path/to/contextd
    • Args: mcp

When --config is omitted, contextd mcp resolves your user-global config, database, and models from platform XDG directories. If you pass a custom config file outside your user config directory and want its [storage]/[server] settings honored, pass mcp, --config, /path/to/contextd.toml, --trust-config.

Continue.dev Integration

You can configure Continue automatically with:

contextd connect --tool continue

Or configure it manually in ~/.continue/config.yaml (recommended — uses your trusted user-global ~/.config/contextd/contextd.toml or platform defaults):

mcpServers:
  - name: contextd
    command: /absolute/path/to/contextd
    args:
      - mcp

To point at a project-specific config outside your user config directory, create .continue/mcpServers/contextd.yaml and add --trust-config if you want its [storage] or [plugins] sections applied:

name: contextd
command: /absolute/path/to/contextd
args:
  - mcp
  - --config
  - /absolute/path/to/contextd.toml
  - --trust-config

Without --trust-config, a config file outside the user config directory is treated as untrusted: [server] and [storage] remain governed by your user-global config or platform defaults, and [plugins] remain disabled.

Usage in Continue

In Continue chat, select MCP tools or ask naturally:

"Use search_context to find code about semantic search with limit 3"

Features

Hybrid Search

contextd combines sqlite-vec KNN vector similarity with full-text keyword search (SQLite FTS5) across CLI, HTTP API, and MCP:

  • Semantic (sqlite-vec): Cosine similarity via local ONNX embeddings (WHERE embedding MATCH ?1 AND k = ?2), with progressive k expansion when file, path, or time filters are active.
  • Keyword (FTS5): Sanitized, tokenized OR queries using the Porter stemming tokenizer (porter unicode61), with SQL filters applied before LIMIT.
  • Normalized Fusion: Reciprocal Rank Fusion (k = 60) normalized to [0.0, 1.0] and blended with semantic cosine similarity.

Search Ranking Pipeline

  1. Vector KNN fetches top candidates (clamp(limit * 5, 50, 200)) via sqlite-vec and applies recency decay (default weight 0.1) and logarithmic frequency boost (default weight 0.1).
  2. FTS5 Keyword Search fetches top keyword matches with SQL filters applied prior to LIMIT.
  3. Normalized RRF combines both rank lists into [0.0, 1.0] and blends rank consensus with vector similarity.
  4. Filtering & Truncation applies min_score, sorts deterministically (mapping NaN to 0.0), truncates to limit, and resolves optional context_lines only for the final results.

Smart Chunking

contextd uses Tree-sitter AST parsing for semantic code splitting:

LanguageStrategyAST Nodes Captured
RustTree-sitterfunction_item, impl_item, struct_item, enum_item, mod_item, trait_item
PythonTree-sitterfunction_definition, class_definition, decorated_definition
JavaScriptTree-sitterfunction_declaration, class_declaration, export_statement, lexical_declaration, expression_statement
TypeScriptTree-sitterSame as JS + interface_declaration, type_alias_declaration
GoTree-sitterfunction_declaration, method_declaration, type_declaration, const_declaration, var_declaration
MarkdownHeader-basedSections by heading hierarchy
PDFPage/form-feedParagraph split
OtherParagraph splitBy blank lines

Plugin System

Extend indexing to additional file formats via external converter commands. Native Tree-sitter chunkers (Rust, Python, JS/JSX, TS/TSX, Go), Markdown splitting, plain text, and built-in PDF extraction (pdf-extract) work out of the box — plugins are only needed for extra formats like .docx, .odt, .epub, or .ipynb.

Plugins are invoked with -- <canonical_file_path> appended as the final arguments and must write UTF-8 text to stdout.

Configuration

Configure [plugins] in your trusted user-global config (~/.config/contextd/contextd.toml on Linux, ~/Library/Application Support/contextd/contextd.toml on macOS):

[plugins]
# External PDF override (wrapper strips the leading `--` guard before calling pdftotext)
pdf = ["./scripts/pdftotext.sh"]

# Office documents (requires pandoc)
docx = ["pandoc", "-t", "plain"]
odt = ["pandoc", "-t", "plain"]
rtf = ["pandoc", "-t", "plain"]
epub = ["pandoc", "-t", "plain"]

# Jupyter notebooks (requires jupyter nbconvert)
ipynb = ["jupyter", "nbconvert", "--to", "markdown", "--stdout"]

Security & Trust Model

  • Workspace Isolation: [plugins] defined in a workspace-local ./contextd.toml (or an untrusted --config file) are disabled by default to prevent arbitrary command execution when indexing untrusted repositories. Enable explicitly via --trust-workspace-plugins, --trust-config, or security.allow_workspace_plugins = true in your user-global config.
  • Flag-Injection Guard: contextd always inserts -- before the canonicalized file path so filenames starting with - cannot be interpreted as flags. Custom wrapper scripts should strip an optional leading -- (see scripts/pdftotext.sh).
  • Execution Limits: stdin is bound to /dev/null, child processes use kill_on_drop(true), execution times out after 30 seconds, stdout is capped at 10 MiB, and output must be valid UTF-8.

Search Intelligence

contextd layers three ranking and presentation signals on top of sqlite-vec KNN + FTS5 hybrid retrieval:

Recency Boost

Recently modified files rank higher during vector candidate scoring. The boost decays smoothly by 50% every 24 hours:

recency_boost = 1.0 / (1.0 + age_hours / 24.0)

Default recency_weight in SearchOptions is 0.1.

Frequency Ranking

Files that are repeatedly matched gain a logarithmic priority boost using the query_hits table:

frequency_boost = ln(1 + hit_count) * frequency_weight

Default frequency_weight in SearchOptions is 0.1.

Smart Context Windows

When context_lines (1-20) is requested via CLI (--context), HTTP API, or MCP (search_context), contextd reads surrounding lines and computes 1-indexed line_start / line_end bounds from disk only for the final top-N results after ranking and truncation.

Embedding Models

Embedding Models Guide

contextd supports multiple local ONNX embedding models for different speed/quality trade-offs.

Available Models

ModelDimensionsPoolingBest For
all-minilm-l6-v2 (default)384MeanGeneral purpose FP32 (~91 MB)
all-minilm-l6-v2-q8384MeanQuantized int8 (~22 MB), faster CPU indexing and lower cold query latency
all-mpnet-base-v2768MeanHigher quality, recommended for code
bge-small-en-v1.5384CLSBalanced quality/speed for retrieval

All supported models are downloaded from pinned HuggingFace commit revisions and verified with SHA-256 checksums before installation.

Each model uses its own subdirectory under model_path. A model switch loads the selected model's files and keeps the other model caches.

Configuration

Set the model in your contextd.toml (or via CONTEXTD_MODEL_TYPE):

[storage]
model_type = "all-mpnet-base-v2"

Switching Models

  1. Update model_type in your config.
  2. Run setup to download and verify the model files:
    contextd setup
    
  3. Remove or point db_path at a new SQLite database file and restart contextd daemon. contextd records model_type and embedding_dim in the database meta table and will fail fast with a clear error if an existing database does not match the active model.

Architecture

┌──────────────────┐
│  Watcher + Walk  │ → 500ms Debounce → Default Secret/Build Exclusions + .gitignore/.contextignore
└──────────────────┘
         │
         ▼
┌──────────────────┐
│  safe_read +     │ → O_NOFOLLOW / Reparse-Point Guard → Binary Sniff (8 KiB) → blake3 Hash
│  PathCoordinator │
└──────────────────┘
         │
         ▼
┌──────────────────┐
│  Parser/Chunker  │ → Tree-sitter (Rust/Py/JS/TS/Go) / Markdown / PDF / Sandboxed Plugins
└──────────────────┘
         │
         ▼
┌──────────────────┐
│ Batched Embedder │ → ONNX Runtime (SHA-256 Pinned Models, Mean/CLS Pooling, L2 Norm)
└──────────────────┘
         │
         ▼
┌──────────────────┐
│  SQLite WAL v2   │ → Transactional Writer + 8-Conn Reader Pool + sqlite-vec KNN + FTS5
└──────────────────┘
         │
         ▼
┌──────────────────┐
│   Query Layer    │ → MCP stdio (2025-06-18) / Hardened Axum HTTP / CLI
└──────────────────┘

Components

Daemon (src/daemon.rs)

The orchestration layer that manages the indexing lifecycle:

  • Initial scan streamed from WalkBuilder with bounded worker concurrency (available_parallelism().clamp(2, 8))
  • Startup reconciliation that prunes deleted files under active watch roots
  • File watcher via notify-debouncer-mini with 500ms default debounce (watch.debounce_ms)
  • Per-path coalescing (PathCoordinator) and blake3 + (mtime_ns, file_size) fast-skipping for incremental updates
  • Symlink-safe regular file reads via safe_read (O_NOFOLLOW on Unix, reparse-point checks on Windows)

Embedder (src/indexer/embeddings.rs, src/download.rs)

Local ONNX Runtime inference pipeline:

  • Tokenizes input text via HuggingFace tokenizers
  • Batched ONNX Runtime inference (embed_batch) with Mean pooling (all-minilm-l6-v2, all-mpnet-base-v2) or CLS pooling (bge-small-en-v1.5)
  • L2 normalization for cosine similarity across 384d and 768d models
  • Pinned HuggingFace commit downloads verified by SHA-256 into per-model cache subdirectories

Storage (src/storage/db.rs)

SQLite schema v2 in WAL mode:

  • Single transactional writer (Mutex<Connection>) + 8-connection read-only r2d2 reader pool (PRAGMA query_only = ON)
  • chunks_vec (sqlite-vec KNN virtual table) + chunks_fts (Porter-stemmed FTS5 virtual table)
  • Normalized Reciprocal Rank Fusion (RRF) with progressive filter over-fetching
  • meta table validating schema_version, model_type, and embedding_dim on open
  • query_hits table for logarithmic frequency ranking

Query Layer (src/api/mod.rs, src/mcp/server.rs, src/cli.rs)

Three async interfaces:

  • HTTP REST API: Hardened Axum server (loopback Host validation, mandatory Bearer auth on non-loopback binds, 64 KiB body cap, 30s timeout, 64 concurrent requests)
  • MCP Server: Async stdio JSON-RPC 2.0 server (2025-06-18, 16 MiB frame cap, notifications/cancelled)
  • CLI: One-off hybrid search (contextd query) and AI tool auto-configuration (contextd connect)

See ARCHITECTURE.md for the full design and trust-boundary documentation.

Testing

contextd includes unit, doctest, integration, MCP end-to-end, benchmark, and memory-stress suites.

Test Suites

SuiteCommandCoverage
Unit & Library Testscargo test --lib --bins --lockedConfig & trust isolation, Tree-sitter/PDF chunking & UTF-8 budgets, safe_read (O_NOFOLLOW), ignore/secret exclusions, external parser plugins, SQLite WAL/sqlite-vec/FTS5 hybrid search, HTTP API security middleware, MCP server, connect, download
Doc Testscargo test --doc --lockedCrate-level embedded library quickstart in src/lib.rs
Integration Testscargo test --tests --lockedwatcher_test (file events/renames/deletes), load_test (concurrent HTTP API + rapid edits), zero_config_test (model cache & setup)
Embedded Examplecargo run --example embedded_searchOffline Tree-sitter + SQLite WAL hybrid search library usage
MCP E2E SuiteCONTEXTD_BIN=./target/debug/contextd python3 scripts/test_mcp_local.py17 end-to-end JSON-RPC 2.0 / MCP protocol, validation, cancellation, and edge-case checks
Memory Stresspython3 scripts/memory_stress_test.pyLarge corpus (10K files, 1K queries) memory-bound check
Benchmarkscargo bench --locked / bash scripts/bench.shCriterion benchmarks (chunker_bench, db_bench)

Running the Full Verification Suite

# Formatting, lints, and rustdoc
cargo fmt --all -- --check
cargo clippy --all-targets -- -D warnings
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --locked

# All Rust tests (unit, doc, integration)
cargo test --locked

# Offline embedded example
cargo run --example embedded_search

# MCP end-to-end tests
CONTEXTD_BIN=./target/debug/contextd python3 scripts/test_mcp_local.py

# Shell script syntax checks
bash -n scripts/install.sh scripts/playground.sh scripts/pdftotext.sh

Contributing to contextd

Thank you for contributing to contextd! Whether you are fixing a bug, improving retrieval quality, adding language chunkers, or tightening security boundaries, this guide will get you productive quickly.

Please also review our Code of Conduct, Architecture Guide, and Security Policy.

Prerequisites

  • Rust: 1.91+ (MSRV enforced in Cargo.toml; rust-toolchain.toml tracks stable with rustfmt and clippy)
  • Python 3 (optional, for MCP end-to-end tests in scripts/test_mcp_local.py)

Getting Started

git clone https://github.com/sandy-sachin7/contextd.git
cd contextd
cargo build --locked

Module Map

PathResponsibility
src/main.rsCLI entrypoint (clap), global flags (--config, --trust-config, --trust-workspace-plugins), subcommand dispatch
src/cli.rssetup, query, completions, date/timestamp parsing
src/config.rsTOML loading, workspace trust isolation, XDG path resolution, CONTEXTD_* env overrides
src/daemon.rsInitial scan (WalkBuilder), notify watcher loop, PathCoordinator coalescing, startup reconciliation
src/indexer/Tree-sitter & text/PDF chunking (chunker.rs), ONNX batched embeddings (embeddings.rs), O_NOFOLLOW reads (safe_read.rs), ignore/secret filters (ignore.rs), sandboxed external plugins (plugins.rs), file watcher (watcher.rs)
src/storage/db.rsSQLite WAL storage (schema v2), r2d2 read-only pool, sqlite-vec KNN, FTS5, normalized RRF hybrid search
src/api/mod.rsHardened Axum HTTP API (/health, /status, /query), DNS-rebinding & Bearer auth middleware
src/mcp/server.rsJSON-RPC 2.0 / MCP stdio server (search_context, get_status, cancellation, frame limits)
src/connect.rsAuto-configuration for 9 AI tools with JSONC/TOML preservation and .bak backups
src/download.rsPinned HuggingFace downloads, SHA-256 verification, per-model cache directories & legacy migration

Verification Checklist

Before opening a pull request, run the full local verification suite:

# Formatting
cargo fmt --all -- --check

# Linting (zero warnings)
cargo clippy --all-targets -- -D warnings

# Rustdoc build (zero warnings)
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --locked

# Unit, doc, and integration tests
cargo test --locked

# Offline embedded library example
cargo run --example embedded_search

# MCP end-to-end test suite (17 checks)
CONTEXTD_BIN=./target/debug/contextd python3 scripts/test_mcp_local.py

# Shell script syntax checks (if scripts changed)
bash -n scripts/install.sh scripts/playground.sh scripts/pdftotext.sh

If you modify CLI flags or subcommands, regenerate shell completions:

cargo run -- completions bash > completions/contextd.bash
cargo run -- completions zsh  > completions/_contextd
cargo run -- completions fish > completions/contextd.fish

Commit & Pull Request Conventions

We use Conventional Commits:

  • feat: — new user-facing capability
  • fix: — bug fix
  • perf: — performance improvement
  • security: — security hardening or vulnerability fix
  • docs: — documentation or mdBook updates
  • refactor: — code restructuring without behavior change
  • test: — adding or updating tests
  • chore: — tooling, CI, or dependency maintenance

Guidelines for smooth reviews:

  1. Keep PRs focused on a single concern and include unit/integration tests for all behavior changes.
  2. Never log user source code or search result contents to stdout or stderr.
  3. Preserve security invariants (trust boundaries, O_NOFOLLOW, loopback/auth gates, bounded inputs).
  4. Update relevant docs in README.md, ARCHITECTURE.md, or docs/book/src/ when changing user-facing behavior.

Security Issues

Do not report security vulnerabilities in public issues or PRs. Follow SECURITY.md to submit a private GitHub Security Advisory.

License

By contributing to contextd, you agree that your contributions will be licensed under the MIT License.