# AGENTS.md

> **IMPORTANT:** Keep this file and `CLAUDE.md` up to date whenever project structure, conventions, or architecture changes. If you add a new subsystem, endpoint, model, or pattern — update both files.

This file provides repository-level guidance for AI coding agents working on `ossctx`.

## What this project is

`ossctx` is a unified Python CLI and web platform for three local context systems:

- `codectx` for source indexing, entity extraction, and graph queries
- `docsctx` for document ingestion, community detection, and semantic search
- `otelctx` for telemetry ingestion, service maps, and observability APIs

The `common` package contains shared CLI, server, config, middleware, context assembly, and database helpers. The `ui` package contains the React SPA frontend and the unified FastAPI app that mounts all subsystems.

## Quick Start

```bash
# Install (uses uv for dependency management)
uv pip install -e .
uv pip install -e .[dev,tree-sitter]

# Run tests
uv run pytest tests/ -x -q

# Start the server
uv run ossCtx serve --port 8070

# Frontend dev (separate terminal)
cd ui/frontend && npm run dev
```

## Core Commands

```bash
ossCtx --version
ossCtx serve --port 8070              # Unified server (all subsystems + React SPA)
ossCtx code index . --db .codecontext.db
ossCtx docs stats --db .docscontext.db
ossCtx otel stats --db .otelcontext.db
```

## Repository Layout

```
common/     — Shared: CLI entry, server factory, middleware, DB base, context assembly
codectx/    — Code indexer, parser registry (20+ languages), repository, HTTP API, MCP
docsctx/    — Document loader, finalize pipeline, community detection, HTTP API, MCP
otelctx/    — OTLP ingest (gRPC+HTTP), repository, service graph, HTTP API, MCP
ui/         — Unified FastAPI app + React SPA (Vite + TypeScript + TailwindCSS v4)
tests/      — pytest suite (68+ tests)
hatch_build.py  — Build hook: runs npm ci && npm run build for wheel packaging
pyproject.toml  — Hatchling build, dependencies, console scripts
```

## Critical Conventions

### 1. API Path Pattern (NEVER change)
Sub-apps mount at `/api/{subsystem}` with internal routes under `/api/`:
```
/api/code/api/stats     ← Double /api is intentional
/api/docs/api/search    ← Do NOT consolidate
/api/otel/api/traces
```

### 2. SPA Mount Order
`mount_spa()` in `common/server.py` must be called **LAST** in `ui/app.py` — after all API and MCP mounts. The catch-all skips `api/`, `mcp/`, `v1/` prefixes.

### 3. Database Pattern
- SQLite with WAL mode via `create_engine_with_wal()`
- All repos use `session_scope()` context manager
- `repo.create_schema()` called on startup (idempotent)
- Default paths: `.codecontext.db`, `.docscontext.db`, `.otelcontext.db`

### 4. MCP Server Pattern
```python
server = FastMCP(name="...", stateless_http=True, json_response=True)
server.settings.streamable_http_path = "/"
app.mount("/mcp/subsystem", server.streamable_http_app())
```
Mounted at `/mcp/code`, `/mcp/docs`, `/mcp/otel`, `/mcp/unified`.

### 5. Frontend Conventions
- React Query with `staleTime: Infinity`, no auto-refetch — manual refresh buttons only
- TailwindCSS v4 with `@theme` design tokens
- Path alias `@/` → `src/`
- Sigma.js node labels must be `String()` coerced (crashes on non-string)
- Backend tree API returns dict-of-dicts, not `{name, children}`
- Build output: `ui/static/dist/` (gitignored)

### 6. No C Compiler Required
User's machine has no C compiler. Only use packages with precompiled wheels.

### 7. Compatibility Aliases
Do not remove: `codecontext`, `docscontext`, `otelcontext` CLI entry points.

## Subsystem Details

### CodeCtx
- CLI: `codectx/cli.py` | Default DB: `.codecontext.db` | Port: 8080
- Workflows: `index`, `query`, `stats`, `clean`, `serve`, `mcp`, `setup`
- Models: File, Entity, Dependency, EntityRelation
- MCP tools: `index_directory`, `stats`, `find_entities`, `get_dependencies`, `search_call_graph`

### DocsCtx
- CLI: `docsctx/cli.py` | Default DB: `.docscontext.db` | Port: 8090
- Workflows: local indexing, URL crawling, finalize, stats, serve, MCP, setup
- Models: Document, DocumentChunk, DocumentEntity, DocumentRelation, DocumentClaim
- Provider config via `DOCSCTX_*` environment variables
- MCP tools: `upload_documents`, `search_documents`, `get_document_structure`, `extract_entities`

### OtelCtx
- CLI: `otelctx/cli.py` | Default DB: `.otelcontext.db` | Port: 8088 | gRPC: 4317
- Workflows: ingest, stats, serve, MCP, setup
- Models: Span, Log, Metric, ServiceNode
- Includes archive, DLQ, TSDB, graph, sampling, websocket, Prometheus support
- MCP tools: `get_system_graph`, `get_service_health`, `search_logs`, `search_traces`, `get_metrics`

### UI / Frontend
- App factory: `ui/app.py` | React SPA: `ui/frontend/`
- Pages: Dashboard, Code, Docs, OTel, OTel Trace Detail, MCP Console
- Visualizations: Sigma.js (entity/service graphs), d3-hierarchy (treemap), Recharts (charts)
- Dev: `npm run dev` at :5173 proxies API to :8070

## Common Tasks for Agents

### Adding a new API endpoint
1. Add route to `{subsystem}/api/routes.py`
2. Add fetch function to `ui/frontend/src/api/{subsystem}.ts`
3. Add React Query hook to `ui/frontend/src/hooks/`
4. Update `CLAUDE.md` and `AGENTS.md`

### Adding a new page
1. Create page in `ui/frontend/src/pages/`
2. Add route to `ui/frontend/src/App.tsx`
3. Add nav item to `ui/frontend/src/components/layout/Sidebar.tsx`
4. Update `CLAUDE.md` and `AGENTS.md`

### Adding a new MCP tool
1. Add tool to `{subsystem}/mcp.py` using `@server.tool()` decorator
2. Update `CLAUDE.md` and `AGENTS.md`

## Validation

Before finishing any non-trivial task:
```bash
uv run pytest tests/ -x -q                    # Python tests
cd ui/frontend && npx tsc --noEmit             # TypeScript check
cd ui/frontend && npm run build                # Vite build
```

## Packaging

Console scripts in `pyproject.toml`: `ossCtx`, `codecontext`, `docscontext`, `otelcontext`

Build hook (`hatch_build.py`) runs `npm ci && npm run build` using `shutil.which("npm")` for cross-platform support. The wheel includes `ui/static/dist/` via force-include.
