Skip to content
emdecrPublic

About

A self-hosted personal knowledge base for collecting, organizing, and searching records (images, quotes, articles, links, notes) with AI-assisted tagging, semantic search, and conversational Q&A.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

257 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CogExt

A self-hosted cognition extension for collecting, organizing, and rediscovering ideas. Save images, quotes, articles, links, and notes – then search, chat with, and reflect on everything you've saved using AI.

Built as an alternative to tools like mymind.com or Pinterest, with full ownership of your data and no feed shaping what you see.

Features

  • AI auto-tagging — records are automatically tagged on save using Claude, no manual organization needed
  • Semantic search — find records by meaning, not just keywords, powered by pgvector embeddings
  • RAG chat — ask questions about your saved knowledge and get answers grounded in your own records
  • Image analysis — uploaded images are analyzed via Claude Vision and made searchable by their visual content
  • Weekly reflections — AI-generated digests that surface patterns, connections, and themes across your recent saves, with media recommendations for deeper exploration. Connections you've drawn between records yourself are fed in first.
  • Connections — manually link related records, with an optional note on why they belong together
  • Inline record links — type [[, press ⌘/Ctrl+Shift+K, or use the toolbar button in the editor to link to another record. Links render as chips with a hover preview, and each record lists the records that mention it under Mentioned in.
  • Collections — manually curate and reorder groups of records with drag-and-drop
  • Command palette — keyboard-first navigation and search (⌘K)
  • Admin panel (/admin) — backup status, AI spend, auth log, system health (including AI call failures), and data stats. Restricted to the emails in ADMIN_EMAILS.

Tech Stack

Layer Technology Why
Framework Next.js 16 (App Router, React 19) Server Components + Server Actions keep the AI/DB logic server-side with minimal client JS
Database PostgreSQL 17 + pgvector Vector similarity search alongside relational data in one database — no separate vector DB to manage
ORM Drizzle Type-safe queries, lightweight, generates raw SQL migrations
Embeddings Voyage AI (voyage-4-lite) High-quality embeddings via API — no GPU or local model server needed. Swappable via provider interface (Ollama included as alternative)
Tagging / Chat / Vision Claude API (Anthropic) Auto-tagging, RAG chat, image analysis, and weekly reflections. Swappable via provider interface (Ollama included as alternative)
Object Storage MinIO (dev and prod) / local filesystem (fallback) S3-compatible, self-hosted — provider pattern abstracts the switch
Auth Custom JWT + bcrypt HTTP-only cookies, proxy-based route protection, no third-party auth dependency
Styling Tailwind CSS + Radix UI Utility-first CSS with accessible, unstyled primitives
Containerization Docker + Docker Compose Multi-stage build (~150MB image), single docker compose up for the full stack

AI Provider Abstraction

The AI layer is provider-agnostic. All AI features code against two interfaces — EmbeddingProvider and LLMProvider (src/lib/ai/types.ts) — and a factory in src/lib/ai/index.ts decides which implementation to use. To swap providers, you change one file; no other code needs to touch.

The repo ships with two sets of implementations:

Provider Embeddings Tagging / Chat When to use
Cloud (default) Voyage AI Claude (Anthropic) Production, no GPU needed
Local Ollama (nomic-embed-text) Ollama (llama3.2) Offline dev, zero API costs, GPU recommended

To switch to Ollama, change the imports in src/lib/ai/index.ts from the Voyage/Claude providers to the Ollama providers and set AI_BASE_URL in your .env.

Architecture

┌─────────────┐     ┌──────────────────────────────────────────────────┐
│   Browser    │────▶│  Next.js App (Server Components + API Routes)   │
└─────────────┘     └──────┬───────────────────┬────────────────────────┘
                           │                   │
                    ┌──────▼──────┐    ┌───────▼──────────────┐
                    │ PostgreSQL  │    │  Cloud APIs           │
                    │ + pgvector  │    │  Voyage AI (embed)    │
                    └─────────────┘    │  Claude (tag/chat)    │
                                       └──────────────────────┘

How AI features work:

  1. Save — user creates a record (any type). If it's an image, Claude Vision generates a rich text description.
  2. Embed — Voyage AI produces a vector embedding from the record's text content and stores it alongside the record in Postgres.
  3. Tag — Claude generates 3–5 tags based on the content. All three steps run async after save.
  4. Search — queries are embedded with the same model, then matched against stored vectors via pgvector's HNSW index (cosine similarity). Keyword search runs in parallel.
  5. Chat — relevant records are retrieved via semantic search and injected as context into a Claude prompt (RAG). Responses stream back to the client.
  6. Reflect — a weekly job collects recent records plus any manual connections touching them, feeds them to Claude with the user's AI profile, and generates a reflection digest with themed media recommendations.

Getting Started

Prerequisites

Local Development Setup

# 1. Clone and install
git clone https://github.com/emdecr/cogext.git
cd cogext
npm install

# 2. Configure environment
cp .env.example .env
# Edit .env — set ANTHROPIC_API_KEY and VOYAGE_API_KEY

# 3. Start Postgres (host port 5435) and MinIO (API :9000, console :9001)
docker compose up -d

# 4. Run database migrations
npm run db:migrate

# 5. Start the dev server
npm run dev

The app will be available at http://localhost:3000.

Creating your account: registration is closed by default (ALLOW_REGISTRATION=false). Set it to true in .env, restart the dev server, register at /register, then set it back to false. To use the admin panel, add your email to ADMIN_EMAILS.

Storage in dev: .env.example defaults to STORAGE_PROVIDER=local (files go to public/uploads/). To use the local MinIO that docker compose starts, which matches prod, set STORAGE_PROVIDER=minio with minioadmin / minioadmin credentials and the cogext-uploads bucket (created by minio-init). See the comments in docker-compose.yml. To load a prod backup locally, use scripts/restore-local.sh rather than restore.sh.

Environment Variables

Variable Required Default Description
DATABASE_URL Yes — PostgreSQL connection string
JWT_SECRET Yes — Secret for signing auth tokens (≥32 chars in production)
VOYAGE_API_KEY Yes — Voyage AI API key for embeddings
ANTHROPIC_API_KEY Yes — Anthropic API key for chat, tagging, image analysis, reflections
EMBED_MODEL No voyage-4-lite Voyage AI embedding model
CHAT_MODEL No claude-sonnet-5-5 Claude model for chat, profile, and reflections
TAGGING_MODEL No claude-haiku-5-5 Claude model for auto-tagging on save
RECOMMENDATIONS_MODEL No claude-haiku-5-5 Claude model for weekly media recommendations
IMAGE_ANALYSIS_MODEL No claude-haiku-5-5 Claude model for describing uploaded images
WEB_SEARCH_TOOL_VERSION No web_search_20250305 Anthropic web search tool version
ALLOW_REGISTRATION No false Open /register for self-service sign-up. Turn on only while adding a user.
ADMIN_EMAILS No — Comma-separated emails allowed into /admin. Empty means nobody.
CRON_SECRET Prod — Bearer token for cron endpoints (reflections, AI health). ≥32 chars, checked at startup in production.
STORAGE_PROVIDER No local local or minio (minio makes the STORAGE_* vars required)
NEXT_PUBLIC_APP_URL No http://localhost:3000 Public-facing app URL
HEALTHCHECKS_API_KEY / HEALTHCHECKS_CHECK_ID No — Read-only healthchecks.io key and check ID for the admin Backups tab
AI_HEALTHCHECK_URL No — healthchecks.io ping URL for AI failure alerts (scripts/ai-health-check.sh)
HEALTHCHECK_URL No — healthchecks.io ping URL for backup notifications (scripts/backup.sh)
OFFSITE_ENABLED / OFFSITE_REMOTE / OFFSITE_RETAIN No false Upload backups to an rclone remote (scripts/backup.sh)

See .env.example for the full list, including MinIO credentials and the alert window settings.

Testing

# Unit + component tests (Vitest + React Testing Library)
npm test              # watch mode
npm run test:run      # single run
npm run test:unit     # unit tests only

# Integration tests (requires running database)
npm run test:integration

# E2E tests (Playwright — starts its own dev server on :3100)
npm run test:e2e
npm run test:e2e:ui   # interactive mode

# Coverage report
npm run test:coverage

Deployment

VPS with Docker Compose

# 1. Copy docker-compose.prod.yml to the server
scp docker-compose.prod.yml deploy@your-server:/opt/cogext/

# 2. Create .env on the server with production values
#    (see .env.example for all variables)
#    Key: DATABASE_URL must use db:5432 (Docker service name, internal port)

# 3. Start everything
docker compose -f docker-compose.prod.yml up -d

# 4. Verify
curl http://localhost:3000/api/health

The production stack runs 3 services on an internal Docker network:

Service Port Notes
app 3000 (exposed) Next.js standalone server, runs migrations on startup
db 5432 (internal) PostgreSQL 17 + pgvector, not exposed to host
minio 9001 (console), 9000 (API) S3-compatible object storage, both on localhost only

Next steps after deployment:

  • Set up a reverse proxy (nginx) with SSL via Certbot
  • Create the MinIO bucket and set its access policy
  • Configure GitHub Actions secrets for automated deploys
  • Set up the weekly reflection cron job (see below)

The steps above are the short version. The full step-by-step guide — cloud-init, DNS, nginx, SSL, MinIO, and every gotcha — lives in DEPLOY.md.

Backup & Recovery

Backups are created by scripts/backup.sh (Postgres pg_dump + MinIO volume tar) to /opt/backups/cogext/ with 7-day retention, and restored with scripts/restore.sh <timestamp>. See DEPLOY.md → Maintenance & Backup for the cron setup and download scripts.

Bringing the app up on a fresh server from a backup (disaster recovery, or migrating hosts):

  1. Have your backup + your old .env values on hand (the DB password and secrets must match, or the restored data won't decrypt/authenticate). Both are captured by the pre-teardown checklist.
  2. Provision the new server and bring the stack up empty — DEPLOY.md steps 1–12.
  3. Upload the backup, then run restore.sh <timestamp> on the server.
  4. Point DNS at the new IP, re-run Certbot, and update the DEPLOY_HOST GitHub secret.

The full runbook is DEPLOY.md → Recover onto a fresh server.

Weekly Reflection Cron Job

Reflections are generated by calling POST /api/reflections/generate with a cron secret. When triggered this way, the endpoint generates reflections for all users — each user's generation runs independently, and failures for one user don't block others.

On the server, add a cron job for the deploy user:

ssh deploy@your-server
crontab -e

Add a line to run every Monday at 7am UTC (adjust to your preference):

0 7 * * 1 curl -sf -X POST http://localhost:3000/api/reflections/generate -H "Authorization: Bearer YOUR_CRON_SECRET" >> /var/log/cogext-reflection.log 2>&1

Replace YOUR_CRON_SECRET with the value of CRON_SECRET from your .env file on the server.

Verify it works by running the curl command manually:

curl -s -X POST http://localhost:3000/api/reflections/generate \
  -H "Authorization: Bearer YOUR_CRON_SECRET" | jq .

The response includes a per-user breakdown: how many reflections were generated, skipped (no records that week), or errored.

Idempotent: calling the endpoint multiple times for the same period won't create duplicate reflections — it returns the existing one.

Custom periods (backfill or multi-week synthesis): pass a dateRange body to generate a reflection for any period instead of the current week. The range can be a single week (backfilling a missed cron run) or span multiple weeks if you'd rather run reflections less frequently and let records compile:

curl -s -X POST http://localhost:3000/api/reflections/generate \
  -H "Authorization: Bearer YOUR_CRON_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"dateRange": {"start": "2026-03-30", "end": "2026-04-05"}}' | jq .

Both dates must be YYYY-MM-DD and start must be on or before end.

Customizing AI Prompts

All LLM prompts live in src/lib/ai/. If you want to adjust tone, format, or behavior:

Feature File What to edit
Auto-tagging src/lib/ai/claude-llm.ts System prompt in the tag() method
Chat / RAG src/app/api/chat/route.ts System prompt built in the route handler
Image analysis src/lib/ai/analyze-image.ts System prompt for Claude Vision
Weekly reflections src/lib/ai/reflection.ts System prompt + buildReflectionPrompt() (includes manual connections)
Media recommendations src/lib/ai/generate-recommendations.ts System prompt + recommendation instructions
User profile src/lib/ai/profile.ts System prompt for profile extraction

CI/CD via GitHub Actions

The repo includes a CI pipeline (.github/workflows/ci.yml) that runs on every push and PR to main:

  • Lint + typecheck — eslint and tsc --noEmit
  • Unit tests — Vitest
  • Build verification — full production build
  • Docker image — builds and pushes to ghcr.io on main (tagged with commit SHA + latest)
  • Deploy — SSHs into the server, pulls the new image, and restarts the app container

To enable Docker pushes, the workflow uses GITHUB_TOKEN (automatic in GitHub Actions). For the deploy job, add these secrets in your repo settings:

  • DEPLOY_HOST — server IP or hostname
  • DEPLOY_SSH_KEY — private SSH key for the deploy user on the server

Project Structure

cogext/
├── .github/workflows/     # CI pipeline
├── deploy/                # Cloud-init config for server provisioning
├── drizzle/               # Generated SQL migrations
├── e2e/                   # Playwright E2E tests
├── scripts/
│   ├── backup.sh          # Database + storage backup (optional offsite upload)
│   ├── restore.sh         # Restore from backup (prod)
│   ├── restore-local.sh   # Load a prod backup into local dev (rewrites image URLs)
│   ├── download-backups.sh / download-minio-images.sh  # Pull backups/images from the server
│   ├── healthcheck.sh     # Post-deploy/reboot smoke test (prod)
│   ├── ai-health-check.sh # Cron: alert on AI call failures via healthchecks.io
│   ├── re-embed-all.ts    # Regenerate missing embeddings
│   └── migrate.mjs        # Standalone migration runner (used in Docker)
├── src/
│   ├── app/               # Next.js routes, pages, and API routes
│   │   ├── (app)/admin/   # Admin panel tabs (backups, AI spend, auth log, system, data)
│   │   └── api/           # REST endpoints (auth, chat, upload, health, profile, records, reflections)
│   ├── components/        # React components (forms, cards, command palette, etc.)
│   ├── db/
│   │   ├── index.ts       # Database connection pool
│   │   └── schema.ts      # Drizzle schema (pgvector index)
│   ├── lib/
│   │   ├── actions/       # Server Actions (records, search, tags, collections, reflections)
│   │   ├── ai/            # AI providers (embeddings, tagging, chat, image analysis, reflections)
│   │   ├── storage/       # Storage abstraction (local filesystem / MinIO)
│   │   ├── auth.ts        # Session management
│   │   ├── config.ts      # Centralized env var config with validation
│   │   ├── logger.ts      # Structured logging (JSON in prod)
│   │   └── rate-limit.ts  # In-memory rate limiting
│   ├── proxy.ts            # Auth proxy for route protection (Next 16 middleware)
│   └── test/              # Test setup, helpers, and mocks
├── Dockerfile             # Multi-stage build (node:24-alpine, ~150MB)
├── docker-compose.yml     # Dev services (Postgres, MinIO)
├── docker-compose.prod.yml # Production stack (app + db + minio)
└── docker-entrypoint.sh   # Runs migrations, then starts the server

About

A self-hosted personal knowledge base for collecting, organizing, and searching records (images, quotes, articles, links, notes) with AI-assisted tagging, semantic search, and conversational Q&A.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages