Skip to content

Contributing to Deriva

uv Pydantic Duckdb

Code style: ruff Typing: ty codecov

Thanks for your interest in contributing to Deriva!

Python 3.14+ is required. The project uses modern Python features and is developed with 3.14 in mind.

Tooling: We use uv for package management, Ruff for linting/formatting, and ty for type checking. Pydantic AI is used for interacting with LLMs, DuckDB for storing configurations and settings. For testing we use pytest and codecov for CI test coverage reporting.

Development Setup

# Clone the repo
git clone https://github.com/StevenBtw/deriva.git
cd Deriva

# Copy environment template
cp .env.example .env
# Edit .env with your configuration (LLM keys, etc.)

# Install all three packages (editable) and the development tools
uv sync

# Run the studio (build the front end once: cd studio && npm install && npm run build)
uv run deriva

# Run linter
uv run ruff check .

# Run type checker
uv run ty check .

Workspace and packages

The repository is a uv workspace that builds three packages, released together with one version number. They share one Python namespace, deriva (a namespace package: there is no deriva/__init__.py).

Package Source Holds
deriva-cli the root, deriva/ adapters, modules, common, services and the CLI
deriva-studio packages/deriva-studio/src/deriva/studio/ the studio backend and its built front end (static/, from studio/)
deriva-dev packages/deriva-dev/src/deriva/bench/ benchmarking, with its CLI commands and its studio API

uv sync installs all three as editable, so a checkout always has benchmarking. The CLI and the studio load deriva.bench only when it is installed (deriva.services.about.features()); without it, deriva-cli benchmark says how to install deriva-dev.

Build the packages the way users get them:

cd studio && npm ci && npm run build && cd ..
uv build --all-packages --no-sources        # dist/: three wheels and three sdists

--no-sources builds without the local overrides in [tool.uv.sources], as uv recommends before publishing. tests/test_packaging.py builds the wheels and checks that each holds exactly its own files.

To try a build as a user would, install it as a tool with every workspace wheel by path; uv otherwise reuses a cached build of the same version number:

uv tool install --python 3.14 dist/deriva_studio-<version>-py3-none-any.whl --with dist/deriva_cli-<version>-py3-none-any.whl

Point DERIVA_HOME at an empty folder to see a first start.

To release, set the same version in the three pyproject.toml files and in the two pins between them (deriva-studio pins deriva-cli==<version>, deriva-dev pins deriva-studio==<version>), then push the tag v<version>. The release workflow checks the versions and pins, builds and smoke tests the packages, publishes them to PyPI with trusted publishing and attaches constraints.txt to the GitHub release.

Architecture

Deriva follows a layered architecture with strict separation of concerns:

  • studio/ (FastAPI + React): Local web UI for running the pipeline, the graphs, the model and configuration
  • cli/cli.py: Headless CLI for automation and scripting
  • Services: Shared orchestration layer with PipelineSession as the unified API
  • Adapters: Stateful services for I/O, persistence, connections
  • Modules: Pure functions for business logic transformations

Key Principle: Both the studio and the CLI use PipelineSession from the services layer. This provides a unified API for lifecycle management, queries, and orchestration. Configuration lives in DuckDB (single source of truth). Data flows through pure transformations, with I/O isolated to adapters.

Architectural Boundaries (Enforced by Ruff)

CLI      → services only (PipelineSession is the API)
App      → services only (PipelineSession is the API)
Bench    → services, adapters, modules, common (deriva-dev; only the CLI and studio entry points load it)
Services → adapters, modules, common
Adapters → common only (NOT modules or services)
Modules  → common only (NOT adapters or services)
Common   → stdlib and third-party only

These boundaries are enforced at lint time via Ruff's TID251 rule with per-layer ruff.toml files.

The same rule keeps third-party libraries where their package declares them (extend-banned-api in pyproject.toml, inherited by every layer): the heavy engines (pydantic-ai, spaCy, CTranslate2, DuckDB, grafeo, lxml, tree-sitter) only in adapters/, the web stack (FastAPI, Starlette, uvicorn, the widgets) only in the studio and bench, and packages no Deriva package declares (requests, anywidget, ipywidgets, marimo) nowhere.

Architecture Overview ### Component Hierarchy
deriva/
├── studio/
│   ├── app.py               - FastAPI app factory (studio layer, services only)
│   ├── routers/             - API routes (repositories, configs, graph, model, runs, grafeo)
│   └── static/              - Built React front end (from studio/ at the repo root)
├── cli/
│   └── cli.py               - Headless CLI + uses PipelineSession
│
├── services/ (Shared orchestration layer)
│   ├── session.py           - PipelineSession: unified API for the CLI and the studio
│   ├── config.py            - Config CRUD (read/write DuckDB settings)
│   ├── extraction.py        - Run extraction step
│   ├── derivation.py        - Run derivation step
│   ├── pipeline.py          - Orchestrate full pipeline
│   └── benchmarking.py      - Multi-model benchmarking and analysis
│
├── common/ (Shared utilities)
│   ├── types.py     - Shared TypedDicts, Protocols, ProgressReporter
│   ├── logging.py   - Pipeline logging with structlog (JSON Lines output)
│   ├── chunking.py  - File chunking with overlap support
│   └── utils.py     - File encoding, helpers
│
├── adapters/ (Stateful I/O services)
│   ├── database/    - DuckDB configuration storage
│   ├── grafeo/      - Embedded graph database (grafeo)
│   ├── repository/  - Git operations
│   ├── graph/       - Graph CRUD (namespace: Graph)
│   ├── archimate/   - ArchiMate CRUD (namespace: Model)
│   └── llm/         - LLM provider abstraction (Azure, OpenAI, Anthropic, Ollama)
│
└── modules/ (Pure business logic)
    └── analysis/
        ├── consistency.py    - Model consistency checks
        ├── deviation.py      - Deviation analysis
        └── types.py          - Shared analysis types
    └── extraction/
        ├── base.py           - Shared extraction utilities (ID generation, deduplication)
        ├── classification.py - File type classification
        ├── repository.py     - Repository node extraction
        ├── directory.py      - Directory node extraction
        ├── file.py           - File node extraction (with type/subtype)
        ├── edges.py          - Unified edge extraction (IMPORTS, CALLS, REFERENCES, etc.)
        ├── type_definition.py - Classes/functions (AST for Python, LLM for others)
        ├── method.py         - Methods within type definitions
        ├── business_concept.py - Domain concepts (LLM)
        ├── technology.py     - Frameworks/libraries detection
        ├── external_dependency.py - External dependencies
        ├── test.py           - Test definitions
        ├── ast_extraction.py - Python AST parsing
        └── input_sources.py  - Input source filtering
    └── derivation/
        ├── base.py           - Shared utilities (prompts, parsing, graph filtering)
        ├── element_base.py   - HybridDerivation base class for all element modules
        ├── application_component.py - ApplicationComponent derivation
        ├── application_interface.py - ApplicationInterface derivation
        ├── application_service.py   - ApplicationService derivation
        ├── business_actor.py        - BusinessActor derivation
        ├── business_event.py        - BusinessEvent derivation
        ├── business_function.py     - BusinessFunction derivation
        ├── business_object.py       - BusinessObject derivation
        ├── business_process.py      - BusinessProcess derivation
        ├── data_object.py           - DataObject derivation
        ├── device.py                - Device derivation
        ├── node.py                  - Node derivation
        ├── system_software.py       - SystemSoftware derivation
        └── technology_service.py    - TechnologyService derivation
### Layer Responsibilities
┌─────────────────┐         ┌─────────────────┐
│     Studio      │         │      CLI        │
│  (web UI)       │         │   (headless)    │
└────────┬────────┘         └────────┬────────┘
         │                           │
         └───────────┬───────────────┘
                     │
              ┌──────▼──────┐
              │ PipelineSession │  ← unified API
              └──────┬──────┘
                     │
              ┌──────▼──────┐
              │  Services   │  ← orchestration functions
              └──────┬──────┘
                     │
         ┌───────────┼───────────┐
         │           │           │
  ┌──────▼──────┐ ┌──▼───┐ ┌─────▼─────┐
  │  Adapters   │ │Modules│ │  Common   │
  │    (I/O)    │ │(pure) │ │ (shared)  │
  └─────────────┘ └──────┘ └───────────┘
### Data Flow Pattern
User clicks "Run" in the studio  OR  runs `deriva-cli run` in the CLI
    ↓
┌─────────────────────────────────────────────────────────────┐
│ PIPELINESESSION (unified API for the CLI and the studio)    │
├─────────────────────────────────────────────────────────────┤
│ with PipelineSession() as session:                          │
│     session.run_extraction(repo_name="my-repo")             │
│     session.run_derivation()                                │
│     session.export_model("output.xml")                      │
│                                                             │
│ # For the studio (one session per process):                 │
│     stats = session.get_graph_stats()                       │
│     elements = session.get_archimate_elements()             │
└─────────────────────────────────────────────────────────────┘
    ↓
