Thank you for your interest in contributing to OpenDocuments! This guide covers everything you need to know to get started.
- Development Setup
- Project Structure
- Contribution Workflow
- Code Conventions
- Writing Tests
- Plugin Development
- Commit Messages
- Pull Request Guide
- Reporting Issues
- Release Process
- Node.js 20 or later
- npm 10 or later
- Git
# 1. Clone the repository
git clone https://github.com/joungminsung/OpenDocuments.git
cd OpenDocuments
# 2. Install dependencies and build everything (one command)
npm run setup
# 3. Run all tests (51 test suites, ~300 tests)
npm run test
# 4. Start development mode (watch for changes)
npm run dev| Command | Description |
|---|---|
npm run setup |
Install dependencies + build all packages |
npm run build |
Build all packages via Turborepo |
npm run test |
Run all test suites |
npm run dev |
Watch mode for all packages |
npx turbo build --filter=@opendocuments/core |
Build a specific package only |
npx turbo test --filter=@opendocuments/core |
Test a specific package only |
You don't need Ollama or any LLM provider installed to develop. When no model provider is available, the bootstrap automatically falls back to stub models that return zero-vector embeddings and placeholder text. The core indexing and search flow still works.
You'll see this message in the console -- it's expected and harmless:
[!!] Model plugin @opendocuments/model-ollama embed probe failed. Using stub models.
You only need a real LLM when developing features that depend on actual model output (e.g., answer quality testing).
OpenDocuments/
├── packages/ # Core packages (5)
│ ├── core/ # All business logic
│ │ ├── src/
│ │ │ ├── auth/ # API key management, OAuth provider
│ │ │ ├── config/ # Zod schema, config loader (jiti)
│ │ │ ├── connector/ # ConnectorManager (orchestrates external sources)
│ │ │ ├── conversation/ # Chat history persistence
│ │ │ ├── document/ # Versioning, tags, collections, chunk relations
│ │ │ ├── events/ # Typed EventBus (18 event types)
│ │ │ ├── ingest/ # Pipeline (parse → chunk → embed → store), chunker, document store
│ │ │ ├── parsers/ # Built-in parsers (Markdown, PlainText, Structured, Archive)
│ │ │ ├── plugin/ # Plugin registry, loader, compatibility checker
│ │ │ ├── rag/ # RAG engine, retriever, generator, profiles, cache,
│ │ │ │ # intent classifier, reranker, hallucination guard,
│ │ │ │ # query decomposer, cross-lingual, context window
│ │ │ ├── security/ # PII redaction, audit logger, security alerts
│ │ │ ├── storage/ # DB abstraction (SQLite), VectorDB (LanceDB), migrations
│ │ │ ├── telemetry/ # Opt-in usage telemetry
│ │ │ ├── utils/ # Logger, hash, fetchWithTimeout, file discovery, file watcher
│ │ │ └── workspace/ # Workspace CRUD
│ │ └── tests/ # 31 test files, 159 tests
│ │
│ ├── server/ # HTTP server (Hono), MCP server, auth middleware
│ │ ├── src/
│ │ │ ├── bootstrap.ts # Wires all core components together
│ │ │ ├── http/
│ │ │ │ ├── app.ts # Hono app (CORS, auth, rate limit, static serving)
│ │ │ │ ├── middleware/ # auth.ts, rate-limit.ts
│ │ │ │ └── routes/ # 9 route files (35+ endpoints)
│ │ │ ├── mcp/ # MCP server (19 tools, 2 resources)
│ │ │ └── widget/ # Embeddable chat widget (postMessage auth)
│ │ └── tests/ # 7 test files, 27 tests
│ │
│ ├── cli/ # CLI binary (Commander.js)
│ │ └── src/commands/ # 17 command files
│ │
│ ├── web/ # React SPA (Vite + Tailwind CSS)
│ │ └── src/
│ │ ├── components/ # 7 pages + CommandPalette + layout
│ │ ├── stores/ # Zustand (appStore, chatStore)
│ │ └── lib/ # API client, SSE helper, i18n, types
│ │
│ └── client/ # TypeScript SDK (@opendocuments/client)
│
├── plugins/ # Plugins (21 total)
│ ├── model-ollama/ # Ollama (local LLM + embedding)
│ ├── model-openai/ # OpenAI (GPT-5.4, text-embedding-3)
│ ├── model-anthropic/ # Anthropic (Claude Opus/Sonnet 4.6, no embedding)
│ ├── model-google/ # Google (Gemini 3.1, text-embedding-005)
│ ├── model-grok/ # xAI (Grok 4, OpenAI-compatible API)
│ ├── parser-pdf/ # PDF (pdf-parse)
│ ├── parser-docx/ # Word (mammoth HTML conversion)
│ ├── parser-xlsx/ # Excel/CSV (SheetJS)
│ ├── parser-html/ # HTML (cheerio)
│ ├── parser-jupyter/ # Jupyter Notebook (JSON parse)
│ ├── parser-email/ # Email .eml (RFC 2822 parser)
│ ├── parser-code/ # Source code (regex-based function/class extraction)
│ ├── parser-pptx/ # PowerPoint (XML text extraction)
│ ├── connector-github/ # GitHub (REST API, tree listing, base64 decode)
│ ├── connector-notion/ # Notion (Search API, block-to-text conversion)
│ ├── connector-gdrive/ # Google Drive (Drive API v3)
│ ├── connector-s3/ # S3/GCS (XML/JSON list + download)
│ ├── connector-confluence/ # Confluence (REST API, HTML-to-text)
│ ├── connector-swagger/ # Swagger/OpenAPI (spec parsing, endpoint chunking)
│ ├── connector-web-crawler/ # Web crawler (cheerio text extraction)
│ └── connector-web-search/ # Tavily web search (query-time, not index-time)
│
├── docs-site/ # VitePress documentation site
├── templates/ # Plugin scaffolding templates
├── benchmarks/ # RAG quality benchmarks (datasets + results)
├── Dockerfile # Multi-stage production image
└── docker-compose.yml # Docker Compose with optional Ollama
- All business logic lives in
@opendocuments/core-- the server package is only a thin protocol translation layer (HTTP/MCP/WebSocket) - Everything is a plugin -- parsers, connectors, models, and middleware all share the same plugin interface with lifecycle hooks
- Config as Code --
opendocuments.config.tsis the single source of truth, loaded at runtime via jiti - Event-driven decoupling -- components communicate through a typed EventBus (18 event types) instead of direct calls
- Storage abstraction -- SQLite and LanceDB sit behind interfaces; switching to PostgreSQL/Qdrant requires only config changes
- Check existing issues
- Look for
good first issuelabels if you're new - For larger changes, open an issue first to discuss the approach
git checkout main
git pull origin main
git checkout -b feat/my-feature # New feature
git checkout -b fix/my-bugfix # Bug fix
git checkout -b docs/my-docs # Documentation# Build and test only the packages you changed
npx turbo build --filter=@opendocuments/core
npx turbo test --filter=@opendocuments/core
# Or build and test everything
npm run build
npm run testFor any change that affects package versions:
npx changesetYou'll be prompted to:
- Select affected packages (spacebar to toggle)
- Choose version bump type:
patch(bugfix) /minor(feature) /major(breaking) - Write a summary of the change
This creates a markdown file in .changeset/. Include this file in your commit.
git add -A
git commit -m "feat(core): add my feature"
git push origin feat/my-featureOpen a Pull Request on GitHub. Fill in the PR template.
GitHub Actions automatically runs on every PR:
npm ci(clean install)npx turbo build(full build)npx turbo typecheck(TypeScript strict check)npx turbo test(all tests)
Tested on Node.js 20 and 22. CI must pass before merge.
- Strict mode is mandatory (
"strict": trueintsconfig.base.json) - ESM modules (
"type": "module"in every package.json) .jsextension required in import paths (ESM requirement):// Correct import { sha256 } from './utils/hash.js' // Wrong import { sha256 } from './utils/hash'
- Minimize
any-- useunknownor proper types.anyis acceptable in Web UI components but not in core or server logic.// Correct const data = await res.json() as { items: string[] } // Avoid const data = await res.json() as any
- Write JSDoc for all public APIs
| What | Convention | Example |
|---|---|---|
| Files | kebab-case | document-store.ts |
| Classes | PascalCase | DocumentStore |
| Functions / variables | camelCase | getDocumentBySourcePath |
| Interfaces / types | PascalCase | PluginContext |
| Constants | UPPER_SNAKE_CASE | MAX_ALERTS |
| Database columns | snake_case | workspace_id |
| Environment variables | UPPER_SNAKE_CASE | OPENDOCUMENTS_DATA_DIR |
| CLI commands | kebab-case | opendocuments auth create-key |
- No emojis -- use ANSI-colored symbols from the
logutility:import { log } from '@opendocuments/core' log.ok('Success') // [ok] green log.fail('Error') // [!!] red log.info('Info') // [--] blue log.arrow('Next step') // [->] cyan log.wait('Processing...') // [..] yellow log.heading('Title') // bold white + divider log.dim('Secondary') // gray
- This ensures consistent output across all terminals and operating systems
- Never silently swallow errors in critical paths -- at minimum, log them
- User-facing errors must be actionable -- explain what went wrong and how to fix it
- Never leak internal details in production:
// Correct return c.json({ error: 'Document not found' }, 404) // Wrong (leaks internal state) return c.json({ error: err.stack }, 500)
When writing new code, verify:
- No API keys or secrets hardcoded -- use environment variables
- SQL queries use parameterized statements (
?placeholders) - LanceDB filters use
buildWhereClause()-- never interpolate raw strings - FTS5 queries use
escapeFTS5Query()-- never pass raw user input - New HTTP endpoints are protected by auth middleware in team mode
- Error responses don't include stack traces or internal paths
- Vitest (Jest-compatible API)
- Test files go in
tests/within each package - File naming:
*.test.ts - Globals are enabled --
describe,it,expect,viare available without import
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
describe('MyModule', () => {
let db: DB
beforeEach(() => {
db = createSQLiteDB(':memory:')
runMigrations(db)
})
afterEach(() => {
db.close()
})
it('does something specific', () => {
// Arrange
const input = 'test'
// Act
const result = myFunction(input)
// Assert
expect(result).toBe('expected')
})
})- Use real SQLite -- create an in-memory database with
:memory: - Use real LanceDB -- create a temp directory, clean up in
afterEach - Mock external APIs -- use
vi.stubGlobal('fetch', ...)for HTTP calls - Each test must be independent -- no shared state between tests, initialize everything in
beforeEach - Test both happy path and error path
- Always clean up resources -- close databases, delete temp directories
import { mkdtempSync, rmSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
let db: DB
let vectorDb: VectorDB
let tempDir: string
beforeEach(async () => {
db = createSQLiteDB(':memory:')
runMigrations(db)
tempDir = mkdtempSync(join(tmpdir(), 'opendocuments-test-'))
vectorDb = await createLanceDB(tempDir)
})
afterEach(async () => {
db.close()
await vectorDb.close()
rmSync(tempDir, { recursive: true, force: true })
})vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ data: 'test' }),
}))
// ... run your test ...
afterEach(() => vi.unstubAllGlobals())vi.mock('@opendocuments/core', async () => {
const actual = await vi.importActual('@opendocuments/core')
return { ...actual, fetchWithTimeout: vi.fn() }
})
import { fetchWithTimeout } from '@opendocuments/core'
// In test:
;(fetchWithTimeout as any).mockResolvedValue({ ok: true, json: async () => ({}) })opendocuments plugin create my-parser --type parser
cd my-parser
npm installGenerated structure:
my-parser/
├── package.json # peerDependency: @opendocuments/core ^0.1.0
├── tsconfig.json
├── vitest.config.ts
├── src/
│ └── index.ts # Plugin implementation (type-specific boilerplate)
├── tests/
│ └── index.test.ts # Basic tests (metadata, healthCheck)
└── README.md
Converts a file format into text chunks.
interface ParserPlugin extends OpenDocsPlugin {
type: 'parser'
supportedTypes: string[] // File extensions: ['.pdf', '.docx']
multimodal?: boolean
parse(raw: RawDocument): AsyncIterable<ParsedChunk>
}The parse method must be an async generator (async function*). Yield one ParsedChunk per logical section. Set chunkType to 'semantic' for text, 'code-ast' for code, 'table' for tabular data, or 'slide' for presentations.
Fetches documents from an external source.
interface ConnectorPlugin extends OpenDocsPlugin {
type: 'connector'
discover(): AsyncIterable<DiscoveredDocument> // List available documents
fetch(ref: DocumentRef): Promise<RawDocument> // Download document content
watch?(onChange: (event: ChangeEvent) => void): Promise<Disposable> // Real-time sync
auth?(): Promise<AuthResult> // Authentication flow
}discover() yields documents one at a time. Include contentHash in the result to enable change detection (skip re-indexing unchanged docs).
Provides LLM, embedding, or reranking capabilities.
interface ModelPlugin extends OpenDocsPlugin {
type: 'model'
capabilities: { llm?: boolean; embedding?: boolean; reranker?: boolean; vision?: boolean }
generate?(prompt: string, opts?: GenerateOpts): AsyncIterable<string> // Streaming LLM
embed?(texts: string[]): Promise<EmbeddingResult> // Batch embedding
rerank?(query: string, docs: string[]): Promise<RerankResult> // Re-scoring
describeImage?(image: Buffer): Promise<string> // Vision
}The generate method must stream tokens via async function*. The embed method receives a batch of texts and returns dense vectors (and optionally sparse vectors).
Hooks into pipeline stages to transform data in-flight.
interface MiddlewarePlugin extends OpenDocsPlugin {
type: 'middleware'
hooks: {
stage: PipelineStage // 'before:parse' | 'after:chunk' | 'before:retrieve' | etc.
handler: (data: unknown) => Promise<unknown>
}[]
}Available stages: before:discover, after:discover, before:fetch, after:fetch, before:parse, after:parse, before:chunk, after:chunk, before:retrieve, after:retrieve, before:rerank, after:rerank, before:generate, after:generate, before:query, after:query.
Every plugin must declare:
{
name: string // e.g., '@opendocuments/parser-pdf'
type: PluginType // 'parser' | 'connector' | 'model' | 'middleware'
version: string // Semver (e.g., '0.1.0')
coreVersion: string // Compatible core version (e.g., '^0.1.0')
setup(ctx: PluginContext): Promise<void> // Initialization (required)
teardown?(): Promise<void> // Cleanup (optional)
healthCheck?(): Promise<HealthStatus> // Diagnostics (recommended)
metrics?(): Promise<PluginMetrics> // Metrics for admin dashboard (optional)
}| Type | Official Plugin | Community Plugin |
|---|---|---|
| Parser | @opendocuments/parser-<format> |
opendocuments-plugin-parser-<format> |
| Connector | @opendocuments/connector-<service> |
opendocuments-plugin-connector-<service> |
| Model | @opendocuments/model-<provider> |
opendocuments-plugin-model-<provider> |
| Middleware | @opendocuments/middleware-<name> |
opendocuments-plugin-middleware-<name> |
opendocuments plugin dev # Watch mode (tsc --watch)
opendocuments plugin test # Run vitest
opendocuments plugin publish # Publish to npm (npm publish --access public)Always use fetchWithTimeout from @opendocuments/core instead of raw fetch:
import { fetchWithTimeout } from '@opendocuments/core'
// Use appropriate timeouts:
// - healthCheck: 10 seconds
// - embed: 30 seconds
// - generate (streaming): 120 seconds
const res = await fetchWithTimeout('https://api.example.com/v1/data', {
headers: { 'Authorization': `Bearer ${this.apiKey}` },
}, 30000)Never include API keys or credentials in error messages.
We follow the Conventional Commits specification:
<type>(<scope>): <description>
| Type | When to Use | Example |
|---|---|---|
feat |
New feature | feat(core): add intent classification |
fix |
Bug fix | fix(server): escape FTS5 query input |
docs |
Documentation only | docs: update README with use cases |
test |
Adding or fixing tests | test(core): add retriever hybrid search test |
refactor |
Code change that doesn't fix a bug or add a feature | refactor: rename OpenDocs to OpenDocuments |
chore |
Build, tooling, or config changes | chore: update turbo.json pipeline |
ci |
CI/CD changes | ci: add Node 22 to test matrix |
| Scope | Package |
|---|---|
core |
@opendocuments/core |
server |
@opendocuments/server |
cli |
@opendocuments/cli |
web |
@opendocuments/web |
client |
@opendocuments/client |
| (none) | Multiple packages or root |
feat(core): add FTS5 sparse search with RRF merge
fix(server): use HttpOnly cookie for OAuth instead of URL params
docs: add plugin development guide to CONTRIBUTING.md
test(core): add hallucination guard grounding tests
refactor(cli): extract file discovery to shared utility
feat: add Google Drive and S3 connector plugins
Before submitting, verify:
- Code follows the project's conventions
- New features have tests
- All existing tests pass (
npm run test) - Build succeeds (
npm run build) - TypeScript type check passes (
npx turbo typecheck) - A changeset was created if the change affects published packages (
npx changeset) - CLI output uses ANSI symbols, not emojis
- New HTTP endpoints have appropriate auth protection
- No secrets or API keys in the code
- Smaller is better -- one logical change per PR
- Large refactors should be split into multiple PRs
- New plugins can be a single PR
- CI must pass before review begins
- At least one maintainer approval is required
- Address review comments, then re-request review
- After approval, the PR is squash-merged into
main
Use the Bug Report template:
- Description -- What happened?
- Steps to reproduce -- Numbered steps
- Expected behavior -- What should have happened?
- Actual behavior -- What actually happened?
- Environment -- OS, Node version, OpenDocuments version
Collecting environment info:
opendocuments doctor
node --version
npm --versionUse the Feature Request template:
- Description -- What do you want?
- Use case -- Why do you need it?
- Proposed implementation (optional) -- How might it work?
We use Changesets for automated releases:
- When PRs are merged, changeset files accumulate in
.changeset/ - A maintainer runs
npx changeset versionto bump versions and generate CHANGELOG entries npx changeset publishpublishes updated packages to npm- A GitHub Release is created automatically
| Bump | When | Example |
|---|---|---|
patch (0.1.x) |
Bug fixes, doc updates | Fix FTS5 query escaping |
minor (0.x.0) |
New features, new plugins | Add Google Drive connector |
major (x.0.0) |
Breaking changes | Change plugin interface |
All plugins declare coreVersion: '^0.1.0'. Core minor updates must maintain backward compatibility with existing plugins. The checkCompatibility() function automatically rejects incompatible plugins at registration time.
- Open a GitHub Issue for questions or problems
- Look for
good first issuelabels if you want an easy starting point - PRs with
help wantedlabels are actively seeking contributors
Thank you for helping make OpenDocuments better!