┌─────────────────────────────────────────────────────────────┐
│ EXTRACTION (inside services.extraction)                     │
├─────────────────────────────────────────────────────────────┤
│ Phases: classify → parse                                    │
│ 1. Load config from DuckDB via services.config              │
│ 2. Get repos from RepositoryManager                         │
│ 3. Classify: modules.extraction.classification [PURE]       │
│ 4. Parse: modules.extraction.structural/* [PURE]            │
│ 5. Parse: modules.extraction.llm/* [PURE + LLM]             │
│ 6. Persist via GraphManager.add_node() [I/O]                │
└─────────────────────────────────────────────────────────────┘
    ↓
┌─────────────────────────────────────────────────────────────┐
│ DERIVATION (inside services.derivation)                     │
├─────────────────────────────────────────────────────────────┤
│ Phases: prep → generate → refine                             │
│ 1. Prep: Graph enrichment (PageRank, communities, k-core)    │
│ 2. Generate: Query candidates with enrichment data [I/O]    │
│ 3. Generate: Call modules.derivation.{element}.generate()   │
│ 4. Generate: Persist via ArchimateManager.add_element()     │
│ 5. Relationship: Derive relationships per-element or batch  │
└─────────────────────────────────────────────────────────────┘
    ↓
Export via ArchimateManager.export_to_xml() [I/O]
    ↓
Studio: streams progress and shows results  |  CLI: prints summary to stdout
### Studio Structure | Area | Purpose | |------|---------| | Workspace | Run configuration, live log, intermediate and output graph (anywidget-graph), ArchiMate model (anywidget-archimate) | | Repositories | Clone, inspect, delete | | General & file types | Settings and the file type registry | | Extraction / Derivation config | Steps with versions, prompt editing, saves as new versions | The studio backend uses PipelineSession for all operations. ### Quick Reference | Component | Purpose | Can Do | Cannot Do | |-----------|---------|--------|-----------| | **studio/** | Web UI (FastAPI + React) | Serve the API and the front end, use PipelineSession | Import adapters/modules/common directly | | **cli/cli.py** | Headless CLI | Parse args, use PipelineSession, print output | Import adapters/modules directly | | **PipelineSession** | Unified API | Lifecycle, queries, orchestration | Business logic | | **Services** | Orchestration | Load config, run pipeline steps, coordinate adapters | Direct I/O, pure business logic | | **Adapters** | I/O & Persistence | Read .env, connect to services, CRUD | Import other adapters, pure logic | | **Modules** | Business Logic | Pure transformations, return data/errors | I/O, import adapters, external state |

Code Style

Naming at a Glance

Element Convention Example
Files/modules snake_case file_utils.py, manager.py
Classes PascalCase GraphManager, ExtractionResult
Functions/methods snake_case read_file_with_encoding()
Variables snake_case file_path, element_type
Constants UPPER_SNAKE_CASE DEFAULT_TIMEOUT, MAX_RETRIES
Private _prefix _internal_cache, _serialize_value()
TypedDicts PascalCase PipelineResult, LLMDetails
Protocols PascalCase + descriptive ExtractionFunction, Serializable

Architectural Rules

  • Adapters: Stateful, own schemas, provide CRUD, raise exceptions
  • Modules: Pure functions, no I/O, return data/errors as dicts
  • app/app.py: Orchestration only, no business logic
  • Single config source: All configuration in .env (no YAML)

File Structure

Every Python file follows this structure:

"""Module-level docstring explaining what this module does."""

from __future__ import annotations  # Always include

# Standard library
import json
from pathlib import Path
from typing import Any, Protocol, TypedDict

# Third-party
from pydantic import BaseModel

# Local imports
from common.types import PipelineResult
from .models import RepositoryNode

# Module constants
DEFAULT_TIMEOUT = 30

# Public API
__all__ = ["process_file", "FileProcessor"]


# =============================================================================
# Section Header (for longer files)
# =============================================================================

class FileProcessor:
    """Class implementation..."""
    pass

Module Organization

Package style (directory with multiple files) - use when a module has related files:

adapters/graph/
├── __init__.py      # Re-exports: from .manager import GraphManager
├── manager.py       # Main class
├── models.py        # Data models
└── queries.py       # Complex queries (if needed)

Flat style (single file) - use for standalone utilities:

common/
├── file_utils.py    # Just utility functions
├── time_utils.py
└── types.py

Rule of thumb: Start flat, graduate to a package when you need models.py or other supporting files.

Import Rules

  1. Always start with from __future__ import annotations
  2. Group imports: stdlib → third-party → local (blank line between groups)
  3. Relative imports for same-package: from .models import Node
  4. Absolute imports for cross-package: from common.types import Result
  5. Multi-line imports when 3+ items from same module
Type Hints #### Modern Syntax (Python 3.10+)
# Unions - use | not Optional or Union
def get_user(id: int) -> User | None:
    ...

# Collections - use lowercase builtins
items: list[str] = []
mapping: dict[str, int] = {}
#### TypedDict for Structured Data Use TypedDict for JSON-like structures:
class LLMDetails(TypedDict, total=False):
    """Tracks LLM call metadata for observability."""
    prompt: str
    response: str
    tokens_in: int
    tokens_out: int
    cache_used: bool
#### Protocol for Interfaces Use Protocol for duck typing with type safety:
class ExtractionFunction(Protocol):
    """Contract for extraction functions."""

    def __call__(
        self,
        file_path: str,
        file_content: str,
        repo_name: str,
        llm_query_fn: Callable,
        config: dict[str, Any]
    ) -> ExtractionResult:
        ...
#### Dataclass for Concrete Objects Use dataclass for objects with behavior or identity:
@dataclass
class RepositoryNode:
    """Represents a code repository in the knowledge graph."""
    name: str
    url: str
    created_at: datetime
    branch: str | None = None

    def generate_id(self) -> str:
        return f"Repository_{self.name}"
#### When to Use What | Use | When | |-----|------| | `TypedDict` | Data shapes (JSON, API responses, result dicts) | | `@dataclass` | Objects with identity/behavior (nodes, entities) | | `BaseModel` | External data validation (API input, config files) |
Docstrings **Core principle:** Explain the *why*, not the *what*. The code shows what happens; docstrings explain why it matters. #### Module Docstrings Brief. What is this module's job?
"""JSON parsing utilities for Deriva.

Handles the messy reality of LLM output that's almost-but-not-quite valid JSON.
"""
#### Class Docstrings What does this class represent? Why does it exist?
class GraphManager:
    """
    High-level interface for graph database operations.

    Wraps grafeo complexity and provides domain-specific operations
    like "add repository" rather than raw graph queries.
    """
#### Function Docstrings Focus on behavior, edge cases, and non-obvious aspects:
def read_file_with_encoding(file_path: Path) -> str | None:
    """
    Read a file with automatic encoding detection.

    Handles the encoding mess you find in real codebases: UTF-8 with/without
    BOM, UTF-16 variants, and falls back to Latin-1 for binary-ish text files.
    Returns None rather than raising - caller decides how to handle.

    Args:
        file_path: Path to the file

    Returns:
        File content as string, or None if reading fails
    """
#### When to Skip Docstrings Trivial methods where the name says everything:
def __enter__(self):
    self.connect()
    return self
Comments Comments explain **why**, not **what**. #### Good Comments
# BOM markers indicate encoding - check before trying UTF-8
if raw.startswith(b'\xff\xfe'):
    return raw.decode('utf-16-le')

# MERGE needs deterministic IDs to avoid duplicates
node_id = f"Repository_{repo_name}"

# LLMs sometimes return markdown-wrapped JSON
content = content.strip().removeprefix("```json").removesuffix("```")
#### Bad Comments
# Increment counter  <- obvious from code
counter += 1

# Check if file exists  <- obvious from code
if file_path.exists():
#### Section Headers Use for organizing longer files (100+ lines):
# =============================================================================
# Graph Query Methods
# =============================================================================
Error Handling #### Be Specific
# Good - catch what you expect
try:
    data = json.loads(content)
except json.JSONDecodeError as e:
    return ParseResult(success=False, error=f"Invalid JSON: {e}")

# Bad - catches everything
try:
    data = json.loads(content)
except Exception:
    return None
#### Return vs Raise - **Return None/Result** for expected failures (file not found, parse error) - **Raise** for unexpected failures or contract violations
def read_file(path: Path) -> str | None:
    """Returns None if file can't be read."""
    try:
        return path.read_text()
    except (OSError, UnicodeDecodeError):
        return None


def connect(self) -> None:
    """Raises ConnectionError if connection fails."""
    try:
        self._db = get_database()
    except Exception as e:
        raise ConnectionError(f"Failed to connect: {e}") from e
Python 3.14 Features Since we're on Python 3.14, use these modern features: #### Deferred Annotations (PEP 649) No need to quote forward references:
from __future__ import annotations

class Node:
    parent: Node | None = None  # Works! No quotes needed
#### Exception Groups (PEP 654) Handle multiple exceptions with exception groups:
# Exception groups (Python 3.11+)
try:
    async_operations()
except* TimeoutError:
    handle_timeout()
except* ConnectionRefusedError:
    handle_connection_error()
#### New UUID Functions
from uuid import uuid7

# uuid7 is time-ordered AND random - better than uuid4
id = uuid7()
#### Path Improvements
from pathlib import Path
import shutil

src = Path("source.txt")
dst = Path("dest.txt")

# Use shutil for copy/move operations
shutil.copy2(src, dst)
shutil.move(src, dst)
#### datetime Parsing
from datetime import datetime

# Parse dates using datetime
d = datetime.strptime("2024-01-15", "%Y-%m-%d").date()
Formatting #### String Quotes Use double quotes consistently:
# Good
name = "Deriva"
data = {"key": "value"}

# Avoid
name = 'Deriva'
#### Line Length 180 characters max (configured in `pyproject.toml`). But prefer shorter when readable. #### Checklist Before Committing - [ ] `from __future__ import annotations` at top - [ ] Imports organized: stdlib → third-party → local - [ ] Type hints on all public functions - [ ] Docstrings on all public classes and functions - [ ] No `print()` statements (use logging) - [ ] Double quotes for strings - [ ] `__all__` defined for modules with public API - [ ] `ruff check` passes
Adapter Rules ### Purpose - Complex, stateful services that manage persistence and external systems - Own their schemas, metamodels, and validation logic - Provide CRUD operations for their domain - Do **NOT** contain business logic (that's in modules) ### Lifecycle - **One instance per session**: `PipelineSession` creates the adapters and keeps them for its lifetime - Maintain **persistent connections** for session lifetime - Support **auto-reconnect** with retry logic (max 3 attempts, exponential backoff) - Cleanup via `__del__` or `__exit__` methods ### Configuration - **Read .env** in `__init__` using `python-dotenv` - **Cache** config values (don't re-read on every operation) - Provide **defaults** for optional settings ### Dependencies - Can import **infrastructure adapters** (e.g., GraphManager ← GrafeoConnection) - **Cannot** import other domain adapters (e.g., GraphManager ✗← ArchimateManager) - **Cannot** import modules ### Error Handling - **Raise exceptions** with clear messages - Use **custom exception classes** (e.g., `GraphError`, `ArchimateError`) - Retry transient errors (connection issues) - Do **NOT** catch and silence errors ### Interface - Export via `__init__.py` (e.g., `from .manager import GraphManager`) - Consistent method naming: `add_*`, `get_*`, `update_*`, `delete_*`, `query_*` - Return **data** (dicts, lists, dataclasses), not side effects - Accept **parameters** from the services (don't read global state) ### Adapter Structure
adapters/{name}/
├── __init__.py           # Re-export manager class and models
├── manager.py            # Main manager class with all CRUD logic
└── models.py             # Data models with generate_id() methods
### ID Generation Pattern Node/element models include a `generate_id()` method for consistent ID generation:
@dataclass
class RepositoryNode:
    name: str
    url: str
    # ...

    def generate_id(self) -> str:
        """Generate a unique ID for this node."""
        return f"Repository_{self.name}"
The adapter's `add_node()` method auto-generates IDs when not provided:
def add_node(self, node: GraphNode, node_id: str | None = None) -> str:
    if node_id is None:
        node_id = node.generate_id()
    # ... persist to database
LLM Manager ### Overview The LLM adapter (`adapters/llm/`) provides a unified interface for multiple LLM providers using **pydantic-ai** for agent-based LLM interactions with automatic retries, caching, and structured output support. **Supported Providers:** - **Azure OpenAI** - Enterprise Azure deployments - **OpenAI** - Direct OpenAI API - **Anthropic** - Claude models - **Mistral** - Mistral AI models - **Ollama** - Local LLM inference (no API key required) ### Basic Usage
from adapters.llm import LLMManager

llm = LLMManager()  # Reads provider config from .env
response = llm.query("What is Python?")

if response.response_type == "live":
    print(response.content)
elif response.response_type == "cached":
    print(f"From cache: {response.content}")
else:
    print(f"Error: {response.error}")
### Structured Output with pydantic-ai Use `response_model` to get validated, type-safe responses via pydantic-ai agents:
from pydantic import BaseModel, Field
from adapters.llm import LLMManager

class BusinessConcept(BaseModel):
    name: str = Field(description="Concept name")
    type: str = Field(description="actor, service, process, etc.")
    description: str = Field(description="Brief description")

llm = LLMManager()
result = llm.query(
    prompt="Extract the main business concept from: ...",
    response_model=BusinessConcept
)

# result is a validated BusinessConcept instance
print(result.name)  # Type-safe, IDE autocomplete works
### Provider Configuration Set provider via `LLM_PROVIDER` in `.env`:
# Use local Ollama
LLM_PROVIDER=ollama
LLM_OLLAMA_MODEL=llama3.2
LLM_OLLAMA_API_URL=http://localhost:11434/api/chat

# Use Azure OpenAI
LLM_PROVIDER=azure
LLM_AZURE_API_URL=https://your-resource.openai.azure.com/...
LLM_AZURE_API_KEY=your-key
LLM_AZURE_MODEL=gpt-4o-mini
### Direct Provider Usage For advanced use cases, create providers directly:
from adapters.llm import create_provider, ProviderConfig

config = ProviderConfig(
    api_url="http://localhost:11434/api/chat",
    api_key=None,
    model="llama3.2"
)
provider = create_provider("ollama", config)

result = provider.complete(
    messages=[{"role": "user", "content": "Hello"}],
    temperature=0.7
)
print(result.content)
### Response Types All queries return one of three Pydantic response types: | Type | When | Key Fields | |------------------|----------------|-------------------------------------| | `LiveResponse` | Fresh API call | `content`, `usage`, `finish_reason` | | `CachedResponse` | From cache | `content`, `cache_key`, `cached_at` | | `FailedResponse` | Error occurred | `error`, `error_type` | ### Caching - Responses are cached to `workspace/cache/` by default - Cache key = SHA256(prompt + model + schema + system prompt + effective temperature + max_tokens), so changing any of them never returns an answer cached for other settings; benchmark runs also add a per-run `bench_hash` so each run gets its own entries - Disable with `LLM_NOCACHE=true` or `use_cache=False` - Errors are also cached to prevent retry storms ### Structured Output Each call's output mode follows from what it asks for; there is no setting per model. Calls with a response model (the extraction classifications) use pydantic-ai's tool output and are validated against the model. Derivation calls ask for JSON in the prompt, and the pipeline reads the answer: a whole JSON answer, a code fence, or the JSON after a short explanation.
Module Rules ### Purpose - **Pure business logic** - data transformations only - Abstracts complex operations away from the services and the UI - Do **NOT** manage state, connections, or I/O ### Purity - **Pure functions**: Same input → same output - **No side effects**: Don't write to files, databases, network - **No state**: No class variables, no module-level state - Return **data** (dicts, lists, dataclasses), never `None` - **No adapter imports** (receive adapter data via parameters) - **No I/O operations** (the services do I/O through adapters) ### Dependencies - Can import **Python stdlib** (pathlib, json, re, typing, dataclasses, etc.) - Can import **each other** (e.g., orchestration ← classification) - Can use **external libs** if pure (e.g., polars for data transforms) - **Cannot** import adapters - **Cannot** import UI libraries ### Error Handling - Return **error data** in results (e.g., `{'errors': [...]}`) - Use **type hints** for clarity - Do **NOT** raise exceptions (return errors as data) ### Result Structure
{
    'success': bool,
    'data': {...},
    'errors': [str],
    'stats': {...}
}
Module Pattern ### Shared Types (`common/types.py`) All pipeline modules use shared TypedDicts and Protocols for consistent interfaces:
from common.types import (
    # Base result type - all modules return this structure
    BaseResult,       # success, errors, stats
    LLMDetails,       # prompt, response, tokens_in, tokens_out, cache_used

    # Extraction types
    ExtractionResult, # BaseResult + data: {nodes, edges} + llm_details
    BatchExtractionResult,

    # Derivation types
    DerivationResult, # BaseResult + data: {elements_created, issues} + llm_details
    DerivationConfig, # step_name, phase, input_graph_query, instruction, example

    # Function protocols for type safety
    ExtractionFunction,
    DerivationFunction,
)
### Base Files (`base.py`) Each module folder has a `base.py` file with shared utilities: | Module | Base File | Provides | |--------|-----------|----------| | `extraction/` | `base.py` | `generate_node_id()`, `parse_json_response()`, `create_extraction_result()` | | `derivation/llm/` | `base.py` | `DERIVATION_SCHEMA`, `build_derivation_prompt()`, `parse_derivation_response()` | | `derivation/graph/` | `base.py` | Graph algorithm utilities for refinement phase | All base files also provide: - `current_timestamp()` - UTC ISO format - `create_empty_llm_details()` - Initialize LLM details dict - `extract_llm_details_from_response()` - Parse LLM response metadata ### Lazy Module Loading (`services/derivation.py`) Derivation modules are loaded lazily by element type:
# services/derivation.py
def _load_element_module(element_type: str) -> Any:
    """Lazily load element generation module."""
    if element_type == "ApplicationComponent":
        from deriva.modules.derivation import application_component as module
    elif element_type == "BusinessObject":
        from deriva.modules.derivation import business_object as module
    # ... other element types
    return module

def generate_element(graph_manager, archimate_manager, llm_query_fn, element_type, ...):
    """Route to appropriate module based on element_type."""
    module = _load_element_module(element_type)
    return module.generate(graph_manager, archimate_manager, ...)
### Adding New Element Types To add a new derivation element type (e.g., `Contract`): 1. Create `modules/derivation/contract.py` with a `generate()` function:
"""Contract element derivation."""
from __future__ import annotations

from deriva.modules.derivation.base import (
    Candidate, GenerationResult, batch_candidates, build_derivation_prompt,
    build_element, get_enrichments, parse_derivation_response, query_candidates,
    DERIVATION_SCHEMA,
)

def generate(
    graph_manager, archimate_manager, engine, llm_query_fn,
    query: str, instruction: str, example: str,
    max_candidates: int, batch_size: int,
    temperature: float | None = None, max_tokens: int | None = None,
) -> GenerationResult:
    # 1. Get enrichments from DuckDB
    enrichments = get_enrichments(engine)
    # 2. Query candidates using the graph query
    candidates = query_candidates(graph_manager, query, enrichments)
    # 3. Filter/limit candidates
    candidates = candidates[:max_candidates]
    # 4. Batch and process with LLM
    # ... (see existing modules for full pattern)
    return GenerationResult(success=True, elements_created=count, ...)
2. Register in `services/derivation.py` `_load_element_module()`:
elif element_type == "Contract":
    from deriva.modules.derivation import contract as module
3. Add derivation config in `adapters/database/data/derivation_config.json`
Module Reference ### Core Modules #### `extraction/classification.py` **Goal:** Classify files by type based on the file type registry.
def classify_files(
    file_paths: List[str],
    file_type_registry: List[Dict[str, str]]
) -> Dict[str, Any]:
    """
    Returns: {
        'classified': [...],   # Files with known types
        'undefined': [...],    # Files with unknown extensions
        'stats': {...},
        'errors': [...]
    }
    """
**Rules:** - Classification priority: full filename → wildcard pattern → extension - Never raises exceptions - returns errors in result dict - Registry comes from DatabaseManager (passed as data, not manager) #### `logging.py` **Goal:** JSON Lines logging for pipeline runs using structlog with configurable verbosity.
class LogLevel(int, Enum):
    PHASE = 1   # High-level: classification, extraction, derivation
    STEP = 2    # Steps: Repository, Directory, File, etc.
    DETAIL = 3  # Item-level: each file, node, edge

class RunLogger:
    """Structured logger using structlog for JSON Lines output."""
    def phase_start(self, phase: str, message: str = "") -> None
    def phase_end(self, phase: str, message: str = "") -> None
    def step(self, step_name: str) -> StepContext  # Context manager
    def get_entries(self, min_level: int = 1) -> List[LogEntry]
**Rules:** - Uses structlog for structured logging with JSON Lines output - Logs stored in `workspace/logs/run_{id}/` - Use level 1 for phase start/end, level 2 for steps, level 3 for details - Logger instance created in services, passed to extraction/derivation functions #### `utils.py` **Goal:** Shared utility functions for file handling and data processing.
def read_file_with_encoding(file_path: Path) -> Optional[str]:
    """Auto-detect encoding (UTF-8, UTF-16, Latin-1 fallback)."""
**Rules:** - Pure functions only - no state - Used by extraction modules for file reading --- ### Extraction Modules (`modules/extraction/`) Extraction is organized by method: - **`structural/`** - File system based extraction (no LLM required) - **`llm/`** - LLM-based semantic extraction - **`ast/`** - AST-based extraction (future) All extraction modules follow the same pattern:
# Build a single node
def build_{node_type}_node(data: Dict) -> Dict[str, Any]

# Extract from files (structural) or via LLM (semantic)
def extract_{node_type}s(...) -> Dict[str, Any]:
    """
    Returns: {
        'nodes': [...],
        'edges': [...],
        'stats': {...},
        'errors': [...]
    }
    """
#### Structural Extraction (`structural/`) | Module | Node Type | Input | Purpose | |--------|-----------|-------|---------| | `repository.py` | Repository | repo metadata | Root node for the repository | | `directory.py` | Directory | file paths | Directory tree structure | | `file.py` | File | file paths + classification | File nodes with type info | #### LLM-Based Extraction (`llm/`) | Module | Node Type | Input | Purpose | |--------|-----------|-------|---------| | `type_definition.py` | TypeDefinition | source files | Classes, functions, interfaces | | `method.py` | Method | TypeDefinition nodes | Methods within type definitions | | `business_concept.py` | BusinessConcept | source files | Domain concepts and entities | | `technology.py` | Technology | config files | Frameworks, databases, infrastructure | | `external_dependency.py` | ExternalDependency | dependency files | Libraries and external integrations | | `test.py` | Test | test files | Test definitions and coverage | **LLM Extraction Pattern:**
# Each LLM module exports:
def build_user_prompt(file_content: str, file_path: str, example: str, ...) -> str  # Dynamic content
def build_extraction_prompt(...) -> str  # Legacy combined format for backward compatibility
def parse_llm_response(response: str) -> List[Dict]
{NODE_TYPE}_SCHEMA: Dict  # JSON schema for validation
{NODE_TYPE}_MULTI_SCHEMA: Dict  # Schema for multi-file batch extraction

# Single file extraction
def extract_{type}s(file_path, content, repo_name, llm_query_fn, config) -> Dict[str, Any]

# Multi-file batch extraction (for token efficiency)
def extract_{type}s_multi(files: List[Dict], repo_name, llm_query_fn, config) -> Dict[str, Any]
**Token Efficiency Patterns:** - **System/User Prompt Separation** (BusinessConcept multi-file extraction): the step's config instruction is the static system prompt (role, guidelines), sent verbatim; `build_user_prompt()` returns the dynamic file-specific content. This allows system prompts to be cached by providers. The other extractors still embed the instruction in a single prompt. - **Compact JSON**: Use `json.dumps(..., separators=(",", ":"))` for context data to minimize tokens. - **Multi-file Batching**: The `batch_size` config column (in `extraction_config` table) controls how many files are processed per LLM call. When `batch_size > 1`, the service uses `extract_{type}s_multi()` for batched extraction. **Rules for LLM modules:** - Module builds prompt, app.py calls LLM, module parses response - Never call LLM directly from module (purity) - Include JSON schema for response validation - Handle malformed LLM responses gracefully (return errors, don't raise) #### Edge Extraction (`edges.py`) Unified Tree-sitter based relationship extraction that parses each file once and extracts all edge types: | Edge Type | Direction | Purpose | |-----------|-----------|---------| | `IMPORTS` | File → File | Internal module imports | | `USES` | File → ExternalDependency | External package imports | | `CALLS` | Method → Method | Function/method calls | | `DECORATED_BY` | Method → Method | Decorator relationships | | `REFERENCES` | Method → TypeDefinition | Type annotation references |
from deriva.modules.extraction.edges import extract_edges_batch, EdgeType

# Extract all edge types (default)
result = extract_edges_batch(files, repo_name, repo_path)

# Extract specific edge types only
result = extract_edges_batch(
    files, repo_name, repo_path,
    edge_types={EdgeType.IMPORTS, EdgeType.CALLS}
)
**Note:** This is 4x more efficient than running separate extraction passes since each file is parsed only once. #### `input_sources.py` **Goal:** Parse and filter input source specifications for extraction steps.
def parse_input_sources(config: Dict) -> Dict[str, List[str]]
def filter_files_by_input_sources(files: List, specs: List[str]) -> List
def has_file_sources(config: Dict) -> bool
def has_node_sources(config: Dict) -> bool
**Rules:** - Supports file type specs (`source:python`, `config:*`) and node type specs (`TypeDefinition`, `File`) - Used by extraction orchestration to determine inputs for each step --- ### Derivation Modules (`modules/derivation/`) Derivation uses a hybrid approach combining graph algorithms with LLM: - **prep phase** - Graph enrichment (PageRank, Louvain communities, k-core analysis) - **generate phase** - LLM-based element derivation using graph metrics for filtering - **refine phase** - Cross-graph validation (duplicates, orphans, structural consistency) **Goal:** Transform Graph nodes into ArchiMate elements across Business, Application, and Technology layers. #### Base Classes (`element_base.py`) All derivation modules inherit from `HybridDerivation`, which combines pattern-based and graph-based filtering:
from deriva.modules.derivation.element_base import HybridDerivation

class ApplicationComponentDerivation(HybridDerivation):
    ELEMENT_TYPE = "ApplicationComponent"
    OUTBOUND_RULES = [...]  # Relationships FROM this element
    INBOUND_RULES = [...]   # Relationships TO this element

    # Optional: customize filtering behavior via class constants
    USE_COMMUNITY_ROOTS = True      # Prioritize community root nodes
    MIN_PAGERANK = 0.001            # Filter low-importance nodes
    COMMUNITY_ROOT_RATIO = 0.6      # 60% community roots in results
**Class Hierarchy:** - `ElementDerivationBase` - Abstract base with common `generate()` flow - `PatternBasedDerivation(ElementDerivationBase)` - Adds include/exclude pattern matching - `HybridFilteringMixin` - Adds graph-based filtering (PageRank, community roots) - `HybridDerivation(PatternBasedDerivation, HybridFilteringMixin)` - Recommended base class #### Utilities (`base.py`) Provides shared utilities for all derivation modules:
from deriva.modules.derivation import (
    Candidate,              # Dataclass for candidate nodes with enrichment data
    query_candidates,       # Run the graph query and return enriched candidates
    batch_candidates,       # Split candidates into batches for LLM
    build_derivation_prompt,    # Build LLM prompt for elements
    build_unified_relationship_prompt,  # Build LLM prompt for relationships
    parse_derivation_response,  # Parse LLM element response
    build_element,              # Build ArchiMate element from LLM output
    DERIVATION_SCHEMA,          # JSON schema for element derivation
    RELATIONSHIP_SCHEMA,        # JSON schema for relationship derivation
)
#### Element Modules Each element type has its own module with a `generate()` function: | Layer | Module | Element Type | Purpose | |-------|--------|--------------|---------| | **Business** | `business_actor.py` | BusinessActor | Roles, users, stakeholders | | | `business_event.py` | BusinessEvent | Business events and triggers | | | `business_function.py` | BusinessFunction | Business capabilities | | | `business_object.py` | BusinessObject | Data entities, domain objects | | | `business_process.py` | BusinessProcess | Activities, workflows | | **Application** | `application_component.py` | ApplicationComponent | Software modules, packages | | | `application_interface.py` | ApplicationInterface | APIs, interfaces | | | `application_service.py` | ApplicationService | Endpoints, services | | | `data_object.py` | DataObject | Files, data structures | | **Technology** | `device.py` | Device | Hardware, containers | | | `node.py` | Node | Compute infrastructure | | | `system_software.py` | SystemSoftware | Operating systems, runtimes | | | `technology_service.py` | TechnologyService | Infrastructure services | #### Module Pattern Each element module exports a `generate()` function:
def generate(
    graph_manager: GraphManager,
    archimate_manager: ArchimateManager,
    engine: Any,  # DuckDB connection for enrichment
    llm_query_fn: Callable,
    query: str,           # Graph query for candidates
    instruction: str,     # LLM derivation instructions
    example: str,         # Example output
    max_candidates: int,
    batch_size: int,
    temperature: float | None = None,
    max_tokens: int | None = None,
) -> GenerationResult:
    """Returns GenerationResult with success, elements_created, created_elements, errors."""
**Rules for derivation modules:** - Query candidates using config's graph query - Enrich candidates with graph metrics (PageRank, community, k-core) - Filter and batch candidates before sending to LLM - Persist elements via `archimate_manager.add_element()` - Configuration comes from DuckDB (instruction, example, query, etc.)
Configuration Pattern ### Configuration Principle: "Who Changes It" Deriva splits configuration by **ownership** - who needs to change it and why: | Category | Location | Owner | Examples | | --------------------- | ---------- | ---------- | -------------------------------------------- | | **Secrets & Keys** | `.env` | Ops/Deploy | API keys, passwords | | **Infrastructure** | `.env` | Ops/Deploy | Connection URIs, paths, provider URLs | | **Provider Settings** | `.env` | Ops/Deploy | LLM rate limits, timeouts, model definitions | | **Algorithm Tuning** | Database | Users | PageRank damping, Louvain resolution | | **Quality Thresholds**| Database | Users | Confidence thresholds, batch sizes | | **Pipeline Configs** | Database | Users | Extraction/derivation prompts, patterns | **Rationale:** - **`.env`** = deployment-specific, rarely changes, requires restart - **Database** = tunable during optimization, versioned for rollback, UI-editable ### Two Configuration Systems 1. **Environment variables (`.env`)** - Infrastructure and provider settings 2. **Database configs (DuckDB)** - Pipeline behavior and tuning parameters ### .env File (Adapter Configuration) - Lives in the Deriva home folder (`deriva/common/paths.py`): the repository root in a checkout, `~/.deriva` for an installed tool, or the folder in `DERIVA_HOME` - **Read in one place**: `deriva/common/settings.py` merges the `.env` file with the process environment (a variable set in the environment wins) and offers typed groups (`LlmSettings`, `GrafeoSettings`, `GraphSettings`, `ArchimateSettings`, `NlpSettings`, `RepositorySettings`); `tests/test_common/test_no_cwd_paths.py` fails on any other `os.getenv`, `os.environ` or `load_dotenv` in the three packages - Each field of a group has a default; an empty number or switch counts as unset (the `LLM_{NAME}_*` model blocks are read by name, `settings.model_configs()`) - Values **cached** by adapters on init (not re-read on every call) - `.env.example` is the template - **No YAML files** for configuration - **Never commit** .env to git (keep in .gitignore) ### Environment Variables - Naming: `{MANAGER}_{CATEGORY}_{SETTING}` (e.g., `GRAFEO_DB_DIR`) - Provide **sensible defaults** in code if env var missing - Comma-separated for lists (e.g., `ARCHIMATE_ELEMENT_TYPES=Component,Service`) - Boolean as string: `true`/`false` (case-insensitive) ### Pattern
# adapters/some_adapter/manager.py
from deriva.common.settings import GrafeoSettings

class SomeManager:
    def __init__(self):
        grafeo = GrafeoSettings()
        self.slow_query_ms = grafeo.slow_query_ms
        # Read all config in __init__
        # Cache values as instance variables
A new setting is a field in its group (or a new group with its own `env_prefix`); `settings.get(name, default)` reads a single value. ### Database Configs (Pipeline Configuration) Pipeline configs (extraction steps, derivation prompts) are stored in DuckDB with **version tracking**. **How versioning works:** - Each config has `id`, `version`, and `is_active` fields - When you update a config via UI or CLI, a **new version** is created - The old version is preserved with `is_active=false` for rollback - Only one version per config type is active at a time **Correct way to update configs:**
# Via CLI (creates new version)
deriva-cli config update extraction BusinessConcept \
  -i "New instruction..."

# View version history
deriva-cli config versions
**Never update configs by editing JSON and importing.** The `db_tool import` command is for **backup restoration only** - it overwrites the database including version history. This defeats the purpose of versioning and makes rollback impossible. **Shipped configuration (seed data).** The database itself (`deriva/adapters/database/sql.db`) is not in the repository. A fresh install creates it on first use from the schema, the migrations and the seed files in `deriva/adapters/database/data/`: the active config rows with their version numbers, the file types, the name patterns and the settings (no version history). An existing database is never touched. Before a release, refresh the seed files from the active configuration (the export reads the configuration database, so a fresh checkout needs it first: any `deriva-cli` command or the studio creates it):
uv run python -m deriva.adapters.database.db_tool export --active-only
### Prompts and LLM Calls Prompt text is configuration, not code: a run must be fully described by its config versions. - **Text that steers the LLM lives in the database.** Persona, instructions, rules, conventions, naming guidance, examples and thresholds told to the model belong in the step's `instruction`, `example` or `params`, changed with `deriva-cli config update`. The relationship prompt rules live in the `relationship` phase row (`GlobalRelationships`: `instruction` plus `params.min_confidence`; disabling it skips the LLM relationship pass). Per-candidate naming is switched on per element with `params.per_candidate` (`min_pool`, `rules`). - **Prompt builders hold only structure.** `build_*prompt*` functions in `modules/` contain section order and headings, serialisation of input data (candidates, elements, metamodel rules from `OUTBOUND_RULES`/`INBOUND_RULES`) and the output contract that matches the schema. Do not add rules, examples or domain words there. This is the target for every builder; some older builders (for example in `modules/extraction/method.py` and `modules/derivation/base.py`) still embed role text and are being migrated. - **Settings that change results** (cutoffs, mode switches) go in `params` or `system_settings`, not in class constants or literals. - **Where the text goes:** `instruction` and `example` for the main prompt, `params` (JSON, both extraction and derivation steps) for extra prompt texts and switches, e.g. `params.prompt` for the Technology headings. - **Every LLM call has a config row.** Services load the row and pass the text in; modules stay pure and only call the `llm_query_fn` they receive. - **Moving text between code and config must not change the prompt.** Pin the exact prompt with a test before the move, and check that a cached benchmark run hits the cache for every call and yields an identical model. Changing text is a result change: new config version, benchmark before and after. See [Benchmarking](https://docs.deriva.dev/benchmarks/) for running benchmarks and [Optimization](https://docs.deriva.dev/optimization/) for the recommended config optimization workflow.
Progress Tracking ### Overview The CLI provides visual progress tracking for pipeline and benchmark operations using the [Rich](https://rich.readthedocs.io/) library. This is implemented as an optional dependency with graceful fallback. ### Installation
# Install with progress support
uv sync --extra progress
### Features - **Progress bars** with ETA, elapsed time, and completion counts - **Spinner animations** for indeterminate operations - **Phase/step hierarchy** for multi-stage pipelines (extraction → derivation) - **Benchmark matrix display** showing current run context (repository, model, iteration) ### CLI Usage
# Default: progress bars shown (if Rich installed)
deriva-cli run all --repo my-repo

# Quiet mode: disable progress display
deriva-cli run all --repo my-repo -q

# Verbose mode: detailed text output (also disables progress bar)
deriva-cli run all --repo my-repo -v

# Benchmark with progress
deriva-cli benchmark run --repos my-repo --models my-model -n 3

# Benchmark quiet mode
deriva-cli benchmark run --repos my-repo --models my-model -n 3 -q
### Architecture Progress reporting uses a **callback protocol** defined in `common/types.py`:
class ProgressReporter(Protocol):
    """UI-agnostic progress reporting protocol."""
    def start_phase(self, name: str, total_steps: int) -> None: ...
    def start_step(self, name: str, total_items: int | None = None) -> None: ...
    def update(self, current: int | None = None, message: str = "") -> None: ...
    def advance(self, amount: int = 1) -> None: ...
    def complete_step(self, message: str = "") -> None: ...
    def complete_phase(self, message: str = "") -> None: ...
    def log(self, message: str, level: str = "info") -> None: ...

class BenchmarkProgressReporter(Protocol):
    """Extended protocol for benchmark operations."""
    # Includes all ProgressReporter methods plus:
    def start_benchmark(self, session_id: str, total_runs: int, ...) -> None: ...
    def start_run(self, run_number: int, repository: str, model: str, ...) -> None: ...
    def complete_run(self, status: str, stats: dict | None = None) -> None: ...
    def complete_benchmark(self, runs_completed: int, runs_failed: int, ...) -> None: ...
### Implementation Layers | Layer | File | Implementation | |-------|------|----------------| | **CLI** | `cli/progress.py` | Rich-based reporters with fallback to no-op | | **Studio** | `studio/runs.py` | Iterates the run generators and streams each update as a server-sent event | | **Services** | `extraction.py`, `derivation.py`, `benchmarking.py` | Accept optional `progress` parameter | The services layer is UI-agnostic: it accepts any object implementing the protocol. This allows: - CLI to use Rich progress bars with real-time updates - The studio to stream every update to the browser as it happens - Tests to use no-op reporters ### Adding Progress to New Services
from deriva.common.types import ProgressReporter

def my_service_function(
    ...,
    progress: ProgressReporter | None = None,
) -> dict:
    if progress:
        progress.start_phase("my_operation", total_steps=3)

    # Step 1
    if progress:
        progress.start_step("Processing items", total_items=len(items))
    for item in items:
        process(item)
        if progress:
            progress.advance()
    if progress:
        progress.complete_step("Done")

    # ... more steps ...

    if progress:
        progress.complete_phase("Operation complete")
    return result
Benchmarking System ### Overview The benchmarking system enables multi-model comparison for evaluating LLM performance on the ArchiMate derivation pipeline. **Key Components:** - `deriva/bench/benchmarking.py` (in `packages/deriva-dev/src/`) - `BenchmarkOrchestrator` for running benchmarks, `BenchmarkAnalyzer` for analysis - OCEL 2.0 event logging for process mining analysis ### Architecture
BenchmarkConfig
    ↓
BenchmarkOrchestrator
    ├── Clears graph/model between runs
    ├── Switches LLM provider per run
    ├── Executes pipeline stages
    ├── Logs events in OCEL format
    └── Tracks runs in DuckDB
    ↓
BenchmarkAnalyzer
    ├── Intra-model consistency (stability)
    ├── Inter-model consistency (agreement)
    └── Inconsistency localization (hotspots)
### OCEL Event Logging Benchmark sessions log their events with `OCELLog` (`deriva/common/ocel.py`). An event has an activity, a time, its objects grouped by type and its attributes:
log.create_event(
    "LLMQuery",
    objects={"BenchmarkRun": [run_id], "Model": [model], "Config": [step]},
    cache_hit=False, tokens_in=1234, latency_ms=850.0,
)
Each session writes, in `ocel/`: - `benchmark_events.jsonl`: the stream, appended after each run; the analyzers read it back (nested attributes such as run stats are kept) - `benchmark_events.json`: the OCEL 2.0 JSON layout (`objectTypes`, `eventTypes`, `objects`, `events` with qualified relationships, typed scalar attributes) for PM4Py, ProM and other tools - `cases.csv`, `cases.xes`: the flat case log (`OCELLog.case_events`, one case per run) for Disco **Object Types** (the qualifier of each relationship names the role): - `BenchmarkSession` (session), `BenchmarkRun` (run: repo × model × iteration; `session:extraction:repo` for a repository's shared extraction) - `Repository` (repository), `Model` (model: the benchmark model's config name), `Config` (step) - `GraphNode` (node) and `Edge` (edge) per extraction step, `Element` (element) per derivation step and run, `Relationship` (relationship) Steps report what they create through their step context (`add_object`, `add_edge`, `add_relationship`); extraction records the nodes a step wrote with `GraphManager.recording_nodes()`. Consistency compares the runs of one repository with one model (the session's `benchmark_runs`); the shared extraction is not a run. ### Adding New Metrics To add a new consistency metric: 1. Add method to `BenchmarkAnalyzer` in `deriva/bench/benchmarking.py` 2. Define result dataclass in the module 3. Integrate into `compute_full_analysis()` 4. Add database table in schema if persisting ### Configuration Benchmark models are configured via environment variables:
LLM_{NAME}_PROVIDER=azure|openai|anthropic|mistral|ollama|lmstudio
LLM_{NAME}_MODEL=model-identifier
LLM_{NAME}_URL=api-endpoint  # Optional
LLM_{NAME}_KEY=api-key      # Optional
The friendly name for CLI usage is derived from `{NAME}` with underscores converted to hyphens and lowercased (e.g., `AZURE_GPT4` → `azure-gpt4`).

Naming Conventions

Use consistent naming across all components:

  • snake_case everywhere (variables, functions, files)
  • Verb-based function names: add_*, get_*, build_*, validate_*
  • Predicate functions: is_*, has_*, can_*
  • Short names when obvious: x, y, i, j, n, m
Naming Details ### Variables & Functions
# snake_case everywhere
parse_input, build_graph, max_iterations

# Short names when obvious
x, y, i, j, n, m          # coordinates, indices, counts
xs, ys, vals              # plurals for collections

# Verb-based functions
add_node(), build_graph(), get_neighbors()

# Predicate functions
is_valid(), can_place(), has_cycle()
### Manager Methods | Prefix | Purpose | Example | |--------|---------|---------| | `add_*` | Create new entities | `add_node()`, `add_element()` | | `get_*` | Retrieve entities | `get_node()`, `get_elements()` | | `update_*` | Modify entities | `update_config()` | | `delete_*` | Remove entities | `delete_repository()` | | `query_*` | Complex queries | `query_by_type()` | | `clear_*` | Reset/clear | `clear_graph()`, `clear_cache()` | | `export_*` | Export data | `export_to_xml()` | ### Module Functions | Prefix | Purpose | Example | |--------|---------|---------| | `build_*` | Construct data structures | `build_nodes()`, `build_edges()` | | `classify_*` | Classification logic | `classify_files()` | | `detect_*` | Detection/discovery | `detect_modules()`, `detect_patterns()` | | `map_*` | Transform/map data | `map_modules_to_components()` | | `validate_*` | Validation logic | `validate_nodes()`, `validate_edges()` | | `run_*` | Pipeline steps | `run_classification_step()` | ### File Naming - **Adapters**: `adapters/{name}/manager.py` with `__init__.py` export - **Modules**: `modules/{name}.py` with clear purpose - **Tests**: `tests/test_{name}.py` mirroring source structure ### Imports
# stdlib first
import os
from pathlib import Path
from dataclasses import dataclass
from typing import Dict, List

# third-party
from dotenv import load_dotenv
import polars as pl

# local
from modules.classification import classify_files
Group: stdlib, then third-party, then local. Blank line between groups.

Studio

The studio is the local web UI: packages/deriva-studio/src/deriva/studio/ (FastAPI backend, a top layer that imports deriva.services only, enforced by its ruff.toml) and studio/ at the repo root (React 19, Vite, TypeScript, CodeMirror 6, own CSS).

Running it

uv run deriva                        # API + built front end on http://127.0.0.1:8765
cd studio && npm run dev             # front-end development; Vite forwards /api, /grafeo, /widgets to 8765
                                     # open http://localhost:5173/api/auth?token=<the token deriva printed>
DERIVA_STUDIO_API=http://127.0.0.1:9000 npm run dev   # the same for a studio started with --port 9000
npm test && npm run lint && npm run typecheck
npm run build                        # writes packages/deriva-studio/src/deriva/studio/static/ (git-ignored, shipped in the wheel)

Backend rules

  • One PipelineSession per process, behind a lock (SessionProvider); request handlers and the run worker take it (the worker once per pipeline step). A database held by another process answers 503 with the holder's PID.
  • Step config edits go through the versioned service functions only (save_extraction_config, save_derivation_config), never in-place updates. Model configs are not versioned: they live in .env (save_model_config).
  • Free-form graph queries (the widget's query bar) run read-only: a write guard plus a grafeo transaction that is always rolled back.
  • Tests inject a fake session (tests/test_studio/conftest.py); they never open the real databases.

Widgets

The studio mounts anywidget-graph and anywidget-archimate without Jupyter, through studio/src/widgets/host.ts (the model API a widget's front-end module expects). The backend serves each widget's module from the installed Python package (/widgets/<name>/index.js). anywidget-graph runs in grafeo server mode against /grafeo (health, query, schema), answered from the embedded databases.

Testing

Tests should mirror the source structure. When adding tests, use this organization:

tests/
├── test_adapters/   # Adapter integration tests
│   ├── test_database.py
│   ├── test_graph.py
│   └── ...
├── test_modules/    # Module unit tests
│   ├── extraction/
│   ├── derivation/
│   └── ...
└── test_services/   # Service tests

Running Tests

# Run all tests
uv run pytest

# Run specific test file
uv run pytest tests/test_modules/extraction/test_classification.py -v

# Run with coverage
uv run pytest --cov=.

Module Tests (Pure Functions)

# tests/test_modules/extraction/test_classification.py
def test_classify_files():
    files = [{'path': 'deriva/main.py', 'content': '...'}]
    registry = {'py': 'python'}

    result = classification.classify_files(files, registry)

    assert result[0]['type'] == 'python'

Module tests should be unit tests only - no external dependencies, mock data only.

Adapter Tests (Integration)

# tests/test_adapters/test_graph.py
def test_add_and_get_node():
    manager = GraphManager()
    node = {'id': 'test1', 'type': 'Repository'}

    manager.add_node(node)
    retrieved = manager.get_node('test1')

    assert retrieved['id'] == 'test1'

Adapter tests may require external services (DuckDB) - use fixtures for setup/teardown.


Anti-Patterns to Avoid

Anti-Pattern Why It's Bad Do This Instead
Importing adapters in app.py or cli.py Violates architectural boundaries Use PipelineSession from services
Business logic in app.py or cli.py Hard to test, violates separation Move logic to modules
Adapters importing adapters Creates coupling Coordinate via services
Modules with I/O Breaks purity, hard to test Pass data as parameters
Direct .env access in modules Violates purity Receive config as parameters
YAML configuration files Multiple config sources Use .env for all config
Creating adapters in individual cells Multiple instances, connection issues Create PipelineSession once

This project includes several specialized documentation files:

Document Description
README.md Project overview; install and usage are on docs.deriva.dev
Architecture Layers, packages, the home folder and the settings layer
Benchmarking User guide for running benchmarks and analyzing consistency
Optimization Prompt engineering and the config optimization workflow
ArchiMate ArchiMate elements, relationships and metamodel rules
Changelog Version history and release notes
.github/SECURITY.md Security policy and vulnerability reporting

Component Documentation

Component README
CLI deriva/cli/README.md
LLM Adapter deriva/adapters/llm/README.md
Graph Adapter deriva/adapters/graph/README.md
Database Adapter deriva/adapters/database/README.md
Grafeo Adapter deriva/adapters/grafeo/README.md
ArchiMate Adapter deriva/adapters/archimate/README.md
Repository Adapter deriva/adapters/repository/README.md
Studio Studio

Philosophy

  1. Working > perfect - ship it, iterate
  2. Readable > clever - clarity over cleverness
  3. Simple > general - solve today's problem
  4. Pure > stateful - isolate side effects to adapters
model.maximize(readability + maintainability)
model.add(complexity <= necessary)