Home · Developers · Ebook

Technical dossier · rev 2026-11-10

The Nova Codex.Collected engineering records

48 field records pulled straight from the Nova Coder engineering wiki, the same source the maintainers read, bound into a single dossier. Architecture, APIs, agents, workspace, security, operations. Open a record and page through.

records 48parts 8 origin wiki/clearance public
REC 01 / 48
PART I · FOUNDATIONS

Record 01 / 48 // Part I · Foundations

Architecture Overview

Services, event bus and DI container · source wiki/architecture-overview.md

Nova Coder is built as a modular, event-driven AI software engineering platform. Every subsystem is a replaceable service with a common lifecycle, communicating through a central event bus and resolving dependencies through a dependency injection container.

Design Principles

  1. Everything is a Service: Config, logging, workspace, AI, tools, agents, and memory all implement the same NovaService lifecycle.
  2. Everything Emits Events: Services do not call each other directly. They publish events on the EventBus with optional filtering and routing.
  3. Everything Uses Dependency Injection: No global state. Services are registered in and resolved from the Container.
  4. Every Provider is Replaceable: AI providers, tools, agents, and plugins share common interfaces.
  5. Build in Phases: The platform grows incrementally from a stable kernel.
  6. Services Can Be Distributed: Service mesh integration enables traffic management, load balancing, and health checks for distributed deployment.
  7. State Can Be Event-Sourced: Event sourcing system provides event replay, state reconstruction, and snapshot support for auditability and debugging.

High-Level Architecture

                        ┌─────────────────────────────────────┐
                        │         User Interfaces             │
                        │  CLI │ Desktop │ Web │ IDE │ API    │
                        └─────────────┬───────────────────────┘
                                      │
                                      ▼
                        ┌─────────────────────────────────────┐
                        │      Nova Core Orchestrator         │
                        │         (Application)               │
                        └─────────────┬───────────────────────┘
                                      │
          ┌───────────────────────────┼───────────────────────────┐
          │                           │                           │
          ▼                           ▼                           ▼
   ┌─────────────┐            ┌─────────────┐            ┌─────────────┐
   │ AI Engine   │            │ Agent Engine│            │ Tool Engine │
   │             │            │             │            │             │
   │ Provider    │            │ Manager     │            │ Registry    │
   │ Router      │            │ Planner     │            │ Filesystem  │
   │ Prompts     │            │ Coder       │            │ Git         │
   │ Context     │            │ Reviewer    │            │ Shell       │
   └─────────────┘            │ Tester      │            └─────────────┘
                              └─────────────┘
                                      │
                                      ▼
                        ┌─────────────────────────────────────┐
                        │   Workspace Intelligence Engine     │
                        │                                     │
                        │  AST Parser │ Symbol Graph │ Vector │
                        │  Knowledge Graph │ Indexer          │
                        └─────────────────────────────────────┘

Data Flow Example

When a user asks "Add JWT authentication":

  1. CLI receives the prompt and publishes PromptReceived.
  2. Planner analyzes the request and publishes a TaskGraph.
  3. Workspace is queried for the authentication layer.
  4. Architect designs the change plan.
  5. Coder generates the code.
  6. Reviewer checks quality.
  7. Tester runs tests.
  8. Tool Engine applies changes via filesystem and git tools.
  9. CLI displays the result.

Service Architecture

All services share a common lifecycle:

class NovaService:
    def initialize(self) -> None
    def start(self) -> None
    def stop(self) -> None
    def dispose(self) -> None
    def health(self) -> ServiceHealth

The kernel manages startup and shutdown order deterministically.

Directory Layout

novacoder/
├── kernel/        # Lifecycle, DI, events, registry, health
├── config/        # Settings and validation
├── logging/       # Structured logging
├── ai/            # AI providers, routing, prompts
├── agents/        # Specialist agents
├── planner/       # Planning engine
├── tools/         # Tool framework
├── workspace/     # Indexing and code understanding
├── memory/        # Memory layers
├── plugins/       # Plugin system
├── cli/           # Command-line interface
└── app.py         # Application orchestrator

Roadmap

  • v0.0.1: Bootstrap, kernel, config, logging, CLI, basic AI, tools, agents, memory
  • v0.0.2: Workspace Intelligence, scanning, AST, symbols, dependency graphs
  • v0.0.3: AI Runtime, multi-provider support, streaming, model routing
  • v0.0.4: Planner, task decomposition and task graphs
  • v0.0.5: Tool Framework, full tool execution and permissions
  • v0.0.6: Agent Runtime, multi-agent orchestration
  • v0.0.7: Memory, persistent memory layers
  • v0.1.0: First public release

Development Instructions

Working with the Architecture

When modifying or extending Nova Coder, follow these rules to preserve the architecture:

  1. Every new capability is a service, implement NovaService and register it in the kernel.
  2. Services do not call each other directly, use the event bus for notifications and the container for dependency resolution.
  3. No global state, store subsystem state in services and access them through the container or registry.
  4. Every interface is replaceable, providers, tools, agents, and plugins share common base classes.
  5. One directory per responsibility, do not mix unrelated logic into the kernel or other modules.

Adding a New Major Subsystem

  1. Create a new directory under novacoder/.
  2. Implement a NovaService subclass in service.py.
  3. Export public classes from __init__.py.
  4. Add the service to NovaApplication.SERVICE_ORDER in novacoder/app.py.
  5. Add the subsystem to the directory layout diagram in this page.
  6. Add a dedicated wiki page in wiki/<subsystem>.md.
  7. Add unit and integration tests in tests/.

Modifying the Data Flow

When adding a new feature, trace how it fits into the flow:

User Request → Intent → Plan → Knowledge → Agents → Tools → Validation → Review

Publish events at each step so plugins and other services can react.

Version Planning

Use the roadmap to decide where a feature belongs. Avoid introducing advanced features before the kernel and runtime are stable.

Record 02 / 48 // Part I · Foundations

Application

The application bootstrap and lifecycle · source wiki/application.md

The Application class is the top-level orchestrator of Nova Coder. It boots the kernel, wires every subsystem, and provides a clean startup and shutdown sequence.

NovaApplication

NovaApplication extends the base Application from the kernel and registers all Nova Coder services in the correct order.

from novacoder.app import create_app

app = create_app(project_path="/path/to/project")
results = app.start()

print(app.health())
app.stop()

Startup Order

config
  ↓
logging
  ↓
workspace
  ↓
memory
  ↓
ai
  ↓
runtime
  ↓
permissions
  ↓
tools
  ↓
agents
  ↓
plugins

Services are initialized in this order and stopped in reverse order.

Wiring Services

NovaApplication creates service instances and registers them in both the Registry and the Container:

config_service = ConfigService(overrides)
config_service.initialize()

registry.register_instance("config", config_service)
container.register_instance("config", config_service)
container.register_instance(ConfigService, config_service)

Each service is also registered by its class so code can resolve either by name or by type. For example, RuntimeService can be resolved by name "runtime" or by class RuntimeService.

Lifecycle

app = create_app()
app.initialize()   # Build kernel, wire services
app.start()          # Initialize and start all services
app.run()            # Start and keep alive
app.stop()           # Stop and dispose all services

Health and Status

report = app.health()
print(report.status)  # healthy, degraded, unhealthy
print(report.services)

status = app.status()
print(status["services"])

Configuration Overrides

app = create_app(
    project_path="/path/to/project",
    overrides={
        "model": {"provider": "openai"},
        "workspace": {"index_on_start": False},
    }
)

Boot Sequence

  1. Application.initialize() creates the kernel via Bootstrap.
  2. Bootstrap.build() returns the container, registry, event bus, scheduler, health monitor, and lifecycle manager.
  3. NovaApplication registers each service in the registry and container.
  4. LifecycleManager.set_startup_order() is configured.
  5. Application.start() calls initialize_all() and start_all() on the lifecycle manager.
  6. If successful, the scheduler is started and ApplicationStarted is published.

Error Handling

If a service fails during startup, the ApplicationStartFailed event is published and app.start() returns the failing results. The application will not be marked as running.

Development Instructions

Adding a Service to the Application

  1. Create a service class in its subsystem (e.g., novacoder/my/service.py).
  2. In NovaApplication.initialize() in novacoder/app.py, instantiate the service using the loaded config.
  3. Register it by name and by class in both the registry and container:
    self._registry.register_instance("my", my_service)
    self._container.register_instance(MyService, my_service)
    
  4. Add the service name to NovaApplication.SERVICE_ORDER.
  5. Add an integration test in tests/test_app.py.
  6. Update the relevant subsystem wiki page and this page.

Testing the Full Lifecycle

from novacoder.app import create_app

app = create_app()
results = app.start()
for name, (ok, error) in results.items():
    assert ok, f"{name}: {error}"
assert app.is_running()
report = app.health()
assert report.status.value == "healthy"
app.stop()

Changing the Startup Order

Edit NovaApplication.SERVICE_ORDER in novacoder/app.py. Ensure dependencies are initialized before services that need them.

Record 03 / 48 // Part I · Foundations

Configuration

Layered config: defaults + user yaml · source wiki/configuration.md

Nova Coder uses a layered, validated configuration system built on Pydantic. Configuration can come from YAML files, environment variables, or programmatic overrides.

Configuration Layers

Layers are loaded in order, with later layers overriding earlier ones:

  1. defaults.yaml, built-in defaults
  2. system.yaml, machine-wide settings
  3. user.yaml, user preferences
  4. workspace.yaml, project-specific settings
  5. Environment variables (NOVACODER_*)
  6. Programmatic overrides passed to create_app()

Default Configuration

The default configuration lives in @config/defaults.yaml:

model:
  provider: ollama
  model: deepseek-coder
  temperature: 0.7

workspace:
  index_on_start: true
  exclude_patterns:
    - .git
    - __pycache__

memory:
  database: sqlite

tools:
  shell: false
  git: true
  python: true
  docker: false
  require_approval: true

agents:
  planner: true
  coder: true
  reviewer: true

Pydantic Models

Configuration is validated by these models:

  • AppConfig, top-level configuration
  • ModelConfig, AI provider settings
  • WorkspaceConfig, project scanning settings
  • MemoryConfig, memory backend settings
  • ToolsConfig, tool permissions
  • AgentsConfig, enabled agents
  • LoggingConfig, logging settings

Loading Configuration

from novacoder.config import ConfigLoader

loader = ConfigLoader()
config = loader.load()

print(config.model.provider)
print(config.workspace.index_on_start)

Environment Variables

Pydantic Settings reads environment variables with the NOVACODER_ prefix and __ as a nested delimiter:

export NOVACODER_MODEL__PROVIDER=openai
export NOVACODER_MODEL__API_KEY=sk-...

Web UI Configuration Editor

The React dashboard exposes the full AppConfig through a structured form in addition to the JSON editor:

  • Component: novacoder/web/react/src/components/ConfigForm.tsx
  • Page: novacoder/web/react/src/pages/Settings.tsx
  • Endpoint: PUT /api/system/config with { updates: draft }

ConfigForm recursively renders all top-level AppConfig sections as collapsible cards with type-aware controls for string, number, boolean, primitive array, and nested object values. It falls back to a JSON textarea for non-primitive arrays or unsupported shapes. This makes configuration editing safer and more discoverable than editing raw JSON.

Path Configuration Environment Variables

Nova Coder supports comprehensive path configuration through environment variables, allowing you to customize where the application stores its data and configuration files.

Data Directory Configuration:

# Set the main application data directory
export NOVACODER_DATA_DIR=/custom/path/novacoder

Memory Database Path:

# Set the memory database path explicitly
export NOVACODER_MEMORY__DB_PATH=/custom/path/memory.db

Default Paths: If no environment variables are set, Nova Coder uses the following default paths:

  • Data directory: ~/.config/novacoder/
  • Memory database: ~/.config/novacoder/memory.db

Example Usage:

# Use a custom data directory for development
NOVACODER_DATA_DIR=/tmp/novacoder_dev novacoder serve

# Use a custom memory database for testing
NOVACODER_MEMORY__DB_PATH=/tmp/test_memory.db novacoder doctor

Path Configuration in Code:

from novacoder.config.settings import AppConfig
from novacoder.memory.memory import MemoryStore

# Environment variables are automatically respected
config = AppConfig()
print(f"Data dir: {config.data_dir}")  # Uses NOVACODER_DATA_DIR if set

# Memory store also respects environment variables
memory_store = MemoryStore()  # Uses NOVACODER_MEMORY__DB_PATH if set

Programmatic Overrides

from novacoder.app import create_app

app = create_app(overrides={
    "model": {"provider": "openai"},
    "workspace": {"index_on_start": False},
    "tools": {"shell": True, "require_approval": False},
})

Workspace Settings

The workspace section controls project scanning and indexing:

  • project_path, path to the project root (null defaults to the current working directory).
  • index_on_start, when true, WorkspaceService scans the project during application startup.
  • incremental, when true, subsequent scans only re-read files whose hashes have changed.
  • exclude_patterns, glob patterns for directories and files to skip. Supports */?/[seq] via fnmatch, and ** for recursive matching.
  • max_file_size, files larger than this many bytes are skipped.
workspace:
  project_path: null
  index_on_start: true
  incremental: true
  exclude_patterns:
    - .git
    - __pycache__
    - node_modules
    - "*.pyc"
    - "test_*.py"
    - "**/*.log"
  max_file_size: 1000000

Tools Permissions

The tools section controls both tool registration and safety gates:

  • shell, enables run_shell (requires run_shell_commands permission).
  • git, enables the git tool suite (requires access_git permission).
  • python, enables run_python (requires run_shell_commands permission).
  • docker, enables run_docker (requires run_shell_commands and network_access permissions).
  • db, enables query_database (requires database_access permission).
  • ssh, enables ssh_command (requires ssh_access permission).
  • k8s, enables kubectl (requires kubernetes_access permission).
  • require_approval, when true, every tool with declared permissions is gated by an approval callback before run() is called.

PermissionsService builds a PermissionChecker from these flags and injects it into ToolService at boot time.

ConfigService

ConfigService is a kernel service that loads configuration during boot:

from novacoder.config.service import ConfigService

service = ConfigService(overrides={})
service.initialize()
config = service.config

Configuration by Key

provider = config_service.get("model.provider", default="ollama")

Configuration Validation

The ConfigService includes comprehensive settings validation to prevent invalid configurations from causing runtime errors:

from novacoder.config.service import ConfigService

service = ConfigService()
service.initialize()

# Validate settings
settings = {
    "api": {"base_url": "http://localhost:8000", "timeout": 30},
    "ai": {"model": "gpt-4", "temperature": 0.7, "max_tokens": 2048},
    "workspace": {"index_on_start": True, "max_file_size": 1048576},
    "memory": {"max_entries": 1000, "ttl": 3600}
}

is_valid, errors = service.validate_settings(settings)
if not is_valid:
    for error in errors:
        print(f"Validation error: {error}")

Validation Rules:

  • API Settings:
    • base_url must be a string
    • timeout must be a positive number
  • AI Settings:
    • model must be a string
    • temperature must be a number between 0 and 2
    • max_tokens must be a positive integer
  • Workspace Settings:
    • index_on_start must be a boolean
    • max_file_size must be a positive integer
  • Memory Settings:
    • max_entries must be a positive integer
    • ttl must be a positive integer

Configuration Import/Export

The ConfigService supports importing and exporting configuration to YAML files:

from novacoder.config.service import ConfigService
from pathlib import Path

service = ConfigService()
service.initialize()

# Export configuration
export_path = Path("/tmp/novacoder_config.yaml")
service.export_settings(export_path, include_profiles=True)

# Import configuration (replace existing)
success, errors = service.import_settings(export_path, merge=False)
if not success:
    print(f"Import failed: {errors}")

# Import configuration (merge with existing)
success, errors = service.import_settings(export_path, merge=True)
if not success:
    print(f"Import failed: {errors}")

Export Features:

  • Exports main configuration and custom configuration
  • Option to include profiles in the export
  • Saves to YAML format for easy editing
  • Creates parent directories if they don't exist

Import Features:

  • Validates imported settings before applying
  • Supports both replace and merge modes
  • Deep merge for nested configuration structures
  • Returns success status and error messages

Configuration Profiles

The ConfigService supports multiple configuration profiles for different use cases:

from novacoder.config.service import ConfigService

service = ConfigService()
service.initialize()

# Create a new profile
service.create_profile("development", "Development environment configuration")

# List available profiles
profiles = service.list_profiles()
for name, description in profiles.items():
    print(f"{name}: {description}")

# Load a profile
success, error = service.load_profile("development")
if not success:
    print(f"Failed to load profile: {error}")

# Delete a profile
deleted = service.delete_profile("development")
if deleted:
    print("Profile deleted successfully")

Profile Features:

  • Create profiles with descriptions
  • Save current configuration as a profile
  • Load profiles to switch configurations
  • List all available profiles
  • Delete profiles when no longer needed
  • Profiles stored in custom_config.json under the profiles key

Profile Use Cases:

  • Development Profile: Local development settings
  • Production Profile: Production environment settings
  • Testing Profile: Testing environment settings
  • Team Profile: Shared team configuration

Development Instructions

Adding a New Configuration Section

  1. Define a Pydantic model in novacoder/config/settings.py.
  2. Add it as a field on AppConfig with a default factory.
  3. Add sensible defaults to config/defaults.yaml.
  4. Update this wiki page and any services that consume the new section.

Example: Adding a New Section

from pydantic import BaseModel

class CacheConfig(BaseModel):
    enabled: bool = True
    ttl: int = 3600

class AppConfig(BaseSettings):
    cache: CacheConfig = Field(default_factory=CacheConfig)

Testing Configuration

from novacoder.config import ConfigLoader

loader = ConfigLoader()
config = loader.load({"cache": {"ttl": 60}})
assert config.cache.ttl == 60

Validation

Pydantic will raise ValidationError for invalid types. Wrap loading in ConfigLoader.load() to convert it into a ValueError with a clear message.

Best Practices

  • Store secrets in environment variables, not YAML files.
  • Keep project-specific settings in workspace.yaml.
  • Use overrides in tests to avoid side effects.
  • Validate any custom config fields by extending the Pydantic models.

Web API Configuration UI

Nova Coder provides a web-based configuration interface that allows users to manage API and model settings through the browser.

Configuration Page

The web interface includes a dedicated Configuration page accessible from the sidebar with the following features:

  • API Configuration Form: Configure API host, port, and optional authentication token
  • Model Configuration Form: Configure AI provider, model name, and custom base URL
  • Connection Testing: Test API connectivity with current settings before saving
  • Real-time Updates: Configuration changes take effect immediately after saving
  • Full Configuration View: Read-only display of all configuration sections

API Configuration Endpoints

POST /api/config/update

Update configuration settings for a specific section:

curl -X POST http://localhost:8000/api/config/update \
  -H "Content-Type: application/json" \
  -d '{
    "section": "api",
    "updates": {
      "host": "0.0.0.0",
      "port": 8000,
      "token": "optional_token"
    }
  }'

Request Model:

  • section: Configuration section to update (api, model, workspace, memory, tools, agents, plugins, logging, security)
  • updates: Dictionary of key-value pairs to update in the specified section

Response:

{
  "success": true,
  "message": "Configuration section 'api' updated successfully",
  "updated": {
    "host": "0.0.0.0",
    "port": 8000,
    "token": "optional_token"
  }
}

Configuration Validation

The web interface includes comprehensive client-side validation:

  • API Configuration:
    • Host: Required field, must be a valid hostname or IP address
    • Port: Required field, must be between 1-65535
    • Token: Optional field, if provided must be 16-256 characters with alphanumeric characters, hyphens, and underscores only
  • Model Configuration:
    • Provider: Required field, must be a valid AI provider name
    • Model: Required field, must be a valid model identifier
    • Base URL: Optional field, if provided must be a valid URL
  • Connection Testing: Validates API connectivity before saving changes
  • Error Display: Validation errors are displayed inline with the corresponding form fields

Configuration Import/Export

The web interface provides configuration backup and restore functionality:

Export Configuration

Export the current configuration to a JSON file for backup:

// Client-side export function
async function exportConfiguration(){
  const cfg=await api('/api/config');
  const configJson=JSON.stringify(cfg,null,2);
  const blob=new Blob([configJson],{type:'application/json'});
  const url=URL.createObjectURL(blob);
  const a=document.createElement('a');
  a.href=url;
  a.download=`novacoder-config-${new Date().toISOString().split('T')[0]}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

Features:

  • Exports all configuration sections to a single JSON file
  • Filename includes date for easy identification
  • Pretty-printed JSON for readability
  • Automatic browser download

Import Configuration

Import configuration from a JSON file:

// Client-side import function
async function importConfiguration(){
  const fileInput=$('config-import-file');
  if(!fileInput.files||!fileInput.files[0]){
    return;
  }
  const file=fileInput.files[0];
  const reader=new FileReader();
  reader.onload=async(e)=>{
    try{
      const config=JSON.parse(e.target.result);
      if(!confirm('This will overwrite your current configuration. Are you sure?'))return;
      const validSections=['api','model','workspace','memory','tools','agents','plugins','logging','security'];
      let allSuccess=true;
      for(const section of validSections){
        if(config[section]){
          const res=await apiWithRetry('/api/config/update',{
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify({section,updates:config[section]})
          });
          if(!res.success){
            allSuccess=false;
            showError(`Import ${section}`,new Error(res.error||'Failed to import section'));
          }
        }
      }
      if(allSuccess){
        alert('Configuration imported successfully');
        renderConfig();
      }else{
        alert('Configuration imported with some errors. Check console for details.');
      }
    }catch(err){
      showError('Import Configuration',err);
    }finally{
      fileInput.value='';
    }
  };
  reader.readAsText(file);
}

Features:

  • Imports configuration from JSON file
  • Section-based import for granular control
  • User confirmation before overwriting existing configuration
  • Error handling for each section
  • Success/failure feedback
  • Automatic UI refresh after successful import

Valid Configuration Sections:

  • api - API host, port, and token settings
  • model - AI provider, model, and base URL settings
  • workspace - Project scanning and indexing settings
  • memory - Memory backend settings
  • tools - Tool permissions and settings
  • agents - Agent configuration
  • plugins - Plugin settings
  • logging - Logging configuration
  • security - Security settings

Usage:

  1. Click "Export Configuration" to download current configuration as JSON
  2. Store the exported file as a backup
  3. To restore, click "Import Configuration" and select the JSON file
  4. Confirm the import operation
  5. Configuration is applied section by section
  6. UI refreshes to reflect the imported configuration

Configuration Persistence

Configuration changes made through the web interface are saved to user.yaml in the configuration directory (~/.config/novacoder/ by default). This ensures that changes persist across application restarts.

Usage

  1. Navigate to the Configuration page in the web interface
  2. Fill in the desired configuration values
  3. Click "Test Connection" (for API settings) to verify connectivity
  4. Click "Save Configuration" to apply changes
  5. The configuration is immediately updated and persisted

Record 04 / 48 // Part I · Foundations

Deployment

Serving, processes and operations · source wiki/deployment.md

Nova Coder can be deployed in various environments including development, staging, and production. This guide covers deployment options, HTTPS configuration, build management, and best practices.

Deployment Options

Development Deployment

For local development, use the built-in development server:

novacoder serve --port 8000

Production Deployment

For production deployment, Nova Coder should be deployed behind a proper web server with SSL/TLS termination.

Reference deployment: novacoder.codexlabsai.com

The live estate runs one hostname with multiple surfaces, fronted by Caddy (deploy/edge/Caddyfile, symlinked ~/websites/Caddyfile) on :8081 behind cloudflared:

Path Backend Purpose
/ novacoder/web/site/ static files Public Quantum marketing site (no build step; file_server)
/app/* 127.0.0.1:8000 (prefix stripped) IDE portal — the React SPA (vite base=/app/) + full API
/demo/* 127.0.0.1:8001 (prefix stripped) Public demo portal — a SECOND isolated instance (scripts/serve_demo.sh, own NOVACODER_DATA_DIR, empty demo-workspace, demo.enabled → role="demo" sessions: browsing + budgeted plain chat, no tools/writes). /demo/ws* is 403'd at the edge
/portal/ + /portal-api/* site static + asksybil portal proxy Customer portal (sign-in, overview, billing)
/pay/ site static + /apex-pay/v1/checkout/* → payments.codexlabsai.com Hosted checkout shim
/sybil/assistant/* asksybil assistant proxy ASK SYBIL site assistant used by site/assets/assistant*.js, IP-bucketed guests
/api/*, /graphql, /ws/*, /docs, /redoc, /openapi.json, /metrics, /static/* 127.0.0.1:8000 unchanged API surface

Both instances are launched by scripts/serve.sh (idempotent; it also invokes serve_demo.sh) on 127.0.0.1 and supervised by scripts/watchdog.sh via crontab. handle_errors serves site/404.html for site-path misses only; backend JSON 404s pass through. Caddy's admin API is unreachable on this host — config changes need kill $(cat ~/websites/.run/caddy.pid) plus watchdog respawn.

HTTPS Configuration

HTTPS enforcement is a deployment concern, not an application-level concern. The Nova Coder API server can be deployed with HTTPS using several methods:

Option 1: Reverse Proxy with SSL/TLS Termination

Nginx Configuration:

server {
    listen 443 ssl http2;
    server_name novacoder.example.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Apache Configuration:

<VirtualHost *:443>
    ServerName novacoder.example.com
    
    SSLEngine on
    SSLCertificateFile /path/to/cert.pem
    SSLCertificateKeyFile /path/to/key.pem
    
    ProxyPreserveHost On
    ProxyPass / http://localhost:8000/
    ProxyPassReverse / http://localhost:8000/
</VirtualHost>

Option 2: Uvicorn with SSL Certificates

uvicorn novacoder.api.app:app \
    --host 0.0.0.0 \
    --port 8000 \
    --ssl-keyfile /path/to/key.pem \
    --ssl-certfile /path/to/cert.pem

Option 3: Cloud Services with Built-in HTTPS

AWS Application Load Balancer:

  • Configure ALB with SSL/TLS certificates
  • Forward HTTP traffic to HTTPS
  • Point ALB to Nova Coder instances

Cloudflare:

  • Use Cloudflare as CDN/SSL proxy
  • Configure SSL/TLS mode in Cloudflare dashboard
  • Point DNS to Cloudflare, which forwards to Nova Coder

Heroku:

  • Heroku automatically provides HTTPS
  • Deploy using the Heroku CLI

Environment Variables for Production

Set appropriate environment variables for production deployment:

# API Configuration
export NOVACODER_API__TOKEN=your-secure-token
export NOVACODER_API__HOST=0.0.0.0
export NOVACODER_API__PORT=8000

# Data Directory
export NOVACODER_DATA_DIR=/var/lib/novacoder

# Memory Database
export NOVACODER_MEMORY__DB_PATH=/var/lib/novacoder/memory.db

# AI Provider Configuration
export NOVACODER_MODEL__PROVIDER=openai
export NOVACODER_MODEL__API_KEY=your-api-key

# Logging
export NOVACODER_LOGGING__LEVEL=INFO
export NOVACODER_LOGGING__FILE_PATH=/var/log/novacoder/novacoder.log

Docker Deployment

Dockerfile

FROM python:3.13-slim

WORKDIR /app
COPY pyproject.toml .
RUN pip install --no-cache-dir -e .[api]

COPY novacoder/ ./novacoder/

EXPOSE 8000
CMD ["uvicorn", "novacoder.api.app:app", "--host", "0.0.0.0", "--port", "8000"]

Docker Compose

version: '3.8'
services:
  novacoder:
    build: .
    ports:
      - "8000:8000"
    environment:
      - NOVACODER_API__TOKEN=${API_TOKEN}
      - NOVACODER_DATA_DIR=/data
    volumes:
      - novacoder_data:/data
    restart: unless-stopped

volumes:
  novacoder_data:

Docker with HTTPS

version: '3.8'
services:
  novacoder:
    build: .
    ports:
      - "8000:8000"
    environment:
      - NOVACODER_API__TOKEN=${API_TOKEN}
      - NOVACODER_DATA_DIR=/data
    volumes:
      - novacoder_data:/data
      - ./certs:/certs:ro
    command: >
      uvicorn novacoder.api.app:app
      --host 0.0.0.0
      --port 8000
      --ssl-keyfile /certs/key.pem
      --ssl-certfile /certs/cert.pem
    restart: unless-stopped

volumes:
  novacoder_data:

Systemd Service

Create a systemd service file for Nova Coder:

[Unit]
Description=Nova Coder AI Engineering Platform
After=network.target

[Service]
Type=simple
User=novacoder
WorkingDirectory=/opt/novacoder
Environment="NOVACODER_DATA_DIR=/var/lib/novacoder"
Environment="NOVACODER_API__TOKEN=your-secure-token"
ExecStart=/usr/bin/python -m novacoder serve --port 8000
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Enable and start the service:

sudo systemctl enable novacoder
sudo systemctl start novacoder

Security Considerations

API Token Security

  • Use strong, randomly generated API tokens
  • Store tokens in environment variables, not in code
  • Rotate tokens regularly
  • Use HTTP-only cookies for authentication when possible

Network Security

  • Use reverse proxy for SSL/TLS termination
  • Configure firewall rules to restrict access
  • Use internal network for service-to-service communication
  • Enable rate limiting to prevent abuse

Data Security

  • Set appropriate file permissions on data directories
  • Use encrypted volumes for sensitive data
  • Regular backups of memory database
  • Secure logging to prevent information leakage

Monitoring and Logging

Health Checks

Monitor the /api/health endpoint for service health:

curl http://localhost:8000/api/health

Log Management

Configure log rotation for production:

# /etc/logrotate.d/novacoder
/var/log/novacoder/*.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    create 0640 novacoder novacoder
}

Metrics

Monitor system metrics provided by the health endpoint:

  • Memory usage
  • Database connection status
  • AI provider availability
  • Request queue depth

Performance Optimization

Caching

  • Use CDN for static assets
  • Enable HTTP caching headers
  • Consider Redis for distributed caching

Scaling

  • Use multiple instances behind a load balancer
  • Configure horizontal pod autoscaling in Kubernetes
  • Monitor resource usage and scale accordingly

Deployment Automation

Nova Coder provides comprehensive deployment automation capabilities through the DeploymentService, including multiple deployment strategies, automatic rollback, deployment verification, and deployment history tracking.

Deployment Strategies

The deployment automation system supports multiple deployment strategies:

  • Rolling Deployment - Gradually replaces old instances with new ones
  • Blue-Green Deployment - Maintains two identical environments for zero-downtime deployments
  • Canary Deployment - Gradually rolls out changes to a subset of users
  • Recreate Deployment - Stops all old instances before starting new ones

Deployment Configuration

from novacoder.deployment.automation import DeploymentConfig, DeploymentStrategy

config = DeploymentConfig(
    strategy=DeploymentStrategy.ROLLING,
    replicas=3,
    health_check_enabled=True,
    rollback_on_failure=True,
    max_retries=3
)

Deployment Execution

from novacoder.deployment.service import DeploymentService

svc = DeploymentService()
record = svc.automation.deploy(config)

print(f"Deployment ID: {record.deployment_id}")
print(f"Status: {record.status.value}")
print(f"Strategy: {record.strategy.value}")
print(f"Replicas: {record.replicas}")

Deployment History

View deployment history to track all deployments:

history = svc.automation.get_deployment_history()
for record in history:
    print(f"ID: {record.deployment_id}")
    print(f"Status: {record.status.value}")
    print(f"Strategy: {record.strategy.value}")
    print(f"Started: {record.started_at}")

Rollback

Automatic rollback is supported when deployment verification fails:

success = svc.automation.rollback(deployment_id)
if success:
    print("Rollback successful")

TUI Integration

The deployment automation is integrated into the TUI with the DeploymentPage:

Location: novacoder/gui/tui_screens/deployment_page.py - DeploymentPage class

TUI Features:

  • Strategy Selection: Choose from rolling, blue-green, canary, or recreate strategies
  • Deploy Button: Execute deployments with selected strategy
  • History View: View deployment history with status and details
  • Real-time Updates: Background thread loading for deployment data
  • Service Integration: Direct integration with DeploymentService via _get_service()

TUI Usage:

# Deploy with selected strategy
@work(thread=True)
def _deploy(self, strategy: str) -> None:
    from novacoder.deployment.service import DeploymentService
    from novacoder.deployment.automation import DeploymentConfig, DeploymentStrategy
    
    svc = _get_service(DeploymentService)
    config = DeploymentConfig(
        strategy=DeploymentStrategy(strategy),
        replicas=3,
        health_check_enabled=True
    )
    record = svc.automation.deploy(config)
    # Update UI with deployment result

Deployment REST API

Endpoint Description
POST /api/deployment/deploy Execute a strategy deployment (rolling, blue_green, canary, recreate) with health-check verification and automatic rollback. Body maps to DeploymentConfig.
GET /api/deployment/deployments Deployment history records
GET /api/deployment/deployments/{id} Single deployment record with logs and verification results
POST /api/deployment/deployments/{id}/rollback Manually roll back a deployment
GET /api/deployment/analytics Success rate, average duration, per-strategy/status breakdowns

The Deployment page exposes these as a "Strategy deployments" card with a strategy selector and per-deployment rollback.

Build Management

Nova Coder provides comprehensive build management capabilities through the DeploymentService, including wheel distribution building, Docker image creation, build status tracking, and artifact management.

Building Wheel Distributions

Build Python wheel and source distributions for PyPI distribution:

# Using CLI
novacoder deployment build-wheel

# Using REST API
curl -X POST http://localhost:8000/api/deployment/build-wheel

The build process uses python -m build and creates distributions in the dist/ directory.

Building Docker Images

Build Docker images for containerized deployment:

# Using CLI
novacoder deployment build-docker --image novacoder:latest

# Using REST API
curl -X POST http://localhost:8000/api/deployment/build-docker \
  -H "Content-Type: application/json" \
  -d '{"image": "novacoder:latest"}'

This requires a Dockerfile in the project root.

Build Status Tracking

Nova Coder automatically tracks build status with JSON persistence to .novacoder/build_status.json. Track build history and results:

# Using CLI
novacoder deployment status

# Using REST API
curl http://localhost:8000/api/deployment/status

Status information includes:

  • Build success/failure status
  • Return codes
  • Timestamps
  • Standard output and error streams

Artifact Management

List available build artifacts including wheel distributions, source distributions, and Docker images:

# Using CLI
novacoder deployment artifacts

# Using REST API
curl http://localhost:8000/api/deployment/artifacts

Web Interface Deployment

The web interface provides a user-friendly Deployment page for building wheel distributions and Docker images without using command-line tools.

Deployment Page Features

  • Build Wheel Card: Single-click wheel distribution building with status feedback
  • Build Docker Image Card: Docker image building with customizable image name
  • Build Status Display: Real-time status with success/failure indicators and timestamps
  • Build Artifacts Display: List of available build artifacts with type information
  • Visual Feedback: Color-coded success (green) and failure (red) indicators

Using the Web Interface

  1. Navigate to the Deployment page from the sidebar
  2. Click "Build Wheel" to create a Python wheel distribution
  3. Enter a custom image name and click "Build Docker Image" for Docker builds
  4. View build status and artifacts in the respective cards
  5. Results display automatically after build completion

Web API Endpoints

The web interface uses the same REST API endpoints as the CLI:

  • POST /api/deployment/build-wheel - Build wheel distribution
  • POST /api/deployment/build-docker - Build Docker image with custom name
  • GET /api/deployment/status - Get current build status
  • GET /api/deployment/artifacts - List available build artifacts

Artifact information includes:

  • Artifact name and type
  • File size (for distributions)
  • File path (for distributions)
  • Docker image size (for images)

DeploymentService API

The DeploymentService provides programmatic access to build operations:

from novacoder.deployment.service import DeploymentService
from novacoder.app import NovaApplication

app = NovaApplication()
app.initialize()
deployment_service = app.container.resolve(DeploymentService)

# Build wheel distribution
result = deployment_service.build_wheel()
print(f"Build success: {result['success']}")

# Build Docker image
result = deployment_service.build_docker(image_name="novacoder:latest")
print(f"Build success: {result['success']}")

# Get build status
status = deployment_service.get_build_status()
print(f"Build status: {status}")

# List artifacts
artifacts = deployment_service.get_artifacts()
print(f"Available artifacts: {len(artifacts)}")

app.stop()

Build Status File Format

Build status is stored in JSON format at .novacoder/build_status.json:

{
  "wheel": {
    "returncode": 0,
    "stdout": "Successfully built novacoder-0.1.0.tar.gz and novacoder-0.1.0-py3-none-any.whl",
    "stderr": "",
    "success": true,
    "timestamp": "1692345678.123"
  },
  "docker": {
    "returncode": 0,
    "stdout": "Successfully built 123abc456def",
    "stderr": "",
    "success": true,
    "timestamp": "1692345690.456"
  }
}

Troubleshooting

Common Issues

Service won't start:

  • Check environment variables are set correctly
  • Verify data directory permissions
  • Check port availability

HTTPS not working:

  • Verify SSL certificates are valid
  • Check reverse proxy configuration
  • Ensure firewall allows HTTPS traffic

Memory database errors:

  • Check disk space availability
  • Verify database file permissions
  • Check database connection limits

Build failures:

  • Check that python -m build is installed
  • Verify Docker is available for Docker builds
  • Check that Dockerfile exists for Docker builds
  • Review build status for detailed error messages
  • Ensure sufficient disk space for artifacts

Build status not updating:

  • Check write permissions for .novacoder/ directory
  • Verify disk space availability
  • Check for file system errors

Record 05 / 48 // Part II · APIs

API Reference

REST surface conventions and shapes · source wiki/api-reference.md

This document provides a concise reference for the core public APIs in Nova Coder.

REST API Route Modules

The Nova Coder REST API is organized into modular route files for better maintainability:

routes_common.py

Common utilities shared across all route modules.

Functions:

  • success_response(data, message) - Create a success JSON response. data is included whenever it is not None, empty lists/dicts/zeros are preserved (do not re-add a falsy check; empty collections are meaningful payloads).
  • error_response(error, error_code, details, status_code) - Create an error JSON response
  • paginated_response(data, total, page, page_size) - Create a paginated JSON response
  • generate_csrf_token() - Generate a new CSRF token
  • validate_csrf_token(request) - Validate CSRF token from request
  • set_csrf_cookie(response, token, request) - Set CSRF cookie on response
  • require_csrf(func) - Decorator to require CSRF token validation
  • rate_limit(limit) - Decorator to apply rate limiting

routes_auth.py

Authentication and session management routes.

Endpoints:

  • GET /api/auth/csrf-token - Generate CSRF token
  • POST /api/auth/login - Authenticate and create session
  • POST /api/auth/logout - Clear session
  • GET /api/auth/status - Check authentication status

routes_chat.py

Chat and messaging routes.

Endpoints:

  • GET /api/chat/history - Get chat history
  • POST /api/chat - Send message to agent
  • POST /api/chat/clear - Clear chat history

routes_system.py

System status and health routes.

Endpoints:

  • GET /api/rate-limit/status - Rate limiting status
  • GET /api/rate-limit/config - Rate limiting configuration
  • GET /api/rate-limit/stats - Rate limiting statistics
  • GET /api/status - Application status
  • GET /api/health - Detailed health metrics

routes_web.py

Web UI routes.

Endpoints:

  • GET / - Serve web dashboard

routes_webhooks.py

Webhook management routes.

Endpoints:

  • POST /api/webhooks - Create webhook
  • GET /api/webhooks - List webhooks (data.webhooks + data.total)
  • GET /api/webhooks/{webhook_id} - Get webhook
  • DELETE /api/webhooks/{webhook_id} - Delete webhook
  • GET /api/webhooks/stats - Webhook statistics

routes_ai.py

AI system features routes.

Endpoints:

  • POST /api/ai/multimodal/process - Process multimodal messages
  • GET /api/ai/multimodal/config - Multimodal configuration
  • POST /api/ai/multimodal/enable - Enable multimodal
  • POST /api/ai/multimodal/disable - Disable multimodal
  • GET /api/ai/systems/status - AI systems status
  • POST /api/ai/batch/request - Add batch request
  • POST /api/ai/batch/process - Process batch
  • GET /api/ai/batch/metrics - Batch metrics
  • POST /api/ai/error-handling/fallback - Register fallback provider
  • POST /api/ai/error-handling/circuit-breaker/reset - Reset circuit breaker
  • POST /api/ai/rag/store - Store RAG document
  • GET /api/ai/rag/search - Search RAG store
  • GET /api/ai/rag/documents - List RAG documents
  • DELETE /api/ai/rag/documents/{key} - Delete RAG document
  • POST /api/ai/rag/clear - Clear RAG store
  • POST /api/ai/rag/generate - Generate RAG response

routes_agents.py

Agent management routes.

Endpoints:

  • GET /api/agents - List agents (paginated)
  • POST /api/agents/run - Run agent task
  • GET /api/agent-features/config - Get features configuration
  • POST /api/agent-features/config - Update features configuration
  • GET /api/agent-features/status - Get features status
  • POST /api/agent-features/enable - Enable feature
  • POST /api/agent-features/disable - Disable feature

For detailed information about the modular route system, see API Modular Routes.

Kernel

NovaService

class NovaService(ABC):
    name: str

    def initialize(self) -> None
    def start(self) -> None
    def stop(self) -> None
    def dispose(self) -> None
    def health(self) -> ServiceHealth

Container

Method Description
register(key, factory, singleton=True) Register a service
register_instance(key, instance) Register an existing instance
resolve(key) Retrieve a service
is_registered(key) Check if a service exists
clear() Remove all registrations

EventBus

Method Description
subscribe(event_name, handler) Register an event handler
unsubscribe(event_name, handler) Remove an event handler
subscribe_with_filter(filter_func, handler) Register a filtered event handler
unsubscribe_with_filter(filter_func, handler) Remove a filtered event handler
add_router(router_func) Add an event router
remove_router(router_func) Remove an event router
publish(event) Publish an event synchronously
publish_async(event) Publish an event asynchronously
get_history(event_name=None) Return recent published events
clear_history() Clear event history

Registry

Method Description
register_instance(name, instance) Register a service instance
register_type(name, service_type) Register a service class
get(name) Get an instance by name
get_type(name) Get a class by name
create(name, *args, **kwargs) Create a new instance
list_services() List registered instance names
list_types() List registered type names

HealthMonitor

Method Description
add_check(name, check) Register a health check
evaluate(services) Evaluate overall health
last_report() Get most recent health report
get_history(limit=None) Get health history
get_service_history(service_name) Get service-specific history
get_alerts(severity=None, limit=None) Get alerts
get_health_trend(hours) Get health trend
add_alert_callback(callback) Register alert callback
save_history(file_path) Save history to file
load_history(file_path) Load history from file

ServiceMesh

Method Description
register_service(instance) Register a service instance
unregister_service(service_name, instance_id) Unregister a service instance
get_service_instances(service_name) Get all instances of a service
get_healthy_instances(service_name) Get only healthy instances
select_instance(service_name) Select an instance using load balancing
health_check(service_name, health_check_func) Perform health checks
record_request(service_name, success, latency_ms) Record request metrics
get_metrics(service_name) Get metrics for a service
get_all_metrics() Get metrics for all services
set_load_balancing(strategy) Set load balancing strategy
get_mesh_status() Get overall mesh status
reset_metrics(service_name=None) Reset metrics

EventSourcingService

Method Description
save_event(event) Save an event and notify handlers
replay_events(aggregate_id, from_version=None) Replay events for an aggregate
reconstruct_state(aggregate, from_version=None) Reconstruct aggregate state from events
register_event_handler(event_type, handler) Register an event handler
get_event_store() Get the event store
save_to_file(file_path) Save event store to file
load_from_file(file_path) Load event store from file
get_aggregate_version(aggregate_id) Get aggregate version
create_snapshot(aggregate) Create and save a snapshot
get_all_events() Get all events in the store

LifecycleManager

Method Description
set_startup_order(order) Define service startup order
initialize_all() Initialize all services in order
start_all() Start all services in order
stop_all() Stop all services in reverse order

Runtime

RuntimeService

class RuntimeService(NovaService):
    def initialize(self) -> None
    def start(self) -> None
    def stop(self) -> None
    def health(self) -> ServiceHealth
    async def stream(self, prompt: str, provider_name: str | None = None, ...) -> AsyncIterator[str]
    def session(self, prompt: str, provider_name: str | None = None, ...) -> StreamingSession

Resolves AIService from the container and exposes two streaming entry points:

  • stream(), async iterator that yields tokens as they are produced
  • session(), returns a StreamingSession that captures tokens and final text

StreamingSession

class StreamingSession:
    async def __aiter__(self) -> AsyncIterator[str]
    def text(self) -> str
    @property
    def tokens(self) -> list[str]

stream_tokens

async def stream_tokens(provider: AIProvider, messages: list[ChatMessage]) -> AsyncIterator[str]

See Runtime Streaming for full documentation and usage examples.

Application

NovaApplication

Method Description
initialize() Build and wire all services
start() Initialize and start all services
run() Start and keep alive
stop() Stop and dispose all services
health() Return health report
status() Return status summary
is_running() Check if running

create_app

def create_app(
    project_path: Path | str | None = None,
    overrides: dict[str, Any] | None = None,
) -> NovaApplication

Configuration

AppConfig

class AppConfig(BaseSettings):
    app_name: str
    version: str
    data_dir: str
    model: ModelConfig
    workspace: WorkspaceConfig
    memory: MemoryConfig
    tools: ToolsConfig
    agents: AgentsConfig
    plugins: PluginsConfig
    api: ApiConfig
    logging: LoggingConfig

ApiConfig

class ApiConfig(BaseModel):
    host: str = "0.0.0.0"
    port: int = 8000
    token: str | None = None

Controls REST API settings. host and port configure the bind address for novacoder serve. Set NOVACODER_API__TOKEN to require the X-API-Token header for all /api/* endpoints.

PluginsConfig

class PluginsConfig(BaseModel):
    plugins_dir: str | None = None
    enabled: bool = True

Controls plugin discovery. plugins_dir is an optional directory path for local plugins. enabled toggles plugin loading entirely.

ConfigLoader

Method Description
load(overrides=None) Load merged configuration
load_from_file(path) Load from a single file

AI Runtime

AIProvider

class AIProvider(ABC):
    @property
    def capabilities(self) -> ProviderCapabilities
    async def chat(self, messages, **kwargs) -> str
    async def complete(self, prompt, **kwargs) -> str
    async def stream(self, messages, **kwargs) -> AsyncIterator[str]
    async def embed(self, text, **kwargs) -> list[float]
    async def available_models(self) -> list[str]
    async def health_check(self) -> dict

ProviderManager

Method Description
register(name, provider_type) Register a provider class
load(name, **kwargs) Create or return a provider
get(name) Return existing provider
list_providers() List registered providers

ModelRouter

Method Description
select(task, **kwargs) Select provider by task
auto_select(task, context_length) Heuristic selection

Agents

Agent

class Agent(ABC):
    name: str
    description: str
    async def run(self, task: AgentTask) -> AgentResult

AgentTask

@dataclass
class AgentTask:
    id: str
    description: str
    goal: str
    context: dict[str, Any]
    priority: int

AgentResult

@dataclass
class AgentResult:
    success: bool
    output: Any | None
    summary: str
    errors: list[str]

AgentManager

Method Description
register(agent) Register an agent
get(name) Get an agent by name
list_agents() List registered agents
run(name, task) Execute a task with an agent
describe_all() Return agent metadata

Tools

Tool

class Tool(ABC):
    name: str
    description: str
    parameters: list[ToolParameter]
    permissions: list[str]
    def run(self, **kwargs) -> ToolResult
    async def arun(self, **kwargs) -> ToolResult
    def to_dict(self) -> dict

ToolResult

@dataclass
class ToolResult:
    success: bool
    output: Any | None
    error: str | None

ToolRegistry

Method Description
register(tool) Register a tool
unregister(name) Remove a tool
get(name) Get a tool by name
list_tools() List registered tools
execute(name, **kwargs) Execute a tool
describe_all() Return tool metadata

Workspace

ProjectScanner

Method Description
scan() Scan the project directory
get_files() Return indexed files
summary() Return project summary

SymbolExtractor

Method Description
extract(path) Extract symbols from a file

SymbolIndex

Method Description
add(symbols) Add symbols
find(name, kind) Find symbols
find_by_file(path) Symbols from a file
clear() Clear index

Memory

MemoryStore

Method Description
initialize() Create tables
close() Close connection
set(key, value, scope) Store value
get(key, scope) Retrieve value
get_all(scope) Retrieve all values
delete(key, scope) Delete value

MemoryScope

  • SESSION
  • WORKING
  • PROJECT
  • PERSISTENT
  • AGENT

Plugins

Plugin

class Plugin(ABC):
    name: str
    version: str
    def initialize(self) -> None
    def shutdown(self) -> None
    def register_tools(self) -> list[Tool]
    def register_agents(self) -> list[Agent]
    def register_providers(self) -> list[AIProvider]
    def register_extractors(self) -> dict[str, LanguageExtractor]
    def register_workflows(self) -> list[Plan]
    def register_commands(self) -> list[dict[str, Any]]
    def to_dict(self) -> dict

PluginService

Method Description
register(plugin) Register a plugin
list_plugins() List plugin metadata

Maintaining This Reference

When adding, removing, or changing a public API:

  1. Update the relevant section in this document.
  2. Keep signatures consistent with the source code.
  3. Add new sections for new subsystems.
  4. Cross-link related subsystem documentation.
  5. Verify that code examples still compile and run.

REST API Endpoints

Dashboard API

Endpoint Method Description
/api/dashboard GET Get system overview and statistics
/api/dashboard/stats GET Get detailed dashboard statistics
/api/dashboard/notifications GET Get system notifications, alerts, and updates

Planner API

Endpoint Method Description
/api/plan POST Generate execution plan from goal
/api/plan/execute POST Execute a previously generated plan
/api/plan/history GET Get history of previously generated plans
/api/plan/validate POST Validate plan structure and resource availability

Editor API

Endpoint Method Description
/api/editor/file GET Read file content
/api/editor/file POST Create new file
/api/editor/file PUT Update existing file
/api/editor/file DELETE Delete file
/api/editor/search GET Search code across files in workspace
/api/editor/symbols GET Extract code symbols from a file
/api/editor/format POST Format code in a file
/api/editor/collaborate POST Handle real-time collaboration events

Monitoring API

Endpoint Method Description
/api/monitoring/metrics GET Get system metrics
/api/monitoring/alerts GET Get monitoring alerts

Analytics API

Endpoint Method Description
/api/analytics/usage GET Get usage analytics
/api/analytics-api/performance GET Get performance analytics
/api/analytics/forecast POST Auto-train + forecast a metric series
/api/analytics/models GET/POST List / register prediction models
/api/analytics/models/{id}/train POST Train a registered model
/api/analytics/models/{id}/predict POST Predict N points ahead
/api/analytics/models/{id} DELETE Remove a prediction model
/api/analytics/report-templates GET List report templates
/api/analytics/reports POST Generate a report (template or custom; optional format render)
/api/analytics/export POST Export a dataset (json/csv/xml)
/api/analytics/exports GET List export jobs
/api/analytics/exports/{id} GET Get export status
/api/analytics/exports/cleanup POST Remove old export records

CI/CD API

Endpoint Method Description
/api/cicd/pipelines GET List CI/CD pipelines
/api/cicd/pipelines POST Create new pipeline (CI-CD system)
/api/cicd/pipelines/{pipeline_id}/run POST Execute pipeline
/api/cicd/runs GET List pipeline runs

Distributed API

Endpoint Method Description
/api/distributed/nodes GET List distributed nodes
/api/distributed/statistics GET Get distributed system statistics

Security API

Endpoint Method Description
/api/security/rules GET List security rules
/api/security/scan POST Scan code for security issues
/api/security/statistics GET Get security statistics
/api/security/zero-trust/identities GET List zero trust identities
/api/security/zero-trust/devices GET List zero trust devices
/api/security/zero-trust/access-request POST Submit zero-trust access request
/api/security/zero-trust/statistics GET Get zero trust statistics
/api/security/ml-threats/predict POST Run ML threat prediction (list: GET /api/security/ml-threats/models)
/api/security/ml-threats/statistics GET Get ML threat statistics
/api/security/behavioral/statistics GET Behavioral analysis statistics (events/alerts/record also available)
/api/security/behavioral/alerts GET List behavioral alerts
/api/security/behavioral/statistics GET Get behavioral analysis statistics
/api/security/automation/rules GET List automation rules
/api/security/automation/statistics GET Automation statistics (rules/process-event also available)
/api/security/automation/statistics GET Get automation statistics
/api/security/supply-chain/sboms GET List Software Bill of Materials
/api/security/supply-chain/sboms POST Generate Software Bill of Materials
/api/security/supply-chain/sboms/{sbom_id}/analyze GET Analyze dependencies for security issues
/api/security/supply-chain/sboms/{sbom_id}/attack-paths GET Analyze attack paths through dependencies
/api/security/supply-chain/statistics GET Get supply chain security statistics
/api/security/compliance/rules GET List compliance rules
/api/security/compliance/rules POST Add compliance rule
/api/security/compliance/reports POST Generate compliance report
/api/security/compliance/reports GET List compliance reports
/api/security/compliance/remediation/{action_id}/execute POST Execute remediation action
/api/security/compliance/statistics GET Get compliance automation statistics

Infrastructure API

Endpoint Method Description
/api/infrastructure/kubernetes/deployments GET List Kubernetes deployments
/api/infrastructure/kubernetes/deployments POST Create Kubernetes deployment
/api/infrastructure/kubernetes/services GET List Kubernetes services
/api/infrastructure/kubernetes/services POST Create Kubernetes service
/api/infrastructure/kubernetes/manifests GET Generate Kubernetes manifests
/api/infrastructure/kubernetes/statistics GET Get Kubernetes statistics
/api/infrastructure/kubernetes/helm-chart GET Generate Helm chart
/api/disaster-recovery/backups GET List disaster recovery backups
/api/disaster-recovery/backups POST Create disaster recovery backup
/api/disaster-recovery/backups/{backup_id}/restore POST Restore disaster recovery backup
/api/disaster-recovery/backups/{backup_id} DELETE Delete disaster recovery backup
/api/disaster-recovery/plans GET List disaster recovery plans
/api/disaster-recovery/plans POST Create disaster recovery plan
/api/disaster-recovery/plans/{plan_id}/execute POST Execute disaster recovery plan
/api/disaster-recovery/plans/{plan_id}/test POST Test disaster recovery plan
/api/disaster-recovery/failover POST Initiate failover to secondary region
/api/disaster-recovery/failover/revert POST Revert failover to primary region
/api/disaster-recovery/replication GET Get data replication status
/api/disaster-recovery/statistics GET Get disaster recovery statistics

Deployment API

Endpoint Method Description
/api/deployment/health GET Deployment service health
/api/deployment/status GET Current deployment status
/api/deployment/build-wheel POST Build a Python wheel artifact
/api/deployment/build-docker POST Build a Docker image ({image_name})
/api/deployment/artifacts GET List build artifacts
/api/deployment/deploy POST Trigger a deployment
/api/deployment/deployments GET List deployments
/api/deployment/deployments/{deployment_id} GET Get deployment detail
/api/deployment/deployments/{deployment_id}/rollback POST Roll back a deployment
/api/deployment/analytics GET Deployment statistics

Code Intelligence API

Endpoint Method Description
/api/code-intelligence/analyze POST Analyze code for issues
/api/code-intelligence/refactoring POST Get refactoring suggestions
/api/code-intelligence/metrics POST Calculate code quality metrics

Memory Governance API

Endpoint Method Description
/api/memory-advanced/versions GET List recorded memory versions
/api/memory-advanced/versions/{id} GET Get a single version
/api/memory-advanced/versions/{id}/rollback POST Restore a previous value
/api/memory-advanced/versions/compare POST Diff two versions
/api/memory-advanced/version-stats GET Versioning statistics
/api/memory-advanced/decay/config GET/POST Get / update decay policy
/api/memory-advanced/decay/preview POST Preview decay effect
/api/memory-advanced/decay/apply POST Apply decay now

Workflow Governance API

Endpoint Method Description
/api/workflows/execute POST Execute a workflow ({workflow, goal}; workflow_name optional)
/api/workflow-templates GET List workflow templates
/api/workflows/{name}/versions GET Version history for a workflow
/api/workflows/access/{grant,revoke,role,user-roles,role-permissions,permissions/{user_id},audit} GET/POST Workflow RBAC policy endpoints

Tool Approvals & Plugin Marketplace API

Endpoint Method Description
/api/tools/approvals GET List pending tool executions
/api/tools/approvals/{id}/approve POST Approve a pending execution
/api/tools/approvals/{id}/reject POST Reject a pending execution
/api/plugins/marketplace/list GET List marketplace plugins
/api/plugins/marketplace/register POST Register a marketplace plugin
/api/marketplace/agents GET List marketplace agents
/api/plugins/{name}/enable POST Enable a plugin
/api/plugins/{name}/disable POST Disable a plugin

Observability API

Endpoint Method Description
/metrics GET Prometheus text exposition (localhost only)
/api/monitoring/metrics/prometheus GET Token-protected Prometheus scrape
/api/monitoring/notification-channels GET List channels (data.channels + data.total)
/api/monitoring/notification-channels/pagerduty POST Add a PagerDuty notification channel
/api/monitoring/user-analytics/behaviors POST Record a user behavior event
/api/monitoring/opentelemetry/export GET/POST OTLP JSON export / write to file
/api/security/threats GET List detected threats (data.threats + data.total)
/api/webhooks GET List webhooks (data.webhooks + data.total)

Response-shape conventions

  • success_response payloads include data whenever it is not None, empty [], {}, and 0 are meaningful and preserved.
  • REST list endpoints diverge by module: some return bare arrays (/api/tools, /api/editor/files), others envelope under a named key (data.webhooks, data.channels, data.threats). Frontend queryFns normalize both, probe the live response before assuming.
  • Secrets are masked with ******** on GET and restored on write; do not round-trip the sentinel into real values.
  • Development Guide
  • Examples
  • Dashboard System
  • Planner
  • Editor System
  • Monitoring System
  • Analytics System
  • CI/CD System
  • Security System
  • Supply Chain Security
  • Compliance Automation
  • Distributed System
  • Kubernetes Integration
  • Disaster Recovery
  • Code Intelligence

Record 06 / 48 // Part II · APIs

API Endpoint Reference

Endpoint inventory · source wiki/api-endpoint-reference.md

This document provides a comprehensive reference for all Nova Coder API endpoints.

Base URL

http://localhost:8000

Authentication

Most endpoints require authentication via API token. Include the token in one of the following ways:

  • Header: X-API-Token: your-token
  • Query parameter: ?token=your-token
  • Cookie: novacoder_session=your-token

Response Format

All responses follow a standardized format:

Success Response:

{
  "success": true,
  "data": {},
  "message": "Optional success message"
}

Error Response:

{
  "success": false,
  "error": "Error message",
  "error_code": "ERROR_CODE",
  "details": {}
}

Endpoints by Category

Authentication

POST /api/auth/login

Login with username and password.

Request Body:

{
  "username": "admin",
  "password": "password"
}

Response:

{
  "success": true,
  "data": {
    "token": "api-token",
    "username": "admin"
  }
}

POST /api/auth/logout

Logout and invalidate session.

Response:

{
  "success": true,
  "message": "Logged out successfully"
}

GET /api/auth/status

Check authentication status.

Response:

{
  "success": true,
  "data": {
    "authenticated": true,
    "username": "admin"
  }
}

GET /api/auth/csrf-token

Get CSRF token for form submissions.

Response:

{
  "success": true,
  "data": {
    "csrf_token": "csrf-token"
  }
}

Agents

GET /api/agents

List all registered agents.

Query Parameters:

  • page (optional): Page number (default: 1)
  • page_size (optional): Items per page (default: 50, max: 100)
  • fields (optional): Comma-separated fields to include
  • exclude (optional): Comma-separated fields to exclude

Response:

{
  "success": true,
  "data": {
    "agents": [
      {
        "name": "coder",
        "description": "Generates and edits code",
        "capabilities": ["code_generation", "code_editing"],
        "status": "active"
      }
    ],
    "total": 17,
    "page": 1,
    "page_size": 50
  }
}

POST /api/agents/run

Run an agent task.

Request Body:

{
  "agent_name": "coder",
  "goal": "Add a login function",
  "context": {
    "file": "auth.py"
  }
}

Response:

{
  "success": true,
  "data": {
    "task_id": "task-123",
    "status": "running",
    "result": null
  }
}

GET /api/agents

Get the list of registered agents (per-agent detail is exposed via /api/agents/{agent_name}/enable|disable, /api/agents/learning/{agent_name}/metrics; there is no GET /api/agents/{agent_name} detail route).

Response:

{
  "success": true,
  "data": {
    "name": "coder",
    "description": "Generates and edits code",
    "capabilities": ["code_generation", "code_editing"],
    "status": "active"
  }
}

Chat

GET /api/chat/history

Get chat history.

Query Parameters:

  • limit (optional): Number of messages to retrieve (default: 50)

Response:

{
  "success": true,
  "data": {
    "messages": [
      {
        "role": "user",
        "content": "Hello",
        "timestamp": "2026-08-04T00:00:00Z"
      },
      {
        "role": "assistant",
        "content": "Hi! How can I help?",
        "timestamp": "2026-08-04T00:00:01Z"
      }
    ]
  }
}

POST /api/chat/send

Send a chat message.

Request Body:

{
  "message": "Help me write code",
  "stream": false
}

Response:

{
  "success": true,
  "data": {
    "response": "I'll help you write code...",
    "message_id": "msg-123"
  }
}

POST /api/chat/clear

Clear chat history.

Response:

{
  "success": true,
  "message": "Chat history cleared"
}

System

GET /api/system/status

Get system status.

Response:

{
  "success": true,
  "data": {
    "status": "running",
    "version": "0.1.0",
    "uptime": 3600,
    "memory_usage": "512MB"
  }
}

GET /api/system/health

Get system health check.

Response:

{
  "success": true,
  "data": {
    "healthy": true,
    "checks": {
      "database": "ok",
      "ai_service": "ok",
      "memory": "ok"
    }
  }
}

GET /api/system/config

Get system configuration.

Response:

{
  "success": true,
  "data": {
    "model": {
      "provider": "openai",
      "model": "gpt-4"
    },
    "workspace": {
      "project_path": "/path/to/project"
    }
  }
}

GET /api/rate-limit/status

Get rate limiting status.

Response:

{
  "success": true,
  "data": {
    "enabled": true,
    "limits": {
      "default": "100/hour"
    },
    "current_usage": {
      "requests": 10,
      "window": "hour"
    }
  }
}

Tools

GET /api/tools

List available tools.

Query Parameters:

  • page (optional): Page number (default: 1)
  • page_size (optional): Items per page (default: 50)

Response:

{
  "success": true,
  "data": {
    "tools": [
      {
        "name": "file_read",
        "description": "Read file contents",
        "parameters": {
          "path": "string"
        }
      }
    ],
    "total": 20,
    "page": 1,
    "page_size": 50
  }
}

POST /api/tools/execute

Execute a tool.

Request Body:

{
  "tool_name": "file_read",
  "parameters": {
    "path": "/path/to/file"
  }
}

Response:

{
  "success": true,
  "data": {
    "result": "file contents",
    "execution_time": 0.1
  }
}

Memory

GET /api/memory

Get memory entries.

Query Parameters:

  • scope (optional): Memory scope (default: "default")
  • limit (optional): Number of entries (default: 50)

Response:

{
  "success": true,
  "data": {
    "entries": [
      {
        "key": "conversation_summary",
        "value": "Summary of conversation",
        "scope": "default",
        "created_at": "2026-08-04T00:00:00Z"
      }
    ]
  }
}

POST /api/memory

Set a memory entry.

Request Body:

{
  "key": "user_preference",
  "value": "dark_mode",
  "scope": "user"
}

Response:

{
  "success": true,
  "message": "Memory entry set"
}

DELETE /api/memory

Delete a memory entry.

Request Body:

{
  "key": "user_preference",
  "scope": "user"
}

Response:

{
  "success": true,
  "message": "Memory entry deleted"
}

Files

GET /api/files

List files in workspace.

Query Parameters:

  • path (optional): Directory path (default: root)
  • recursive (optional): Include subdirectories (default: false)

Response:

{
  "success": true,
  "data": {
    "files": [
      {
        "path": "src/main.py",
        "size": 1024,
        "type": "file",
        "modified_at": "2026-08-04T00:00:00Z"
      }
    ]
  }
}

GET /api/editor/file

Get file content.

Query Parameters:

  • path: File path (required)

Response:

{
  "success": true,
  "data": {
    "path": "src/main.py",
    "content": "file contents",
    "size": 1024
  }
}

Webhooks

POST /api/webhooks

Create a new webhook.

Request Body:

{
  "url": "https://example.com/webhook",
  "events": ["AGENT_EXECUTION_COMPLETED"],
  "secret": "webhook-secret"
}

Response:

{
  "success": true,
  "data": {
    "webhook_id": "webhook-123",
    "url": "https://example.com/webhook",
    "events": ["AGENT_EXECUTION_COMPLETED"],
    "status": "ACTIVE"
  }
}

GET /api/webhooks

List all webhooks.

Response:

{
  "success": true,
  "data": {
    "webhooks": [
      {
        "webhook_id": "webhook-123",
        "url": "https://example.com/webhook",
        "events": ["AGENT_EXECUTION_COMPLETED"],
        "status": "ACTIVE"
      }
    ]
  }
}

GET /api/webhooks/{webhook_id}

Get webhook by ID.

Response:

{
  "success": true,
  "data": {
    "webhook_id": "webhook-123",
    "url": "https://example.com/webhook",
    "events": ["AGENT_EXECUTION_COMPLETED"],
    "status": "ACTIVE",
    "statistics": {
      "total_delivered": 100,
      "total_failed": 2
    }
  }
}

DELETE /api/webhooks/{webhook_id}

Delete a webhook.

Response:

{
  "success": true,
  "message": "Webhook deleted"
}

GET /api/webhooks/stats

Get webhook statistics.

Response:

{
  "success": true,
  "data": {
    "total_webhooks": 5,
    "active_webhooks": 4,
    "total_deliveries": 1000,
    "total_failures": 10
  }
}

API Gateway

GET /api/gateway/status

Get gateway status and configuration.

Response:

{
  "success": true,
  "gateway": {
    "enabled": false,
    "timeout": 30,
    "retry_attempts": 3,
    "load_balancing_strategy": "round_robin",
    "registered_services": ["default"],
    "routes": {"/api/v1": "default"}
  }
}

GET /api/gateway/metrics

Get comprehensive gateway metrics.

Response:

{
  "success": true,
  "metrics": {
    "gateway_status": {...},
    "service_statuses": {
      "default": {
        "service": "default",
        "total_endpoints": 2,
        "healthy_endpoints": 2
      }
    }
  }
}

GET /api/gateway/services/{service_name}

Get status for a specific service.

Response:

{
  "success": true,
  "service": {
    "service": "default",
    "total_endpoints": 2,
    "healthy_endpoints": 2,
    "endpoints": [...]
  }
}

POST /api/gateway/configure

Configure gateway settings.

Request Body:

{
  "enabled": true,
  "timeout": 30,
  "retry_attempts": 3,
  "load_balancing_strategy": "round_robin"
}

Response:

{
  "success": true,
  "result": {
    "status": "configured",
    "settings": {...}
  }
}

POST /api/gateway/routes

Add a new route.

Request Body:

{
  "path": "/api/v1",
  "service_name": "backend"
}

Response:

{
  "success": true,
  "result": {
    "status": "added",
    "route": {...}
  }
}

POST /api/gateway/services

Register a new service.

Request Body:

{
  "service_name": "backend",
  "endpoint_url": "http://localhost:8001",
  "weight": 1
}

Response:

{
  "success": true,
  "result": {
    "status": "registered",
    "service": "backend",
    "endpoint": "http://localhost:8001"
  }
}

AI

POST /api/ai/multimodal/process

Process multimodal AI request.

Request Body:

{
  "text": "Analyze this image",
  "image": "base64-encoded-image"
}

Response:

{
  "success": true,
  "data": {
    "result": "Analysis result",
    "tokens_used": 100
  }
}

POST /api/ai/batch/request

Submit a batch AI request (see also /api/ai/batch/process, /api/ai/batch/metrics).

Request Body:

{
  "requests": [
    {"prompt": "Task 1"},
    {"prompt": "Task 2"}
  ]
}

Response:

{
  "success": true,
  "data": {
    "results": [
      {"result": "Result 1"},
      {"result": "Result 2"}
    ]
  }
}

POST /api/ai/rag/generate

Process RAG (Retrieval-Augmented Generation) request.

Request Body:

{
  "query": "How do I implement X?",
  "context": "project_context"
}

Response:

{
  "success": true,
  "data": {
    "answer": "Answer with retrieved context",
    "sources": ["file1.py", "file2.py"]
  }
}

Analytics API

GET /api/analytics-api/summary

Get comprehensive analytics summary including endpoint stats, error analysis, performance metrics, and client analytics.

Response:

{
  "success": true,
  "data": {
    "endpoint_stats": {...},
    "error_analysis": {...},
    "performance_metrics": {...},
    "client_analytics": {...},
    "total_events": 1000,
    "retention_days": 30,
    "enabled": true
  }
}

GET /api/analytics-api/endpoint-stats

Get statistics for a specific endpoint or all endpoints.

Query Parameters:

  • endpoint (optional): Endpoint path or full metric key to get stats for. If omitted, all recorded endpoint statistics are returned. When a plain path is supplied (e.g. /api/health), metrics are aggregated across all HTTP methods that hit that path.

Response:

{
  "success": true,
  "data": {
    "endpoint": "/api/status",
    "request_count": 100,
    "total_duration_ms": 5000,
    "error_count": 2,
    "status_codes": {200: 98, 500: 2},
    "avg_duration_ms": 50,
    "last_request": "2026-08-05T12:00:00.000000"
  }
}

GET /api/analytics-api/time-series

Get time series analytics data for requests.

Query Parameters:

  • endpoint (optional): Optional endpoint filter
  • hours (optional): Time period in hours (default: 24, range: 1-168)

Response:

{
  "success": true,
  "data": {
    "endpoint": "all",
    "period_hours": 24,
    "data": [
      {
        "hour": "2026-08-05-12",
        "count": 50,
        "errors": 1,
        "avg_duration_ms": 45
      }
    ]
  }
}

GET /api/analytics-api/error-analysis

Get error analysis data.

Response:

{
  "success": true,
  "data": {
    "total_errors": 10,
    "error_rate": 1.0,
    "by_status": {400: 5, 500: 5},
    "by_endpoint": {
      "/api/chat": {"count": 5, "status_codes": {500: 5}}
    }
  }
}

GET /api/analytics-api/performance

Get performance metrics.

Response:

{
  "success": true,
  "data": {
    "avg_duration_ms": 50,
    "p50_duration_ms": 45,
    "p95_duration_ms": 100,
    "p99_duration_ms": 200,
    "min_duration_ms": 10,
    "max_duration_ms": 500
  }
}

GET /api/analytics-api/clients

Get client analytics.

Query Parameters:

  • limit (optional): Number of top clients to return (default: 10, range: 1-100)

Response:

{
  "success": true,
  "data": {
    "top_clients": [
      {
        "client_id": "203.0.113.100",
        "request_count": 100,
        "error_count": 2,
        "avg_duration_ms": 45
      }
    ]
  }
}

POST /api/analytics-api/clear

Clear all analytics data.

Response:

{
  "success": true,
  "data": {
    "status": "cleared",
    "timestamp": "2026-08-05T12:00:00.000000"
  }
}

GET /api/analytics-api/status

Get analytics system status.

Response:

{
  "success": true,
  "data": {
    "enabled": true,
    "retention_days": 30,
    "total_events": 1000,
    "total_endpoints": 50,
    "timestamp": "2026-08-05T12:00:00.000000"
  }
}

Workflows

GET /api/workflows/health

Get the workflow subsystem health status.

Response:

{
  "success": true,
  "data": {
    "healthy": true,
    "status": "running"
  }
}

GET /api/workflows/components

List components registered in the workflow subsystem.

Response:

{
  "success": true,
  "data": {
    "components": ["scheduler", "executor", "validator"]
  }
}

GET /api/workflows

List all saved workflow files.

Response:

{
  "success": true,
  "data": {
    "workflows": ["deploy", "test-suite"]
  }
}

GET /api/workflows/{name}

Load a saved workflow YAML file by name.

Response:

{
  "success": true,
  "data": {
    "name": "deploy",
    "yaml": "name: deploy\nsteps: []"
  }
}

POST /api/workflows

Save a workflow YAML file.

Request Body:

{
  "name": "deploy",
  "yaml": "name: deploy\nsteps: []"
}

Response:

{
  "success": true,
  "message": "Workflow saved"
}

DELETE /api/workflows/{name}

Delete a saved workflow YAML file.

Response:

{
  "success": true,
  "message": "Workflow deleted"
}

Security Audit

GET /api/security/health

Get the security subsystem health status.

Response:

{
  "success": true,
  "data": {
    "healthy": true,
    "status": "running"
  }
}

GET /api/security/components

List components registered in the security subsystem.

Response:

{
  "success": true,
  "data": {
    "components": ["scanner", "audit_logger", "rules_engine"]
  }
}

GET /api/security/audit

List recent security audit events.

Response:

{
  "success": true,
  "data": {
    "events": [
      {
        "timestamp": "2026-08-05T12:00:00Z",
        "event_type": "scan",
        "details": "..."
      }
    ]
  }
}

GET /api/security/audit/summary

Get a summary of security audit events.

Response:

{
  "success": true,
  "data": {
    "total_events": 42,
    "event_types": {"scan": 30, "alert": 12}
  }
}

PUT /api/system/config

Update the full application configuration.

Request Body:

{
  "model": {
    "provider": "ollama",
    "model": "deepseek-coder"
  }
}

Response:

{
  "success": true,
  "message": "Configuration updated"
}

Field Selection

Many endpoints support field selection via query parameters:

  • fields: Comma-separated fields to include
  • exclude: Comma-separated fields to exclude

Example:

GET /api/agents?fields=name,status
GET /api/agents?exclude=metadata,capabilities

Pagination

List endpoints support pagination:

  • page: Page number (default: 1)
  • page_size: Items per page (default: 50, max: 100)

Example:

GET /api/agents?page=2&page_size=25

Rate Limiting

API requests are rate limited. Default limit is 100 requests per hour.

Rate limit headers are included in responses:

  • X-RateLimit-Limit: Total limit
  • X-RateLimit-Remaining: Remaining requests
  • X-RateLimit-Reset: Reset time (Unix timestamp)

Record 07 / 48 // Part II · APIs

API Authentication

Token auth, sessions, CSRF · source wiki/api-authentication.md

The Nova Coder API supports token-based authentication with opaque server-side sessions.

Overview

The live authentication model is a single configured API token (api.token config or NOVACODER_API_TOKEN), enforced by TokenAuthMiddleware on all /api/* routes plus /graphql, /docs, /redoc, and /openapi.json. POST /api/auth/login issues an opaque, server-side session cookie (api/sessions.py) that expires per authentication.session_timeout and is revoked by /api/auth/logout.

2026-10-13 update: the dormant JWTAuth / PasswordAuth / OAuth2Handler / AdvancedAuthMiddleware helpers were removed from novacoder/api/auth.py, they were never wired into the request path (login issued a raw-token cookie, and no route decoded a JWT). The sections below describing them are retained for design history only; JWT_SECRET_KEY is no longer read or required. If multi-user JWT auth is ever implemented it should land as a deliberate feature, not dormant code guarded by the boot check.

Authentication Methods

Token-Based Authentication

The simplest authentication method using API tokens:

import httpx

# Using header
response = httpx.get("http://localhost:8000/api/status",
    headers={"x-api-token": "your-token-here"}
)

# Using Bearer token
response = httpx.get("http://localhost:8000/api/status",
    headers={"Authorization": "Bearer your-token-here"}
)

# Using the session cookie (obtained via POST /api/auth/login)
response = httpx.get("http://localhost:8000/api/status",
    cookies={"novacoder_session": "session-id"}
)

Note: there is no query-parameter authentication — ?token=… and ?api_key=… are not consulted by TokenAuthMiddleware (keeping tokens out of URLs/logs is deliberate).

JWT Authentication (removed, historical)

JSON Web Tokens provide stateless authentication:

from novacoder.api.auth import JWTAuth

# Create access token
token = JWTAuth.create_access_token({"user_id": "user123"})

# Use token in Authorization header
response = httpx.get("http://localhost:8000/api/status",
    headers={"Authorization": f"Bearer {token}"}
)

OAuth2 Authentication

OAuth2 provides standardized authorization:

from novacoder.api.auth import OAuth2Handler

# Create OAuth2 token
token = OAuth2Handler.create_oauth2_token("user123", ["read", "write"])

# Use token in Authorization header
response = httpx.get("http://localhost:8000/api/status",
    headers={"Authorization": f"Bearer {token}"}
)

Password Authentication

Password hashing and verification:

from novacoder.api.auth import PasswordAuth

# Hash password
hashed = PasswordAuth.hash_password("mypassword")

# Verify password
is_valid = PasswordAuth.verify_password("mypassword", hashed)

Configuration

Environment Variables

  • NOVACODER_API_TOKEN: API token for header/Bearer authentication
  • JWT_SECRET_KEY (no longer used, JWT helpers removed 2026-10-13)
  • ENVIRONMENT: Environment setting (development/staging/production)
  • NOVACODER_AUTHENTICATION__ENVIRONMENT: Authentication environment setting
  • NOVACODER_AUTHENTICATION__COOKIE_SECURE: Cookie secure flag (true/false)
  • NOVACODER_AUTHENTICATION__COOKIE_SAMESITE: Cookie SameSite policy (lax/strict/none)
  • NOVACODER_AUTHENTICATION__SESSION_TIMEOUT: Session timeout in seconds (default: 3600)

Token Configuration

Configure token authentication in the application config:

from novacoder.config.settings import AppConfig

config = AppConfig(api={"token": "your-api-token"})

Authentication Configuration

The authentication system uses a dedicated configuration section:

from novacoder.config.settings import AppConfig, AuthenticationConfig

config = AppConfig(
    api={"token": "your-api-token"},
    authentication={
        "environment": "development",
        "cookie_secure": False,
        "cookie_httponly": True,
        "cookie_samesite": "lax",
        "session_timeout": 3600,
        "rate_limit_enabled": True,
        "rate_limit_requests": 100,
        "rate_limit_period": 60
    }
)

Or configure via config/defaults.yaml:

authentication:
  environment: development
  cookie_secure: false
  cookie_httponly: true
  cookie_samesite: lax
  session_timeout: 3600
  rate_limit_enabled: true
  rate_limit_requests: 100
  rate_limit_period: 60

Security Best Practices

  1. Use HTTPS: Always use HTTPS in production
  2. Secure Secret Keys: Use strong, random secret keys
  3. Token Expiration: Set appropriate token expiration times
  4. Token Rotation: Implement token rotation for long-lived tokens
  5. Scope Limitation: Use OAuth2 scopes to limit access
  6. Environment-Aware Security: Use appropriate security settings per environment
  7. Session Timeout: Implement session timeout for automatic logout
  8. Cookie Security: Use HttpOnly and SameSite flags for cookies
  9. Rate Limiting: Implement rate limiting on authentication endpoints
  10. CSRF Protection: Use CSRF tokens for state-changing operations
  11. Audit Logging: Track authentication attempts and failures

Session Management

Session Cookies

The authentication system uses session cookies for web interface authentication:

  • Cookie Name: novacoder_session
  • Cookie Format: token:timestamp (e.g., novacoder-secure-token-2024:1785273593)
  • HttpOnly: Prevents JavaScript access to cookies
  • SameSite: lax for better cross-site compatibility
  • Secure: Environment-aware (false in development, true in production)
  • Max-Age: Configurable session timeout (default: 3600 seconds)

Session Timeout

Sessions automatically expire after the configured timeout:

# Session timeout is checked on each authentication status check
# Expired sessions return authenticated: false with diagnostic information

Session Diagnostics

The /api/auth/status endpoint provides diagnostic information:

{
  "authenticated": true,
  "success": true,
  "diagnostics": {
    "has_session_token": true,
    "app_running": true,
    "token_configured": true,
    "cookie_present": true,
    "session_expired": false,
    "session_age": 123,
    "session_timeout": 3600
  }
}

Environment-Aware Security

The authentication system automatically adapts security settings based on the environment:

Development Environment

  • Cookie secure flag: false (allows HTTP)
  • Detailed error messages enabled
  • Full diagnostic information available
  • Authentication bypass: When authentication.environment is set to development, API authentication is bypassed for easier testing. This allows API endpoints to be called without tokens in development mode.

Production Environment

  • Cookie secure flag: true (requires HTTPS)
  • Generic error messages for security
  • Limited diagnostic information
  • Strict authentication: API tokens are required for all endpoints except /api/health.

Environment Detection

The system detects the environment using:

  • ENVIRONMENT environment variable
  • URL detection (localhost/127.0.0.1 for development)
  • Configuration file settings

API Endpoints

Login Endpoint

POST /api/auth/login

Authenticate with API token and create session.

Request Body:

{
  "token": "your-api-token"
}

Response:

{
  "success": true,
  "message": "Login successful",
  "authenticated": true,
  "session_timeout": 3600
}

Response Headers:

set-cookie: novacoder_session=token:timestamp; HttpOnly; Max-Age=3600; Path=/; SameSite=lax

Logout Endpoint

POST /api/auth/logout

Clear session and logout by invalidating the session cookie.

Response:

{
  "success": true,
  "message": "Logout successful",
  "authenticated": false
}

Cookie Deletion: The logout endpoint sends a Set-Cookie header to clear the session cookie:

set-cookie: novacoder_session=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/; SameSite=lax

Implementation Details:

  • Stateless design - no server-side session state to clear
  • Cookie deletion via Set-Cookie header with past expiration
  • Environment-aware cookie attributes (secure flag adapts to environment)
  • Client must handle UI state changes after logout

Status Endpoint

GET /api/auth/status

Check authentication status with diagnostics.

Response:

{
  "authenticated": true,
  "success": true,
  "diagnostics": {
    "has_session_token": true,
    "app_running": true,
    "token_configured": true,
    "cookie_present": true,
    "session_expired": false
  }
}

Implementation

Token enforcement lives in TokenAuthMiddleware (novacoder/api/app.py); session issue/expiry/revocation in novacoder/api/sessions.py and novacoder/api/routes_auth.py; boot-time environment validation in novacoder/api/auth.py (validate_auth_environment, warns on missing token in development, refuses to boot unauthenticated otherwise).

Dependency Handling

The live auth path has no optional dependencies, opaque session ids are secrets.token_urlsafe values, so no PyJWT/passlib requirement exists. (The dormant helpers previously documented here were removed 2026-10-13.)

Web UI Integration

The Authentication system is fully integrated into the Nova Coder Web UI with a dedicated "Authentication" navigation item under the Administration section.

Authentication UI Features

The Authentication UI provides:

  • Authentication Status Display: Shows whether the user is authenticated
  • Success Status Display: Shows the success status of the authentication check
  • Login Button: Displays a login button when the user is not authenticated
  • Session Management: Tracks authentication session status

API Endpoints Used

The Authentication UI integrates with the following API endpoint:

  • GET /api/auth/status - Check authentication status

UI Navigation

Access the Authentication UI by:

  1. Navigate to the Administration section in the sidebar
  2. Click on "Authentication"
  3. The UI displays authentication status in a grid layout

JavaScript Integration

The Authentication UI is implemented in novacoder/web/static/js/app.js with the following functions:

  • renderAuth() - Main render function for the Authentication page
  • loadAuthData() - Load and display authentication status
  • toggleAuth() - Toggle authentication state (login/logout)

Response Handling

The UI handles API responses according to the actual response structure from the auth status endpoint:

  • Auth Status Response: Expects authenticated (boolean) and success (boolean) fields
  • Authenticated Field: Indicates whether the user is currently authenticated
  • Success Field: Indicates whether the authentication check was successful

Display Format

The Authentication UI displays authentication information in a grid layout with:

  • Authenticated Status: Yes/No indicator with color coding
  • Success Status: Yes/No indicator
  • Login Button: Displayed when not authenticated, hidden when authenticated

Session Management

The Authentication UI uses session cookies for authentication:

  • Session Cookie: novacoder_session cookie stores the authentication token
  • Token Validation: Compares session token with configured API token
  • Auto-Refresh: Authentication status is checked on page load and navigation

Record 08 / 48 // Part II · APIs

API GraphQL

Strawberry GraphQL schema and auth · source wiki/api-graphql.md

The Nova Coder API provides a GraphQL endpoint for flexible data queries, complementing the REST API with field selection and nested queries.

Overview

GraphQL allows clients to request exactly the data they need in a single request, reducing over-fetching and under-fetching. The GraphQL endpoint is available at /graphql when the strawberry-graphql package is installed.

Installation

Install the optional GraphQL dependency:

pip install novacoder[api]
# or
pip install strawberry-graphql>=0.239.0

Availability

The GraphQL endpoint is only available when strawberry-graphql is installed. If not installed, the endpoint will not be registered and the API will continue to function with REST endpoints only.

Check availability:

from novacoder.api.graphql import is_graphql_available

if is_graphql_available():
    print("GraphQL is available")
else:
    print("GraphQL is not available (install strawberry-graphql)")

GraphQL Endpoint

  • URL: /graphql
  • Method: POST
  • Content-Type: application/json

Available Queries

Agents

query {
  agents {
    name
    description
  }
}

Get a specific agent:

query {
  agent(name: "coder") {
    name
    description
  }
}

Tools

query {
  tools {
    name
    description
  }
}

Get a specific tool:

query {
  tool(name: "read_file") {
    name
    description
  }
}

Memory

Get all memory entries:

query {
  memory {
    key
    scope
    value
    createdAt
  }
}

Filter by scope:

query {
  memory(scope: "default") {
    key
    scope
    value
    createdAt
  }
}

Limit results:

query {
  memory(limit: 10) {
    key
    scope
    value
  }
}

Files

Get workspace files:

query {
  files {
    path
    size
    modifiedAt
  }
}

Limit results:

query {
  files(limit: 50) {
    path
    size
    modifiedAt
  }
}

Status

query {
  status
}

Available Mutations

Run Agent

mutation {
  runAgent(
    agent: "coder"
    goal: "Write a Flask API"
    context: "Optional context"
  )
}

Store Memory

mutation {
  storeMemory(
    key: "my_key"
    value: "my_value"
    scope: "default"
  )
}

Delete Memory

mutation {
  deleteMemory(
    key: "my_key"
    scope: "default"
  )
}

Usage Examples

Using curl

curl -X POST http://localhost:8000/graphql \
  -H "Content-Type: application/json" \
  -d '{
    "query": "query { agents { name description } }"
  }'

Using Python

import httpx

query = """
query {
  agents {
    name
    description
  }
}
"""

response = httpx.post(
    "http://localhost:8000/graphql",
    json={"query": query}
)

data = response.json()
print(data)

Using JavaScript (fetch)

const query = `
  query {
    agents {
      name
      description
    }
  }
`;

fetch('http://localhost:8000/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ query }),
})
  .then(res => res.json())
  .then(data => console.log(data));

GraphQL Playground

When the GraphQL endpoint is available, you can access the GraphQL Playground at:

  • URL: /graphql
  • Interactive UI: Available through the Strawberry GraphQL explorer

Implementation

The GraphQL system is implemented in novacoder/api/graphql.py:

from novacoder.api.graphql import (
    is_graphql_available,
    get_graphql_router,
    create_graphql_router,
)

GraphQL Types

GraphQLAgent

  • name: String
  • description: String

GraphQLTool

  • name: String
  • description: String

GraphQLMemory

  • key: String
  • scope: String
  • value: String
  • createdAt: DateTime

GraphQLFile

  • path: String
  • size: Int
  • modifiedAt: DateTime

Integration with FastAPI

The GraphQL router is automatically registered with the FastAPI app when strawberry-graphql is available:

from novacoder.api.app import app

# GraphQL router is automatically included at /graphql
# if strawberry-graphql is installed

Error Handling

GraphQL errors are returned in the standard GraphQL error format:

{
  "data": null,
  "errors": [
    {
      "message": "Error message",
      "locations": [{"line": 2, "column": 3}]
    }
  ]
}

Authentication

The GraphQL endpoint respects the same authentication as the REST API:

  • Header: X-API-Token
  • Cookie: novacoder_session
  • Query Parameter: token
curl -X POST http://localhost:8000/graphql \
  -H "Content-Type: application/json" \
  -H "X-API-Token: your-token" \
  -d '{"query": "query { agents { name } }"}'

Best Practices

  1. Field Selection: Request only the fields you need to reduce payload size
  2. Batch Queries: Combine multiple queries into a single request
  3. Use Variables: Use GraphQL variables for dynamic values
  4. Error Handling: Always check for errors in the response
  5. Introspection: Use GraphQL introspection to explore the schema
  6. Caching: Cache GraphQL responses when appropriate
  7. Rate Limiting: Respect rate limits when making queries

Schema Introspection

Explore the GraphQL schema using introspection:

query {
  __schema {
    types {
      name
      kind
      description
      fields {
        name
        type {
          name
          kind
        }
      }
    }
  }
}

Debugging Status

✅ Verified Working: All GraphQL components have been debugged and verified:

  • GraphQL module imports work correctly
  • GraphQL availability check works correctly
  • GraphQL router creation works correctly
  • API module export works correctly
  • App integration works correctly
  • No import conflicts with existing systems
  • Graceful degradation when strawberry-graphql is not installed

Record 09 / 48 // Part II · APIs

API WebSocket Support

Realtime channels and subprotocols · source wiki/api-websockets.md

The Nova Coder API supports WebSocket connections for real-time updates and streaming.

Overview

WebSocket support enables real-time bidirectional communication between clients and the server, allowing for live updates, streaming responses, and efficient push notifications. The enhanced WebSocket system includes connection metadata tracking, room management for collaboration, and timestamp tracking for all messages.

WebSocket Endpoints

Chat WebSocket

  • Endpoint: ws://localhost:8000/ws/chat?user_id={id}
  • Purpose: Real-time chat streaming
  • Channel: chat
  • Parameters: user_id (optional) - User identifier for connection tracking

Agents WebSocket

  • Endpoint: ws://localhost:8000/ws/agents?user_id={id}
  • Purpose: Real-time agent execution updates
  • Channel: agents
  • Parameters: user_id (optional) - User identifier for connection tracking

Workspace WebSocket

  • Endpoint: ws://localhost:8000/ws/workspace?user_id={id}
  • Purpose: Real-time workspace updates
  • Channel: workspace
  • Parameters: user_id (optional) - User identifier for connection tracking

System WebSocket

  • Endpoint: ws://localhost:8000/ws/system?user_id={id}
  • Purpose: Real-time system monitoring
  • Channel: system
  • Parameters: user_id (optional) - User identifier for connection tracking

Authentication

WebSocket connections require authentication, the HTTP token middleware does not cover /ws/*, so the handshake itself is checked in routes_websocket.py:

  • Session cookie: a valid novacoder_session cookie (set by POST /api/auth/login) is accepted automatically for same-origin clients, this is how the React SPA authenticates.
  • Token: the API token may be supplied via the token query parameter or the x-api-token / Authorization: Bearer handshake headers.
  • Unauthenticated handshakes are rejected with HTTP 403 before the socket opens.

Event Delivery

api/websocket.py bridges the kernel EventBus into channel clients during the lifespan (wire_event_bus(loop)):

  • Channel routing: AgentRun*/Workflow* events → agents; Index*/Workspace* events → workspace; Service*/Application* events → system; chat/messages → chat.
  • History replay: the most recent events per channel are replayed to new subscribers on connect.
  • Burst coalescing: rapid-fire events are coalesced so bursty services cannot flood clients; suppressed events arrive as an aggregate count.
  • Connection metadata: each socket receives a connected welcome frame containing connection_id, channel, and timestamps.
  • Real progress events: AgentRunStarted, WorkflowExecutionStarted/Completed/Failed, and IndexScanStarted are published from the API entry points (routes_agents.py, routes_workflows_2.py, routes_indexing.py).

React consumption

novacoder/web/react/src/hooks/useEventStream.ts wraps reconnect/auth/state for SPA pages and is consumed by the Layout topbar (live indicator), Indexing/Workspace (scan progress), Workflows/Agents (execution feed), and System (service lifecycle) pages. Polling remains as fallback.

WebSocket Channels

The system uses predefined channels for different types of updates:

  • chat: Chat messages and streaming responses
  • agents: Agent execution updates
  • workspace: Workspace changes and scan results
  • memory: Memory updates
  • system: System health and metrics
  • tools: Tool execution updates
  • collaboration: Real-time collaboration features (NEW)
  • dashboard: Real-time dashboard updates (NEW)
  • notifications: Real-time notifications (NEW)

Enhanced Features

Connection Metadata Tracking

Each WebSocket connection is tracked with metadata:

{
    "connection_id": "uuid",
    "channel": "chat",
    "user_id": "user_abc123",
    "connected_at": "2024-01-01T00:00:00Z",
    "last_activity": "2024-01-01T00:00:00Z"
}

Room Management

The WebSocket manager supports room-based collaboration:

# Join a room
await manager.join_room(websocket, room_id="session_123", user_id="user_abc")

# Leave a room
await manager.leave_room(websocket, room_id="session_123", user_id="user_abc")

# Send message to room
await manager.send_to_room({"type": "update", "data": {...}}, room_id="session_123")

Timestamp Tracking

All messages include automatic timestamps:

{
    "type": "message",
    "content": "Hello",
    "timestamp": "2024-01-01T00:00:00Z"
}

Usage Examples

Basic WebSocket Connection

const ws = new WebSocket('ws://localhost:8000/ws/chat?user_id=user_123');

ws.onopen = () => {
    console.log('WebSocket connected');
    ws.send(JSON.stringify({ message: 'Hello' }));
};

ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Received:', data);
};

ws.onerror = (error) => {
    console.error('WebSocket error:', error);
};

ws.onclose = () => {
    console.log('WebSocket disconnected');
};

Using the WebSocket Client Library

// Get a client for a specific channel
const chatClient = WebSocketManager.getClient('chat');

// Register message handlers
chatClient.on('connected', (data) => {
    console.log('Connected:', data);
});

chatClient.on('message', (message) => {
    console.log('Received:', message);
});

// Send a message
chatClient.send({ type: 'message', content: 'Hello' });

// Disconnect
chatClient.disconnect();

Collaboration Room Example

const collabClient = WebSocketManager.getClient('collaboration');

// Join a collaboration session
collabClient.joinSession('session_123');

// Send cursor updates
collabClient.sendCursorUpdate('session_123', { line: 10, column: 5 });

// Send edits
collabClient.sendEdit('session_123', {
    type: 'text',
    range: { start: 0, end: 10 },
    text: 'replacement'
});

// Leave session
collabClient.leaveSession('session_123');

Python WebSocket Client

import asyncio
import websockets
import json

async def chat_websocket():
    uri = "ws://localhost:8000/ws/chat?user_id=user_123"
    async with websockets.connect(uri) as websocket:
        # Send message
        await websocket.send(json.dumps({"message": "Hello"}))
        
        # Receive response
        response = await websocket.recv()
        data = json.loads(response)
        print(f"Received: {data}")

asyncio.run(chat_websocket())

Message Format

Client to Server

{
    "type": "message",
    "content": "Your message here"
}

Server to Client

{
    "type": "chat_chunk",
    "content": "Partial response",
    "timestamp": "2024-01-01T00:00:00Z"
}

Connection Welcome Message

{
    "type": "connected",
    "connection_id": "uuid",
    "channel": "chat",
    "timestamp": "2024-01-01T00:00:00Z"
}

Room Messages

{
    "type": "user_joined",
    "room_id": "session_123",
    "user_id": "user_abc",
    "member_count": 3,
    "timestamp": "2024-01-01T00:00:00Z"
}

Implementation

The WebSocket support is implemented via the enhanced WebSocketManager in novacoder/api/websocket.py:

from novacoder.api.websocket import WebSocketManager, WebSocketChannels

manager = WebSocketManager()

# Connect with user tracking
connection_id = await manager.connect(websocket, channel="chat", user_id="user_123")

# Get connection info
info = manager.get_connection_info(websocket)

# Get all connections in a channel
connections = manager.get_channel_connections("chat")

Connection Management

The WebSocket manager handles:

  • Connection lifecycle (connect/disconnect)
  • Connection metadata tracking (connection_id, user_id, timestamps)
  • Channel-based message routing
  • Broadcasting to multiple clients with exclude option
  • Personal messaging to specific clients
  • Room management for collaboration
  • Connection count tracking
  • Connection info retrieval

WebSocket Client Library

The JavaScript WebSocket client library provides:

  • Base WebSocketClient: Automatic reconnection with exponential backoff
  • Channel-specific clients: Chat, Agent, Workspace, System, Collaboration, Dashboard, Notification
  • Message handlers: Register handlers for specific message types
  • Room management: Join/leave rooms, send messages to rooms
  • Connection state tracking: Monitor connection status
  • Global WebSocketManager: Manage multiple connections

See WebSocket Client Library for detailed documentation.

Security

WebSocket connections inherit the same authentication as HTTP endpoints. Use the same token-based authentication when establishing WebSocket connections. The user_id parameter is optional and defaults to "anonymous" if not provided.

Debugging Status

✅ Verified Working: All WebSocket components have been debugged and verified:

  • WebSocketManager class works correctly
  • WebSocketChannels constants work correctly
  • Connection management works correctly
  • Channel-based broadcasting works correctly
  • Connection metadata tracking works correctly
  • Room management for collaboration works correctly
  • Timestamp tracking works correctly
  • 4 WebSocket endpoints registered in _routes.py
  • No import conflicts with existing systems
  • Integration with FastAPI works correctly

Record 10 / 48 // Part II · APIs

API Rate Limiting

In-memory limiter and governed paths · source wiki/api-rate-limiting.md

The Nova Coder API supports enhanced rate limiting with configurable limits, whitelist/blacklist support, and graceful dependency handling.

Overview

Rate limiting protects the API from abuse and ensures fair resource allocation. The enhanced rate limiting system uses a token bucket algorithm with configurable limits and supports both in-memory and slowapi-based implementations.

Features

Token Bucket Algorithm

  • Configurable burst limits and refill rates
  • Automatic token replenishment over time
  • Temporary blocking for exceeded limits
  • Retry-after headers for blocked clients

Whitelist/Blacklist

  • Whitelist for unlimited access (e.g., internal services)
  • Blacklist for blocking abusive clients
  • Dynamic management of lists
  • Per-client statistics

Configuration

  • Environment-based configuration
  • Configurable rate limits and burst limits
  • TTL settings for rate limit windows
  • Enable/disable features as needed

Configuration

Environment Variables

  • API_RATE_LIMIT: Default rate limit (default: "100/minute")
  • API_BURST_LIMIT: Maximum burst size (default: 10)
  • API_RATE_LIMIT_TTL: Time-to-live for rate limit windows (default: 60 seconds)

Configuration Class

from novacoder.api.rate_limit import RateLimitConfig

config = RateLimitConfig(
    rate_limit="100/minute",
    burst_limit=10,
    ttl=60,
    enable_whitelist=True,
    enable_blacklist=True
)

Usage Examples

Basic Rate Limiting

from novacoder.api.rate_limit import in_memory_limiter, get_client_id

# Check if request is allowed
client_id = get_client_id(request)
allowed, info = in_memory_limiter.check_rate_limit(client_id)

if not allowed:
    return JSONResponse(
        {"error": "Rate limit exceeded", "retry_after": info.get("retry_after")},
        status_code=429
    )

Whitelist Management

from novacoder.api.rate_limit import in_memory_limiter

# Add client to whitelist
in_memory_limiter.add_to_whitelist("203.0.113.100")

# Remove from whitelist
in_memory_limiter.remove_from_whitelist("203.0.113.100")

# Check if whitelisted
if in_memory_limiter.is_whitelisted("203.0.113.100"):
    # Allow unlimited requests
    pass

Blacklist Management

from novacoder.api.rate_limit import in_memory_limiter

# Add client to blacklist
in_memory_limiter.add_to_blacklist("203.0.113.200")

# Remove from blacklist
in_memory_limiter.remove_from_blacklist("203.0.113.200")

# Check if blacklisted
if in_memory_limiter.is_blacklisted("203.0.113.200"):
    # Block all requests
    pass

Rate Limit Statistics

from novacoder.api.rate_limit import in_memory_limiter

# Get rate limiting statistics
stats = in_memory_limiter.get_stats()
print(f"Total clients: {stats['total_clients']}")
print(f"Whitelisted: {stats['whitelisted_clients']}")
print(f"Blacklisted: {stats['blacklisted_clients']}")
print(f"Blocked: {stats['blocked_clients']}")

Implementation

The rate limiting system is implemented in novacoder/api/rate_limit.py:

from novacoder.api.rate_limit import (
    RateLimitConfig,
    InMemoryRateLimiter,
    check_rate_limit_middleware
)

Dependency Handling

The system gracefully handles the slowapi dependency:

  • If slowapi is available, it uses the library for enhanced rate limiting
  • If not available, it falls back to the in-memory implementation
  • No breaking changes if the dependency is missing

Debugging Status

✅ Verified Working: All rate limiting components have been debugged and verified:

  • RateLimitConfig initializes correctly with all parameters
  • InMemoryRateLimiter implements token bucket algorithm correctly
  • Whitelist/blacklist management works correctly
  • Rate limit checking returns proper allowed/denied responses
  • Statistics tracking works correctly
  • Graceful handling of missing slowapi dependency
  • No import conflicts with existing systems

Best Practices

  1. Set Appropriate Limits: Configure limits based on your API capacity
  2. Use Whitelists: Whitelist trusted services that need higher limits
  3. Monitor Statistics: Regularly check rate limiting statistics
  4. Handle 429 Responses: Clients should respect retry-after headers
  5. Test Limits: Test rate limiting in staging before production

Record 11 / 48 // Part II · APIs

API Error Codes

Error shapes and status codes · source wiki/api-error-codes.md

This document provides a comprehensive reference for all error codes used in the Nova Coder API.

Error Response Format

All error responses follow a standardized format:

{
  "success": false,
  "error": "Error message description",
  "error_code": "ERROR_CODE",
  "details": {}
}

Error Codes by Category

Application Errors

Error Code HTTP Status Description
APP_NOT_RUNNING 503 The Nova Coder application is not running. Start the application before making API requests.
SERVICE_UNAVAILABLE 503 A required service is not available.

Authentication & Authorization Errors

Error Code HTTP Status Description
UNAUTHORIZED 401 Authentication required or invalid credentials.
FORBIDDEN 403 User does not have permission to perform this action.
INVALID_TOKEN 401 The provided authentication token is invalid.
TOKEN_EXPIRED 401 The authentication token has expired.

Request Validation Errors

Error Code HTTP Status Description
INVALID_REQUEST 400 The request is invalid or missing required parameters.
INVALID_PAGINATION 400 Pagination parameters are invalid.
INVALID_RATING 400 Rating must be between 1 and 5.
INVALID_FIELDS 400 Invalid field names in field selection.

Resource Not Found Errors

Error Code HTTP Status Description
AGENT_NOT_FOUND 404 The specified agent does not exist.
JOB_NOT_FOUND 404 The specified job does not exist.
DATASET_NOT_FOUND 404 The specified dataset does not exist.
DASHBOARD_NOT_FOUND 404 The specified dashboard does not exist.
THREAT_NOT_FOUND 404 The specified security threat does not exist.
RULE_NOT_FOUND 404 The specified alert rule does not exist.
ALERT_NOT_FOUND 404 The specified alert does not exist.
WEBHOOK_NOT_FOUND 404 The specified webhook does not exist.

AI Service Errors

Error Code HTTP Status Description
AI_SERVICE_NOT_AVAILABLE 503 The AI service is not available.
MULTIMODAL_ERROR 500 Error processing multimodal request.
BATCH_ERROR 500 Error processing batch request.
ERROR_HANDLING_ERROR 500 Error in error handling system.
FINE_TUNING_ERROR 500 Error in fine-tuning operation.

Security Errors

Error Code HTTP Status Description
SECURITY_NOT_AVAILABLE 503 Security service is not available.
SECURITY_ERROR 500 Error in security operation.

Monitoring Errors

Error Code HTTP Status Description
MONITORING_ERROR 500 Error in monitoring operation.
MONITORING_NOT_AVAILABLE 503 Monitoring service is not available.

Agent Marketplace Errors

Error Code HTTP Status Description
MARKETPLACE_ERROR 500 Error in agent marketplace operation.
INSTALLATION_ERROR 500 Error installing agent from marketplace.
RATING_ERROR 500 Error submitting agent rating.

Gateway Errors

Error Code HTTP Status Description
GATEWAY_STATUS_ERROR 500 Error retrieving gateway status.
GATEWAY_METRICS_ERROR 500 Error retrieving gateway metrics.
GATEWAY_SERVICE_ERROR 500 Error retrieving gateway service status.
GATEWAY_CONFIG_ERROR 500 Error configuring gateway.
GATEWAY_ROUTE_ERROR 500 Error adding gateway route.
GATEWAY_SERVICE_REGISTER_ERROR 500 Error registering gateway service.

Tools Errors

Error Code HTTP Status Description
TOOLS_ERROR 500 Error in tools operation.

Dashboard Errors

Error Code HTTP Status Description
DASHBOARD_ERROR 500 Error in dashboard operation.

Rate Limiting Errors

Error Code HTTP Status Description
RATE_LIMIT_EXCEEDED 429 Rate limit has been exceeded.

CSRF Errors

Error Code HTTP Status Description
CSRF_TOKEN_MISSING 403 CSRF token is missing from request.
CSRF_TOKEN_INVALID 403 CSRF token is invalid.

HTTP Status Codes

Status Code Description
200 Success
400 Bad Request - Invalid request parameters
401 Unauthorized - Authentication required
403 Forbidden - Permission denied
404 Not Found - Resource not found
429 Too Many Requests - Rate limit exceeded
500 Internal Server Error - Server error
503 Service Unavailable - Service not running

Error Handling Best Practices

  1. Always Check success Field: The success boolean field indicates whether the request succeeded.
  2. Handle Error Codes: Use the error_code field to programmatically handle specific error conditions.
  3. Log Error Details: The details field may contain additional debugging information.
  4. Implement Retry Logic: For 5xx errors, implement exponential backoff retry logic.
  5. Validate Input: Check request parameters before sending to avoid 400 errors.
  6. Handle Rate Limits: Implement proper handling for 429 errors with appropriate backoff.

Example Error Handling

import requests

response = requests.get("http://localhost:8000/api/agents")
data = response.json()

if not data.get("success"):
    error_code = data.get("error_code")
    error_message = data.get("error")
    
    if error_code == "APP_NOT_RUNNING":
        print("Application not running. Please start the application.")
    elif error_code == "RATE_LIMIT_EXCEEDED":
        print("Rate limit exceeded. Please wait before retrying.")
    elif error_code == "AGENT_NOT_FOUND":
        print("Agent not found. Please check the agent name.")
    else:
        print(f"Error: {error_message} (Code: {error_code})")
else:
    print("Request successful!")

Record 12 / 48 // Part II · APIs

API Versioning

Version negotiation · source wiki/api-versioning.md

The Nova Coder API supports versioning to enable evolution of the API without breaking existing clients.

Overview

API versioning allows the API to evolve over time while maintaining backward compatibility with existing clients. The system supports version specification via URL path or HTTP headers.

Versioning Strategy

Correction (2026-11): APIVersionMiddleware detects a version from the URL path (/api/vN/...), header, or query param and records it on request.state.api_version, but it does not rewrite the path and no /api/vN/* routes are registered — POST /api/v1/chat 404s. In practice, versioning is metadata-only: every real endpoint lives at the unversioned /api/* path and every supported version string resolves to the same handlers. Use header/query versioning (or nothing) and call /api/chat.

URL Path Detection

The middleware recognizes a version embedded in the URL path (/api/v1/..., /api/v2/...) for validation and response headers — but those paths are not routable; only v1 is supported and v2 is rejected with 400.

Header Versioning

Include the version in the X-API-Version header:

X-API-Version: v1

Default Version

If no version is specified, the system defaults to v1.

Supported Versions

  • v1: Current stable version
  • Future versions will be added as needed

Version Lifecycle

  1. Stable: Production-ready version
  2. Deprecated: Version marked for future removal
  3. Retired: Version no longer supported

Migration Guide

When a new version is released:

  1. Review the changelog for breaking changes
  2. Update your API calls to use the new version
  3. Test your integration with the new version
  4. Migrate before the old version is retired

Usage Examples

Using URL Path Versioning

import httpx

# The only supported version is the default — just call the unversioned path
response = httpx.post("http://localhost:8000/api/chat", json={
    "message": "Hello"
})

Using Header Versioning

import httpx

# Use header versioning
response = httpx.post("http://localhost:8000/api/chat", 
    json={"message": "Hello"},
    headers={"X-API-Version": "v1"}
)

Implementation

The API versioning is implemented via the APIVersionMiddleware in novacoder/api/versioning.py:

from novacoder.api.versioning import APIVersionMiddleware

app.add_middleware(
    APIVersionMiddleware,
    default_version="v1",
    supported_versions=["v1"]
)

Record 13 / 48 // Part II · APIs

API Modular Routes System

Route module registration contract · source wiki/api-modular-routes.md

Overview

The Nova Coder API has been refactored from a monolithic _routes.py file (349KB, 8540 lines) into a modular route system organized by feature.

Route Modules

routes_common.py

Common utilities shared across all route modules:

  • Response helpers (success_response, error_response, paginated_response)
  • CSRF token management (generate_csrf_token, validate_csrf_token, set_csrf_cookie)
  • CSRF protection decorator (require_csrf)
  • Rate limiting decorator (rate_limit)

routes_auth.py

Authentication and session management:

  • GET /api/auth/csrf-token - Generate CSRF token
  • POST /api/auth/login - Authenticate and create session
  • POST /api/auth/logout - Clear session
  • GET /api/auth/status - Check authentication status

routes_chat.py

Chat and messaging:

  • GET /api/chat/history - Get chat history
  • POST /api/chat - Send message to agent
  • POST /api/chat/clear - Clear chat history

routes_system.py

System status and health:

  • GET /api/rate-limit/status - Rate limiting status
  • GET /api/rate-limit/config - Rate limiting config
  • GET /api/rate-limit/stats - Rate limiting stats
  • GET /api/status - Application status
  • GET /api/health - Detailed health metrics

routes_web.py

Web UI:

  • GET / - Serve web dashboard

routes_webhooks.py

Webhook management:

  • POST /api/webhooks - Create webhook
  • GET /api/webhooks - List webhooks
  • GET /api/webhooks/{webhook_id} - Get webhook
  • DELETE /api/webhooks/{webhook_id} - Delete webhook
  • GET /api/webhooks/stats - Webhook statistics

routes_ai.py

AI system features:

  • POST /api/ai/multimodal/process - Process multimodal messages
  • GET /api/ai/multimodal/config - Multimodal configuration
  • POST /api/ai/multimodal/enable - Enable multimodal
  • POST /api/ai/multimodal/disable - Disable multimodal
  • GET /api/ai/systems/status - AI systems status
  • POST /api/ai/batch/request - Add batch request
  • POST /api/ai/batch/process - Process batch
  • GET /api/ai/batch/metrics - Batch metrics
  • POST /api/ai/error-handling/fallback - Register fallback
  • POST /api/ai/error-handling/circuit-breaker/reset - Reset circuit breaker
  • POST /api/ai/rag/store - Store RAG document
  • GET /api/ai/rag/search - Search RAG store
  • GET /api/ai/rag/documents - List RAG documents
  • DELETE /api/ai/rag/documents/{key} - Delete RAG document
  • POST /api/ai/rag/clear - Clear RAG store
  • POST /api/ai/rag/generate - Generate RAG response

routes_agents.py

Agent management:

  • GET /api/agents - List agents (paginated)
  • POST /api/agents/run - Run agent task
  • GET /api/agent-features/config - Get features config
  • POST /api/agent-features/config - Update features config
  • GET /api/agent-features/status - Get features status
  • POST /api/agent-features/enable - Enable feature
  • POST /api/agent-features/disable - Disable feature

routes_analytics.py

API analytics dashboard:

  • GET /api/analytics-api/summary - Get comprehensive analytics summary
  • GET /api/analytics-api/endpoint-stats - Get statistics for specific endpoint (optional endpoint query parameter; accepts a full metric key or a plain path and aggregates across HTTP methods)
  • GET /api/analytics-api/time-series - Get time series analytics data
  • GET /api/analytics-api/error-analysis - Get error analysis data
  • GET /api/analytics-api/performance - Get performance metrics
  • GET /api/analytics-api/clients - Get client analytics
  • POST /api/analytics-api/clear - Clear all analytics data
  • GET /api/analytics-api/status - Get analytics system status

Integration

All modules are registered in app.py:

import novacoder.api.routes_common
import novacoder.api.routes_auth
import novacoder.api.routes_chat
import novacoder.api.routes_system
import novacoder.api.routes_web
import novacoder.api.routes_webhooks
import novacoder.api.routes_ai
import novacoder.api.routes_agents
import novacoder.api.routes_analytics
import novacoder.api._routes  # Remaining routes

Benefits

  • Maintainability: Smaller, focused files
  • Collaboration: Reduced merge conflicts
  • Testing: Better test isolation
  • Documentation: Clear feature organization

Status

✅ All 9 modules implemented and tested ✅ 342 routes registered (after duplicate removal, gateway additions, and analytics addition) ✅ No import conflicts or errors ✅ UI integration verified ✅ Gateway management endpoints added (6 new routes) ✅ Analytics API dashboard endpoints added (8 new routes)

Record 14 / 48 // Part III · Intelligence

Agents

Multi-agent hierarchy and built-ins · source wiki/agents.md

Nova Coder uses a multi-agent system instead of a single monolithic prompt. Specialist agents collaborate through the event bus and are coordinated by the AgentManager.

Agent Hierarchy

Manager
  ↓
Planner
  ↓
Architect
  ↓
Coder
  ↓
Reviewer
  ↓
Tester
  ↓
Debugger
  ↓
Documenter

Base Agent

Every agent extends Agent and receives optional service references:

from novacoder.agents.agent import Agent, AgentTask, AgentResult

class MyAgent(Agent):
    name = "my_agent"
    description = "Does something useful."

    async def run(self, task: AgentTask) -> AgentResult:
        return AgentResult(
            success=True,
            output={},
            summary=f"Completed {task.goal}",
        )

Agent may be constructed with ai, tools, memory, workspace, and communication_protocol references. AgentService.initialize() injects these services from the kernel container. A synchronous wrapper, run_sync(), is available for non-async callers.

During a run, AgentManager sets a SessionContext on the agent via agent.set_session_context(). The agent can access it through self.session_context to read or write session-scoped memory. Agents can also communicate with each other through the communication_protocol if enabled.

Built-in Agents

Agent Responsibility
chat Provides fast conversational responses for quick interactions
planner Breaks goals into executable plans
architect Explores project structure and designs implementation approaches
coder Generates and edits code
reviewer Reviews code for quality and safety
tester Plans and executes tests to verify code changes
debugger Analyzes errors and proposes debugging steps
documentation Drafts and updates project documentation
security Scans code for vulnerabilities and security anti-patterns
performance Analyzes and optimizes code performance
devops Handles deployment, CI/CD, and infrastructure
database Database schema design, migrations, and queries
mobile Mobile app development (iOS, Android)
ui_ux User interface and experience design
data_science Data analysis, ML model development
api_design API design, documentation, and testing
compliance Regulatory compliance checking
git Manages Git version control operations including commits, branches, merges, and conflict resolution

Note: The default built-in set in the AgentService includes the core agents plus documentation and security. Advanced/specialized agents (performance, devops, database, mobile, ui_ux, data_science, api_design, compliance, git) are disabled by default and can be enabled through AgentsConfig or by explicitly calling AgentManager.register().

AgentTask

Tasks carry the context an agent needs:

from novacoder.agents.agent import AgentTask

task = AgentTask(
    id="task-1",
    description="Add OAuth login",
    goal="Add OAuth login",
    context={"framework": "flask"},
    priority=1,
)

AgentManager

AgentManager registers and dispatches agents. Both async and sync runners are available:

from novacoder.agents.manager import AgentManager

manager = AgentManager()
print(manager.list_agents())

# Synchronous entry point
result = manager.run("planner", task)

# Asynchronous entry point
result = await manager.run_async("planner", task)
print(result.success, result.summary)

Advanced AgentManager Features

The AgentManager supports several advanced systems that can be enabled or disabled:

manager = AgentManager(
    memory_service=None,
    enable_communication=True,      # Enable agent-to-agent communication
    enable_learning=True,           # Enable performance tracking and learning
    enable_testing=True,             # Enable agent testing framework
    enable_recovery=True,            # Enable error recovery system
    enable_state_management=True,    # Enable agent state management
    enable_monitoring=True,          # Enable agent monitoring
    enable_security_validation=True,  # Enable agent security validation
    enable_cost_tracking=True,       # Enable agent cost tracking
    enable_collaboration=True,       # Enable agent collaboration patterns
    enable_marketplace=True,         # Enable agent marketplace
    enable_versioning=True,          # Enable agent versioning
    enable_sandboxing=True,          # Enable agent sandboxing
    enable_task_distribution=True,   # Enable intelligent task distribution
    enable_access_control=True,      # Enable role-based access control
    enable_input_validation=True,    # Enable input validation
    enable_pooling=True,             # Enable agent pooling
    enable_execution_pool=True,      # Enable execution pool management
    enable_memory_management=True,   # Enable memory management
    enable_profiling=True,           # Enable agent profiling
)
  • Communication Protocol: Enables agents to send messages to each other, delegate tasks, and hand off work
  • Learning System: Tracks agent performance and provides recommendations for improvement
  • Orchestrator: Provides multiple strategies for multi-agent workflow execution (sequential, parallel, dynamic, etc.)
  • Testing Framework: Comprehensive testing infrastructure for validating agent behavior
  • Error Recovery: Automatic error classification and recovery strategies
  • State Management: Persistent agent state storage with checkpointing and task resumption
  • Monitoring: Agent execution tracing, performance metrics, and anomaly detection
  • Security Validation: Agent action validation with security policies and audit logging
  • Cost Tracking: Per-agent cost monitoring with budgeting and optimization recommendations
  • Collaboration: Multiple collaboration patterns for complex multi-agent workflows
  • Marketplace: Agent sharing and discovery system with packaging, search, and reviews
  • Versioning: Semantic versioning for agent configurations with rollback capabilities
  • Sandboxing: Secure isolated execution environments with resource limits
  • Task Distribution: Intelligent load balancing and capability-based task assignment
  • Access Control: Role-based access control with permissions and policies
  • Input Validation: Comprehensive input validation with security checks
  • Agent Pooling: Agent pooling with lazy initialization and load balancing
  • Execution Pool: Concurrent task execution with retry logic and queuing
  • Memory Management: Memory usage tracking, limits, and garbage collection
  • Profiling: Function call tracing and performance analysis
  • Performance Optimization: Performance metrics tracking, optimization suggestions, and result management
  • Documentation Automation: Automatic documentation generation with templates and multiple output formats

Access these systems through the manager:

# Communication
protocol = manager.communication_protocol
await protocol.send_message('agent1', 'agent2', MessageType.NOTIFICATION, {'data': 'value'})

# Learning
metrics = manager.get_agent_metrics('coder')
recommendations = manager.get_learning_recommendations('coder')

# Orchestration
orchestrator = manager.orchestrator
orchestrator.set_strategy(OrchestrationStrategy.PARALLEL)

# Testing
framework = manager.test_framework
suite = framework.create_test_suite('coder')

# Error Recovery
recovery = manager.error_recovery
stats = manager.get_error_statistics('coder')

# State Management
state_manager = manager.state_manager
summary = manager.get_state_summary('coder')

# Monitoring
monitoring = manager.monitoring
perf_summary = manager.get_performance_summary('coder')

# Security Validation
security_validator = manager.security_validator
sec_summary = manager.get_security_summary('coder')

# Cost Tracking
cost_tracker = manager.cost_tracker
cost_summary = manager.get_cost_summary('coder')

# Collaboration
collaboration = manager.collaboration
result = await collaboration.execute_swarm('Write code', 'Generate code', ['coder', 'architect'])

# Marketplace
marketplace = manager.marketplace
stats = manager.get_marketplace_statistics()

# Versioning
version_manager = manager.version_manager
history = manager.get_version_history('coder')

# Sandboxing
sandbox_manager = manager.sandbox_manager
sandbox_stats = manager.get_sandbox_statistics()

# Task Distribution
task_distributor = manager.task_distributor
dist_stats = manager.get_distribution_statistics()

# Access Control
access_control = manager.access_control
has_permission = access_control.check_permission('coder', PermissionType.READ, '/path/to/file')

# Input Validation
input_validator = manager.input_validator
validation_result = input_validator.validate({'data': 'value'}, 'agent_input')

# Agent Pooling
pool_manager = manager.pool_manager
pool_stats = pool_manager.get_statistics()

# Execution Pool
execution_pool_manager = manager.execution_pool_manager
exec_stats = execution_pool_manager.get_statistics()

# Memory Management
memory_manager = manager.memory_manager
mem_stats = memory_manager.get_statistics()

# Profiling
profiler = manager.profiler
prof_stats = profiler.get_statistics()

# Performance Optimization
performance_optimizer = manager.performance_optimizer
perf_stats = performance_optimizer.get_statistics()

# Documentation Automation
documentation_automation = manager.documentation_automation
doc_summary = documentation_automation.get_documentation_summary()

TUI Integration

The Agent System is integrated into the Terminal User Interface (TUI) through the Agents page.

Agent Monitoring in TUI

The TUI provides enhanced agent monitoring capabilities:

  • Performance Metrics Display: Real-time display of total runs, success rate, average cost, and active tasks
  • Per-Agent Metrics: Each agent in the table shows runs, success rate, and average cost
  • Detailed Metrics View: Button to view detailed performance metrics for selected agent
  • Automatic Refresh: Metrics automatically refresh after agent execution

Agent Versioning in TUI

The TUI provides agent version management capabilities:

  • Version History: View all versions of an agent with status and creation date
  • Active Version Display: Shows currently active version for each agent
  • Changelog View: Display change log for each version
  • Rollback Support: Support for rolling back to previous versions via TUI

TUI Usage

Access agent monitoring and versioning in the TUI:

  • Navigate to the Agents page
  • View performance metrics at the top of the page
  • Click "View Metrics" to see detailed metrics for selected agent
  • Click "Version History" to view version history and changelog

Agent Collaboration in TUI

The TUI provides agent collaboration pattern execution:

  • Collaboration Patterns: 8 pattern types (Swarm, Hierarchical, Peer Review, Debate, Consensus, Chain of Thought, Divide and Conquer, Specialist Pool)
  • Multi-Agent Execution: Execute tasks with multiple agents working together
  • Pattern Selection: Choose the appropriate collaboration pattern for the task
  • Agent Selection: Specify which agents should participate in the collaboration
  • Result Display: View collaboration results including agent contributions and execution time

Agent Configuration in TUI

The TUI provides agent configuration management:

  • Priority Setting: Configure agent priority (1-10)
  • Execution Time Limits: Set maximum execution time for agents
  • Retry Configuration: Configure retry count for failed executions
  • Enable/Disable: Enable or disable specific agents
  • Configuration Persistence: Save and load agent configurations

Sandboxing

sandbox_manager = manager.sandbox_manager sandbox_stats = manager.get_sandbox_statistics()

Task Distribution

task_distributor = manager.task_distributor dist_stats = manager.get_distribution_statistics()


Agents can also be unregistered:

```python
manager.unregister("planner")

AgentService

AgentService is the kernel service that exposes the agent manager and workflow executor to the rest of the application. It resolves AIService, ToolService, MemoryService, WorkspaceService, and RuntimeService from the container and injects them into agent constructors. AgentService also uses ModelRouter to choose the best AI provider for each agent task. Agents are enabled or disabled based on AgentsConfig flags during initialization.

from novacoder.agents.service import AgentService
from novacoder.config.settings import AppConfig

config = AppConfig(agents={"chat": False, "planner": False, "coder": True})
service = AgentService(config)
service.initialize()

assert "chat" not in service.manager.list_agents()
assert "planner" not in service.manager.list_agents()
assert "coder" in service.manager.list_agents()

For a full end-to-end workflow, use AgentService.execute():

result = await service.execute("Build a Flask API")
print(result["plan"])
print(result["results"])

Tool Actions

Specialist agents do not only return text; they now call tools through the injected ToolService:

  • coder, writes generated code with WriteFileTool and applies edits with ApplyEditTool
  • tester, runs RunPytestTool and RunPythonTool to verify changes
  • debugger, analyses output and applies suggested fixes with ApplyEditTool
  • documentation, writes or updates docs with WriteFileTool

The result object returned by each agent includes the outcome of the tool calls, including generated files, test results, and applied edits.

Development Instructions

Adding a New Agent

  1. Create a class in novacoder/agents/ extending Agent.
  2. Set name and description class attributes.
  3. Implement async def run(self, task: AgentTask) -> AgentResult.
  4. Use injected self._ai, self._tools, self._memory, and self._workspace to access runtime services.
  5. Register the agent in AgentManager._register_defaults() in novacoder/agents/manager.py.
  6. Add tests in tests/test_agents.py or a new test file.
  7. Update this wiki page and the CLI help text if relevant.

Agent Template

from novacoder.agents.agent import Agent, AgentResult, AgentTask

class MyAgent(Agent):
    name = "my_agent"
    description = "Performs a specialized task."

    async def run(self, task: AgentTask) -> AgentResult:
        # Access task.goal, task.description, task.context
        # Access self._ai, self._tools, self._memory, self._workspace
        return AgentResult(
            success=True,
            output={"done": True},
            summary=f"Processed {task.goal}",
        )

Agent Testing

def test_my_agent():
    agent = MyAgent()
    task = AgentTask(id="1", description="Test", goal="Test")
    result = agent.run(task)
    assert result.success
    assert result.summary

Agent Collaboration

Agents should not call each other directly. Instead, the manager or planner dispatches tasks and combines results. Use the event bus for notifications such as AgentFinished.

Error Handling

If an agent cannot complete a task, return AgentResult(success=False, errors=[...]) with a descriptive error. Do not raise exceptions unless the failure is unrecoverable.

Enhanced Error Handling (August 2026):

All specialist agents now include comprehensive error handling and logging:

  • AI Service Validation: Agents check if AI provider is available before attempting calls
  • Exception Handling: Try-catch blocks around all AI service calls with detailed error logging
  • Informative Error Messages: Clear error messages when AI service is unavailable or fails
  • Logging Integration: All agent operations are logged for debugging and monitoring
  • Graceful Degradation: Agents return structured error results instead of silent failures

Example error handling pattern:

if self._ai is not None:
    try:
        response = await self._ai.chat(messages)
        logger.info(f"Agent successfully processed task: {task.goal}")
    except Exception as e:
        logger.error(f"Agent AI call failed: {e}", exc_info=True)
        return AgentResult(
            success=False,
            errors=[f"AI service error: {str(e)}"],
            output=None,
            summary="Task failed due to AI service error"
        )
else:
    logger.warning(f"Agent: AI provider not available for task: {task.goal}")
    return AgentResult(
        success=False,
        errors=["AI provider not available - please ensure AI service is configured and running"],
        output=None,
        summary="Task failed - AI provider unavailable"
    )

Discovery Notes

During the latest system-wide debug pass, the default plan produced by PlannerEngine referenced architect and tester, but those agents were not registered in AgentManager. This caused any execution of the default plan to fail when it reached those agents. The following agents were added and registered in novacoder/agents/manager.py:

  • architect
  • tester
  • debugger
  • documentation

All agents referenced in the default plan are now runnable. The registration test in tests/test_agents.py verifies the complete set of default agents.

Future Agents

(None currently - all planned agents have been implemented)

  • Planner
  • Tools
  • AI Runtime
  • Agent Communication
  • Agent Learning
  • Agent Orchestration
  • Agent Testing
  • Agent Error Recovery
  • Agent State Management
  • Agent Monitoring
  • Agent Security Validation
  • Agent Cost Tracking
  • Agent Collaboration
  • Agent Performance Optimization
  • Agent Documentation Automation
  • Agent DevOps
  • Agent Database
  • Agent Mobile
  • Agent UI/UX
  • Agent Data Science
  • Agent API Design
  • Agent Git
  • Agent Compliance
  • Agent Marketplace
  • Agent Versioning
  • Agent Sandboxing
  • Agent Task Distribution
  • Agent Access Control
  • Agent Input Validation
  • Agent Pooling
  • Agent Execution Pool
  • Agent Memory Management
  • Agent Profiling
  • Agent Benchmarks

REST API, Enablement & Distribution

Agent enablement is runtime-toggleable via AgentService.set_agent_enabled(name, enabled) (registration is driven by a _build_agent_factories() name→factory map):

Method Path Description
GET /api/agents/states Per-agent enabled/registered state
POST /api/agents/{name}/enable / disable Register/unregister at runtime; persists agents.<name> to user.yaml
GET /api/agents/distribution/statistics TaskDistributor strategy/queue/outcome stats (404 when agents.enable_task_distribution=false)
POST /api/agents/distribution/strategy Set distribution strategy (round_robin, least_loaded, capability_match, performance_based, priority_queue, affinity, distributed)

UI: Enablement card on the Agents page; the Chat agent selector reads GET /api/agents dynamically. ChatRequest and POST /api/stream validate/route against the live registry.

Record 15 / 48 // Part III · Intelligence

NovaCoder Agents System

AgentManager, tasks and orchestration · source wiki/agents-system.md

Overview

The Nova Coder agents system is a comprehensive multi-agent architecture that enables specialized AI agents to collaborate on complex software development tasks. The system includes core agents, advanced agent systems, and sophisticated orchestration capabilities.

Location

  • Main Directory: novacoder/agents/
  • Service: novacoder/agents/service.py
  • Manager: novacoder/agents/manager.py

Components

Core Agent Classes

  • Agent - Base agent class with task execution
  • AgentTask - Task definition with goal, description, and context
  • AgentResult - Result structure with success status, output, and errors
  • AgentManager - Orchestrator for managing and dispatching agents

Specialist Agents

Core Specialist Agents (8)

  1. PlannerAgent - Breaks down goals into task plans
  2. ArchitectAgent - Explores and analyzes project structure
  3. CoderAgent - Generates and modifies code
  4. ReviewerAgent - Reviews code for quality and correctness
  5. TesterAgent - Generates and executes tests
  6. DebuggerAgent - Diagnoses and fixes errors
  7. DocumentationAgent - Generates documentation
  8. ChatAgent - Handles conversational interactions

Advanced Specialist Agents (9)

  1. PerformanceOptimizationAgent - Optimizes code performance
  2. AgentPerformanceOptimizer - Analyzes agent performance
  3. DocumentationAutomation - Automates documentation generation
  4. DevOpsAgent - Handles DevOps operations (CI/CD, deployment)
  5. DatabaseAgent - Handles database operations and queries
  6. MobileAgent - Handles mobile app development
  7. UIUXAgent - Handles UI/UX design
  8. DataScienceAgent - Handles data science tasks
  9. APIDesignAgent - Handles API design
  10. ComplianceAgent - Checks compliance requirements
  11. GitAgent - Handles Git operations

Advanced Agent Systems

The Nova Coder agents system includes several advanced systems for multi-agent workflows:

  • Agent Communication Protocol - Enables agents to send messages, delegate tasks, and collaborate
  • Agent Learning System - Tracks agent performance and provides improvement recommendations
  • Agent Orchestration - Provides multiple strategies for multi-agent workflow execution
  • Agent Testing Framework - Comprehensive testing infrastructure for validating agent behavior
  • Agent Error Recovery - Automatic error classification and recovery strategies
  • Agent State Management - Persistent agent state storage with checkpointing and task resumption
  • Agent Monitoring - Agent execution tracing, performance metrics, and anomaly detection
  • Agent Security Validation - Agent action validation with security policies and audit logging
  • Agent Cost Tracking - Per-agent cost monitoring with budgeting and optimization recommendations
  • Agent Collaboration - Multiple collaboration patterns for complex multi-agent workflows
  • Agent Marketplace - Agent sharing and discovery system with packaging, search, and reviews
  • Agent Versioning - Semantic versioning for agent configurations with rollback capabilities
  • Agent Sandboxing - Secure isolated execution environments with Docker container support and resource limits
  • Agent Distribution - Intelligent task distribution with distributed node management and load balancing
  • Agent Benchmarks - Performance benchmarking and optimization for agent startup and memory usage
  • AgentCollaboration - Multi-agent workflow orchestration
  • CollaborationPattern - Collaboration modes (SEQUENTIAL, PARALLEL, HIERARCHICAL)
  • CollaborationTask - Multi-agent task definitions
  • CollaborationResult - Collaboration outcome tracking

Communication System

  • AgentCommunicationProtocol - Message routing between agents
  • MessageBus - Pub/sub messaging system
  • MessageType - Message type definitions (REQUEST, RESPONSE, NOTIFICATION)
  • AgentMessage - Message structure with sender, receiver, content

State Management

  • AgentStateManager - Manages agent state transitions
  • AgentState - Agent state representation
  • AgentStateSnapshot - Point-in-time state capture
  • AgentCheckpoint - Restore points for agent state

Learning System

  • AgentLearningSystem - Tracks and learns from agent performance
  • LearningStrategy - Learning approach definitions
  • AgentExecutionRecord - Individual execution records
  • AgentPerformanceMetrics - Performance metrics aggregation

Error Recovery

  • AgentErrorRecovery - Error handling and recovery
  • RecoveryStrategy - Recovery approaches (RETRY, FALLBACK, SKIP)
  • ErrorType - Error categorization
  • RecoveryPolicy - Recovery rule definitions
  • ErrorRecord - Error tracking

Testing Framework

  • AgentTestFramework - Agent testing infrastructure
  • TestType - Test categories (UNIT, INTEGRATION, E2E)
  • AgentTestCase - Test case definitions
  • TestResult - Test outcome tracking
  • TestSuite - Test grouping

Monitoring System

  • AgentMonitoring - Agent metrics collection
  • MetricType - Metric categories (COUNTER, GAUGE, HISTOGRAM)
  • Metric - Individual metric representation
  • AgentExecutionTrace - Execution tracking
  • AnomalyDetection - Anomaly detection in metrics

Customization System

  • AgentCustomizationManager - Agent configuration management
  • CustomizationScope - Customization levels (AGENT, TASK, GLOBAL)
  • CustomizationType - Customization categories (BEHAVIOR, PERFORMANCE, UI)
  • CustomizationRule - Customization rule definitions
  • CustomizationProfile - Rule grouping
  • CustomizationContext - Context for customization

Marketplace System

  • AgentMarketplace - Agent sharing and discovery
  • AgentCategory - Agent type categories
  • AgentStatus - Package states (DRAFT, PUBLISHED, DEPRECATED)
  • AgentMetadata - Agent package metadata
  • AgentPackage - Agent package representation
  • Review - User reviews

Versioning System

  • AgentVersionManager - Agent version control
  • Version - Semantic version representation
  • VersionStatus - Version states (DRAFT, PUBLISHED, DEPRECATED)
  • AgentVersion - Agent version representation
  • VersionDiff - Version comparison

Sandboxing System

  • AgentSandbox - Isolated execution environment
  • AgentSandboxManager - Sandbox lifecycle management
  • SandboxType - Isolation mechanisms (DOCKER, PROCESS, THREAD)
  • ResourceLimits - Resource constraints
  • SandboxConfig - Sandbox configuration
  • SandboxExecutionResult - Execution outcome

Distribution System

  • TaskDistributor - Task distribution across agents
  • DistributionStrategy - Distribution algorithms (ROUND_ROBIN, LEAST_LOADED, CAPABILITY_BASED)
  • TaskPriority - Priority levels (LOW, MEDIUM, HIGH, CRITICAL)
  • AgentCapability - Agent skill definitions
  • DistributedTask - Distributed task representation
  • TaskAssignment - Task-to-agent mapping
  • AgentLoad - Agent workload tracking

Access Control System

  • AgentAccessControl - Permission management
  • PermissionType - Permission categories (READ, WRITE, EXECUTE, ADMIN)
  • Role - Role definitions
  • Permission - Permission definitions
  • RoleDefinition - Role structure
  • AgentAccessPolicy - Access policy definitions

Input Validation System

  • InputValidator - Generic input validation
  • AgentInputValidator - Agent-specific validation
  • ValidationRule - Validation rule definitions
  • ValidationSeverity - Severity levels (INFO, WARNING, ERROR)
  • ValidationError - Validation error representation
  • ValidationResult - Validation outcome
  • FieldValidation - Field-level validation

Pooling System

  • AgentPool - Agent instance pooling
  • AgentPoolManager - Pool lifecycle management
  • LazyAgent - Deferred agent creation
  • PoolConfig - Pool configuration
  • PooledAgent - Pooled agent representation
  • PoolStrategy - Pooling strategies (EAGER, LAZY, HYBRID)

Execution Pool System

  • ExecutionPool - Task execution pooling
  • ExecutionPoolManager - Execution pool management
  • ExecutionConfig - Execution configuration
  • ExecutionStrategy - Execution strategies (FIFO, PRIORITY, DEADLINE)
  • ExecutionTask - Execution task representation
  • PriorityExecutionPool - Priority-based execution

Memory Management System

  • MemoryManager - Agent memory usage management
  • MemoryMonitor - Memory usage tracking
  • MemoryConfig - Memory configuration
  • MemoryLimit - Memory limit definitions
  • MemoryLimitType - Limit enforcement (SOFT, HARD)
  • MemorySnapshot - Memory state capture
  • MemoryContext - Memory context

Profiling System

  • AgentProfiler - Agent performance profiling
  • ProfilingDecorator - Function profiling decorator
  • PerformanceAnalyzer - Performance data analysis
  • ProfileConfig - Profiling configuration
  • ProfilingLevel - Profiling detail (BASIC, STANDARD, DETAILED)
  • FunctionCall - Function call representation
  • AgentProfile - Agent performance profile

Benchmarks System

  • BenchmarkResult - Benchmark result data structure
  • AgentBenchmark - Individual agent benchmark
  • AgentBenchmarkRunner - Benchmark execution runner
  • AgentStartupOptimizer - Agent startup performance optimizer
  • AgentMemoryOptimizer - Agent memory usage optimizer

API Reference

AgentManager

class AgentManager:
    def __init__(self) -> None
    def register(self, agent: Agent) -> None
    def unregister(self, agent_id: str) -> bool
    def get(self, agent_id: str) -> Agent | None
    def list_agents(self) -> list[str]
    def run(self, agent_id: str, task: AgentTask) -> AgentResult
    async def run_async(self, agent_id: str, task: AgentTask) -> AgentResult

Agent

class Agent:
    def __init__(self, ai=None, tools=None, memory=None, workspace=None) -> None
    def set_session_context(self, context: dict) -> None
    async def run(self, task: AgentTask) -> AgentResult
    def run_sync(self, task: AgentTask) -> AgentResult

AgentTask

class AgentTask:
    def __init__(self, id: str, description: str, goal: str, context: dict | None = None) -> None

AgentResult

class AgentResult:
    def __init__(self, success: bool, output: dict, errors: list[str] = []) -> None

Usage

Basic Agent Execution

from novacoder.agents import AgentManager, AgentTask

# Create manager
manager = AgentManager()

# Run a task
task = AgentTask(id="task1", description="Build API", goal="Build REST API")
result = manager.run("planner", task)

if result.success:
    print(result.output)
else:
    print(result.errors)

Using Specialist Agents

from novacoder.agents import CoderAgent, AgentTask
from novacoder.ai.providers.mock import MockProvider

# Create agent with AI provider
ai = MockProvider(responses={"Generate code": "print('hello')"})
agent = CoderAgent(ai=ai)

# Run task
task = AgentTask(id="task1", description="Write hello", goal="Write hello world")
result = agent.run_sync(task)

Multi-Agent Collaboration

from novacoder.agents import AgentCollaboration, CollaborationPattern, CollaborationTask

# Create collaboration
collaboration = AgentCollaboration()

# Define multi-agent task
task = CollaborationTask(
    task_id="task1",
    pattern=CollaborationPattern.SEQUENTIAL,
    agents=["planner", "coder", "tester"]
)

# Execute collaboration
result = await collaboration.execute_swarm(
    "Build feature",
    "Implement the task",
    ["planner", "coder", "tester"],
)

Agent Learning

from novacoder.agents import AgentLearningSystem, AgentExecutionRecord

# Create learning system
learning = AgentLearningSystem()

# Record execution
record = AgentExecutionRecord(
    agent_id="coder",
    task_id="task1",
    success=True,
    duration=1.5,
    tokens_used=100
)
learning.record_execution(record)

# Get metrics
metrics = learning.get_agent_metrics("coder")
print(f"Success rate: {metrics.success_rate}")

Integration

Kernel Integration

The agents system is integrated with the Nova Coder kernel via the AgentService:

from novacoder.agents.service import AgentService
from novacoder.config.settings import AppConfig

# Create service
service = AgentService(config=AppConfig())
service.initialize()

# Execute via service
result = service.execute("Build API")

Service Integration

The agents system integrates with:

  • AI Service - For AI provider access
  • Memory Service - For memory operations
  • Workspace Service - For workspace operations
  • Tool Service - For tool execution

Best Practices

  1. Use AgentManager - Always use AgentManager for agent orchestration
  2. Handle Errors - Always check AgentResult.success and handle errors
  3. Context Management - Use session context for multi-turn conversations
  4. Resource Limits - Configure memory and execution limits for production
  5. Monitoring - Enable monitoring for production deployments
  6. Testing - Write tests for custom agents
  7. Validation - Use input validation for agent inputs
  8. Error Recovery - Configure appropriate recovery strategies

Performance Impact

  • Agent Pooling - Reduces agent initialization overhead
  • Execution Pooling - Limits concurrent executions
  • Memory Management - Prevents memory leaks
  • Profiling - Identifies performance bottlenecks
  • Caching - Reduces redundant computations

Error Handling

All agents return AgentResult with:

  • success - Boolean indicating success/failure
  • output - Dictionary with results
  • errors - List of error messages

Always check result.success before accessing result.output.

Limitations

  1. AI Provider Required - Agents require an AI provider for full functionality
  2. Tool Dependencies - Some agents require specific tools
  3. Memory Usage - Complex agents can consume significant memory
  4. Execution Time - Some operations can be time-consuming
  5. Concurrency - Limited by execution pool configuration

Future Enhancements

  • Agent Marketplace - Public marketplace for sharing agents
  • Agent Versioning - Full version control for agents
  • Sandboxing - Docker-based isolation for agents
  • Distribution - True distributed agent execution
  • Federation - Cross-instance agent collaboration
  • Auto-tuning - Automatic performance optimization
  • Visual Editor - GUI for agent configuration

Record 16 / 48 // Part III · Intelligence

Advanced Agent Management

Specialist agent systems · source wiki/advanced-agents.md

Nova Coder provides advanced agent management capabilities for batch execution, history tracking, stopping agents, metrics analysis, and agent training. These commands are accessible through the agents-advanced sub-application.

Overview

The advanced agent management system allows you to:

  • Execute agents in batch mode for multiple goals
  • Track agent execution history
  • Stop running agents when needed
  • Analyze agent performance metrics
  • Train agents with custom data

Commands

Batch Agent Execution

Execute an agent on multiple goals in a single batch operation.

novacoder agents-advanced batch <agent> <goals...>

Example:

novacoder agents-advanced batch coder "Fix authentication bug" "Add user profile" "Optimize database queries"

Batch Features:

  • Sequential or parallel execution
  • Progress tracking
  • Error handling
  • Result aggregation
  • Performance monitoring

Agent History

View the execution history of a specific agent.

novacoder agents-advanced history <agent> --limit <n>

Example:

novacoder agents-advanced history coder --limit 20

History Includes:

  • Execution timestamps
  • Goals and results
  • Success/failure status
  • Performance metrics
  • Error details

Stop Running Agent

Stop a currently running agent by its ID.

novacoder agents-advanced stop <agent_id>

Example:

novacoder agents-advanced stop agent-id-123

Stop Features:

  • Graceful shutdown
  • State preservation
  • Cleanup operations
  • Resource release
  • Status reporting

Agent Metrics

View performance metrics for a specific agent.

novacoder agents-advanced metrics <agent>

Example:

novacoder agents-advanced metrics coder

Metrics Include:

  • Execution count
  • Success rate
  • Average duration
  • Resource usage
  • Error frequency

Train Agent

Train an agent with custom data to improve performance.

novacoder agents-advanced train <agent> --data <path>

Example:

novacoder agents-advanced train coder --data /path/to/training-data

Training Features:

  • Custom dataset support
  • Performance improvement
  • Model fine-tuning
  • Validation testing
  • Result analysis

Use Cases

Batch Processing

Process multiple goals efficiently:

novacoder agents-advanced batch coder "Fix bug #1" "Fix bug #2" "Fix bug #3"

History Review

Review agent execution history:

novacoder agents-advanced history planner --limit 50

Agent Control

Stop a misbehaving agent:

novacoder agents-advanced stop agent-id-456

Performance Analysis

Analyze agent performance:

novacoder agents-advanced metrics tester

Agent Training

Train agent with project-specific data:

novacoder agents-advanced train coder --data ./project-training-data

Implementation Details

Batch Execution

Batch execution supports:

  • Sequential processing (default)
  • Parallel processing (when enabled)
  • Dependency tracking
  • Resource management
  • Error recovery

History Storage

Agent history is stored with:

  • Unique execution IDs
  • Timestamps and duration
  • Input and output data
  • Success/failure status
  • Performance metrics

Agent Lifecycle

Agent lifecycle management:

  • Initialization and startup
  • Execution monitoring
  • State management
  • Graceful shutdown
  • Resource cleanup

Metrics Collection

Metrics are collected for:

  • Execution frequency
  • Success/failure rates
  • Duration statistics
  • Resource consumption
  • Error patterns

Training Process

Agent training involves:

  • Data preprocessing
  • Model fine-tuning
  • Validation testing
  • Performance evaluation
  • Model deployment

Best Practices

  1. Batch Size: Use appropriate batch sizes for optimal performance
  2. History Review: Regularly review agent history for patterns
  3. Resource Monitoring: Monitor agent resource usage during execution
  4. Training Data: Use high-quality, relevant training data
  5. Metrics Analysis: Regularly analyze metrics for performance insights

Troubleshooting

Batch Execution Failures

If batch execution fails:

  1. Check individual goal validity
  2. Review error messages
  3. Verify agent availability
  4. Check resource availability
  5. Try smaller batch sizes

History Issues

If history is not available:

  1. Verify history storage configuration
  2. Check file permissions
  3. Review storage capacity
  4. Ensure agent has executed previously

Agent Stop Failures

If agent stop fails:

  1. Verify agent ID is correct
  2. Check agent status
  3. Review permissions
  4. Force stop if necessary
  5. Check for dependencies

Training Problems

If training fails:

  1. Verify training data format
  2. Check data quality
  3. Review error messages
  4. Ensure sufficient resources
  5. Validate agent compatibility

Advanced Features

Custom Batch Strategies

Define custom batch execution strategies:

  • Priority-based ordering
  • Dependency-aware scheduling
  • Resource-aware allocation
  • Error recovery policies

History Filtering

Filter agent history by:

  • Date ranges
  • Success/failure status
  • Goal patterns
  • Performance metrics
  • Error types

Agent Groups

Group related agents for management:

  • Team-based groups
  • Project-specific groups
  • Performance-based groups
  • Custom categorization

Training Pipelines

Create automated training pipelines:

  • Data preprocessing
  • Model validation
  • Performance testing
  • Automated deployment
  • Continuous improvement

Agent Types

Coder Agent

  • Code generation and editing
  • Bug fixing and optimization
  • Refactoring and documentation
  • Testing and validation

Planner Agent

  • Goal decomposition
  • Task planning
  • Resource allocation
  • Timeline estimation

Tester Agent

  • Test generation
  • Test execution
  • Result analysis
  • Bug identification

Debugger Agent

  • Error analysis
  • Root cause identification
  • Fix suggestion
  • Validation testing

Architect Agent

  • System design
  • Architecture planning
  • Technology selection
  • Implementation guidance

API Endpoints

The advanced agent management system is accessible via REST API endpoints. All endpoints have been tested and verified to be working.

Batch Agent Execution

Execute an agent on multiple goals in a single batch operation.

POST /api/agents-advanced/batch
Content-Type: application/json
x-api-token: novacoder-secure-token-2024

{
  "tasks": [
    {
      "id": "task-1",
      "agent": "coder",
      "goal": "Fix authentication bug",
      "context": {}
    },
    {
      "id": "task-2",
      "agent": "coder",
      "goal": "Add user profile",
      "context": {}
    }
  ]
}

Response:

{
  "batch_id": "batch-0",
  "total_tasks": 2,
  "completed_tasks": 2,
  "failed_tasks": 0,
  "results": [
    {
      "task_id": "task-1",
      "agent": "coder",
      "status": "completed",
      "result": {
        "output": "Generated code fix",
        "errors": []
      }
    },
    {
      "task_id": "task-2",
      "agent": "coder",
      "status": "completed",
      "result": {
        "output": "Generated user profile code",
        "errors": []
      }
    }
  ],
  "timestamp": "2026-07-31T03:00:05.273456Z"
}

Batch Features:

  • Sequential task execution
  • Error handling per task
  • Result aggregation
  • Batch ID tracking
  • Performance metrics

Status: ✅ Tested and working

Agent History

View the execution history of a specific agent.

GET /api/agents-advanced/history?agent=coder&limit=10
x-api-token: novacoder-secure-token-2024

Response:

{
  "agent": "coder",
  "total_entries": 0,
  "history": [],
  "timestamp": "2026-07-31T03:00:05.273456Z"
}

History Features:

  • Agent-specific history
  • Result limiting
  • Success/failure tracking
  • Duration metrics
  • Timestamp tracking

Status: ✅ Tested and working

Stop Running Agent

Stop a currently running agent by its ID.

POST /api/agents-advanced/stop
Content-Type: application/json
x-api-token: novacoder-secure-token-2024

{
  "agent_id": "agent-id-123"
}

Response:

{
  "agent_id": "agent-id-123",
  "status": "stopped",
  "note": "Agent lifecycle tracking requires full implementation in AgentService",
  "timestamp": "2026-07-31T03:00:05.273456Z"
}

Stop Features:

  • Agent ID-based stopping
  • Status reporting
  • Graceful shutdown notes
  • Lifecycle tracking

Status: ✅ Tested and working

Agent Metrics

View performance metrics for a specific agent.

GET /api/agents-advanced/metrics?agent=coder
x-api-token: novacoder-secure-token-2024

Response:

{
  "agent": "coder",
  "error": "Agent not found",
  "timestamp": "2026-07-31T03:00:05.273456Z"
}

Note: Metrics are calculated from agent execution history. If no history exists for the agent, it will return "Agent not found".

Metrics Features:

  • Execution count tracking
  • Success rate calculation
  • Average duration metrics
  • Agent-specific statistics
  • Historical analysis

Status: ✅ Tested and working

Status Check

Check the status of the advanced agent management system.

GET /api/agents-advanced/status
x-api-token: novacoder-secure-token-2024

Response:

{
  "enabled": true,
  "services": {
    "agent_batch_executor": true,
    "agent_history_manager": true,
    "agent_stopper": true,
    "agent_metrics_collector": true,
    "agent_trainer": true
  },
  "running_agents": 0,
  "active_trainings": 0,
  "timestamp": "2026-07-31T03:00:05.273456Z"
}

Status: ✅ Tested and working

Integration Notes

  • App Instance Integration: Fixed to use shared API server app instance instead of creating new instances for each request
  • Async/Await Context: Fixed batch execution to use await instead of asyncio.run() since already in async context
  • Authentication: All endpoints require x-api-token header with valid API token
  • Error Handling: Proper error responses with status codes for invalid requests
  • Agent Service: Uses existing AgentService from the Nova Coder application container
  • CLI Enhancements
  • Agents
  • CLI
  • Agent Communication
  • Agent Learning
  • REST API

Record 17 / 48 // Part III · Intelligence

AI Models

Model registry and selection · source wiki/ai-models.md

The AI Models system provides comprehensive management of AI models across multiple providers, enabling model listing, selection, and configuration for the Nova Coder platform.

Overview

The AI Models system allows developers to view and manage available AI models from configured providers. It supports multiple AI providers including OpenAI, Anthropic, Cohere, HuggingFace, LocalAI, and vLLM, providing a unified interface for model management.

Features

  • Model Listing: View all available AI models from configured providers
  • Provider Information: Display provider information for each model
  • Model Size Display: Show model size information
  • Multi-Provider Support: Support for multiple AI providers
  • Model Selection: Select models for use in AI operations

API Endpoints

GET /api/models

List all available AI models from configured providers.

GET /api/ai/management/dashboard

Returns the unified model management dashboard with provider status, cost summary, and failover state.

GET /api/ai/management/providers

Lists provider health and availability.

GET /api/ai/management/costs

Returns aggregated cost metrics across providers and models.

GET /api/ai/management/failover

Returns the current provider failover routing configuration.

Response:

[
  {
    "name": "gpt-4",
    "provider": "openai",
    "size": "-"
  },
  {
    "name": "claude-3-opus",
    "provider": "anthropic",
    "size": "-"
  },
  {
    "name": "command",
    "provider": "cohere",
    "size": "-"
  }
]

Web UI Integration

The AI Models system is fully integrated into the Nova Coder Web UI with a dedicated "AI Models" navigation item under the Administration section.

AI Models UI Features

The AI Models UI provides:

  • Model Listing Display: View all available AI models in a grid layout
  • Provider Information: Display provider name for each model
  • Model Size Display: Show model size information
  • Grid Layout: Organized display of models in a grid layout for easy browsing

API Endpoints Used

The AI Models UI integrates with the following API endpoint:

  • GET /api/models - List all available AI models from configured providers

UI Navigation

Access the AI Models UI by:

  1. Navigate to the Administration section in the sidebar
  2. Click on "AI Models"
  3. The UI displays all available models in a grid layout

JavaScript Integration

The AI Models UI is implemented in the React SPA (novacoder/web/react/src/pages/Ai.tsx, backed by GET /api/models); there is no separate novacoder/web/static/js/app.js. The legacy inline UI in novacoder/api/_html.py also calls /api/models.

Response Handling

The UI handles API responses according to the actual response structure from the models endpoint:

  • Models Response: Expects array of model objects with name, provider, and size fields
  • Model Object: Each model contains name (model identifier), provider (provider name), and size (model size information)

Display Format

The AI Models UI displays models in a grid layout with:

  • Model Name: Displayed as the card title
  • Provider Information: Displayed below the model name
  • Model Size: Displayed below the provider information

Supported AI Providers

The AI Models system supports the following providers:

  • OpenAI: GPT-4, GPT-3.5, and other OpenAI models
  • Anthropic: Claude 3 Opus, Claude 3 Sonnet, and other Anthropic models
  • Cohere: Command, Command Light, and other Cohere models
  • HuggingFace: Various open-source models
  • LocalAI: Local models via LocalAI
  • vLLM: Local models via vLLM
  • Azure OpenAI: Azure-hosted OpenAI models
  • Bedrock: AWS Bedrock models
  • Vertex AI: Google Vertex AI models

Usage Examples

Listing Available Models

from novacoder.ai.service import AIService
from novacoder.app import create_app

app = create_app()
ai_service = app.container.resolve(AIService)

# List all available models
providers = ai_service.manager.list_providers()
for provider_name in providers:
    provider = ai_service.manager.load(provider_name)
    models = await provider.available_models()
    print(f"Provider: {provider_name}")
    for model in models:
        print(f"  - {model}")

Getting Model Information

# Get model information for a specific provider
provider = ai_service.manager.load("openai")
models = await provider.available_models()
for model in models:
    print(f"Model: {model}")
    print(f"Provider: openai")

Model Configuration

Models are configured through the AI provider configuration:

from novacoder.config.settings import AppConfig

config = AppConfig(
    ai={
        "providers": {
            "openai": {
                "api_key": "your-api-key",
                "model": "gpt-4"
            }
        }
    }
)

Model Selection

Select models for specific operations:

# Use a specific model for AI operations
provider = ai_service.manager.load("openai")
response = await provider.complete(
    prompt="Hello, world!",
    model="gpt-4"
)

Record 18 / 48 // Part III · Intelligence

AI Provider Configuration

Provider setup and credentials · source wiki/ai-provider-configuration.md

The AI Provider Configuration system provides comprehensive configuration management for AI providers, including multi-scope configuration, validation, and import/export capabilities.

Overview

The configuration system provides:

  • Multi-Scope Configuration: Global, provider, model, and request-level configuration
  • Configuration Merging: Intelligent merging of configurations from different scopes
  • Configuration Validation: Validation of configuration values
  • Import/Export: JSON import and export of configurations
  • Provider Configuration: Provider-specific settings (API keys, base URLs, timeouts)
  • Model Configuration: Model-specific settings (temperature, max tokens, penalties)

Architecture

Global Config
     ↓
Provider Config
     ↓
Model Config
     ↓
Request Config
     ↓
Merged Config

Components

ConfigManager

Manager for provider configurations:

from novacoder.ai.provider_config import ConfigManager

manager = ConfigManager()

ProviderConfig

Configuration for a provider:

from novacoder.ai.provider_config import ProviderConfig

config = ProviderConfig(
    name="openai",
    api_key="sk-...",
    base_url="https://api.openai.com/v1",
    timeout=30.0,
    max_retries=3
)

ModelConfig

Configuration for a model:

from novacoder.ai.provider_config import ModelConfig

config = ModelConfig(
    provider="openai",
    model="gpt-4",
    temperature=0.7,
    max_tokens=4096
)

RequestConfig

Configuration for a specific request:

from novacoder.ai.provider_config import RequestConfig

config = RequestConfig(
    provider="openai",
    model="gpt-4",
    temperature=0.8,
    max_tokens=2048
)

ConfigMiddleware

Middleware for configuration management:

from novacoder.ai.provider_config import ConfigMiddleware

middleware = ConfigMiddleware()

Usage Examples

Setting Provider Configuration

from novacoder.ai.provider_config import ConfigManager, ProviderConfig

manager = ConfigManager()

# Set provider configuration
config = ProviderConfig(
    name="openai",
    api_key="sk-...",
    base_url="https://api.openai.com/v1",
    timeout=30.0,
    max_retries=3,
    enable_streaming=True,
    enable_caching=True
)

manager.set_provider_config(config)

Setting Model Configuration

from novacoder.ai.provider_config import ModelConfig

# Set model configuration
config = ModelConfig(
    provider="openai",
    model="gpt-4",
    temperature=0.7,
    max_tokens=4096,
    top_p=1.0,
    frequency_penalty=0.0,
    presence_penalty=0.0
)

manager.set_model_config(config)

Setting Global Configuration

# Set global configuration values
manager.set_global_config("default_timeout", 30.0)
manager.set_global_config("enable_logging", True)
manager.set_global_config("log_level", "INFO")

# Get global configuration
timeout = manager.get_global_config("default_timeout", 30.0)

Merging Configurations

from novacoder.ai.provider_config import RequestConfig

# Create request configuration
request_config = RequestConfig(
    provider="openai",
    model="gpt-4",
    temperature=0.8
)

# Merge configurations from all scopes
merged = manager.merge_configs(
    request_config=request_config,
    provider="openai",
    model="gpt-4"
)

print(f"Merged config: {merged}")

Configuration Validation

# Validate configuration
config = {
    "temperature": 0.7,
    "max_tokens": 4096,
    "top_p": 1.0
}

errors = manager.validate_config(config)
if errors:
    print(f"Validation errors: {errors}")
else:
    print("Configuration is valid")

Import/Export Configuration

# Export configuration to JSON
json_config = manager.export_config(scope=ConfigScope.GLOBAL)
print(json_config)

# Import configuration from JSON
success = manager.import_config(json_config, scope=ConfigScope.GLOBAL)

Listing Configurations

# List all provider configurations
provider_configs = manager.list_provider_configs()

# List model configurations
model_configs = manager.list_model_configs()

# List model configurations for a specific provider
openai_configs = manager.list_model_configs(provider="openai")

Deleting Configurations

# Delete provider configuration
manager.delete_provider_config("openai")

# Delete model configuration
manager.delete_model_config("openai", "gpt-4")

Configuration Scopes

from novacoder.ai.provider_config import ConfigScope

# Available configuration scopes
ConfigScope.GLOBAL      # Global configuration
ConfigScope.PROVIDER    # Provider-specific configuration
ConfigScope.MODEL       # Model-specific configuration
ConfigScope.REQUEST     # Request-specific configuration

Configuration Priority

Configurations are merged in the following order (lower priority first):

  1. Global Configuration: Default values for all providers
  2. Provider Configuration: Provider-specific settings
  3. Model Configuration: Model-specific settings
  4. Request Configuration: Request-specific overrides

Configuration Validation

The system validates the following parameters:

  • Temperature: Must be between 0.0 and 2.0
  • Max Tokens: Must be positive
  • Top P: Must be between 0.0 and 1.0
  • Top K: Must be positive
  • Frequency Penalty: Must be between -2.0 and 2.0
  • Presence Penalty: Must be between -2.0 and 2.0

Best Practices

  1. Use Global Defaults: Set sensible global defaults
  2. Provider-Specific Settings: Use provider-specific settings for API keys and endpoints
  3. Model-Specific Settings: Use model-specific settings for model parameters
  4. Request Overrides: Use request overrides for specific requests
  5. Validate Configurations: Always validate configurations before use
  6. Export Configurations: Export configurations for backup and version control
  7. Use Environment Variables: Use environment variables for sensitive data

Performance Considerations

  • Configuration Merging: Fast O(1) operations
  • Validation: Fast validation of configuration values
  • Import/Export: JSON serialization/deserialization overhead
  • Memory Usage: Minimal memory usage for configuration storage

Configuration

Configure configuration management behavior:

# Production configuration
manager = ConfigManager()
manager.set_global_config("default_timeout", 30.0)
manager.set_global_config("enable_logging", True)

# Development configuration
manager = ConfigManager()
manager.set_global_config("default_timeout", 60.0)  # Longer timeout for development
manager.set_global_config("enable_logging", False)  # Disable logging in development
  • AI Runtime
  • AI Provider Metrics
  • AI Rate Limiting

Record 19 / 48 // Part III · Intelligence

AI Streaming System

SSE token streaming contract · source wiki/ai-streaming.md

The AI Streaming System provides enhanced streaming capabilities for AI provider responses, including token counting, progress callbacks, cancellation, and state management.

Overview

The streaming system enhances the basic streaming functionality provided by AI providers with additional middleware capabilities:

  • Token Counting: Real-time token counting during streaming
  • Progress Callbacks: Callbacks for streaming progress updates
  • Cancellation: Ability to cancel in-progress streaming operations
  • State Management: Tracking of streaming state (idle, connecting, streaming, paused, completed, error, cancelled)
  • Statistics: Collection of streaming statistics (tokens per second, characters per second)
  • Chunked Streaming: Support for chunked streaming of large responses

Architecture

Provider Stream
     ↓
StreamingMiddleware
     ↓
Enhanced Stream (StreamingToken)
     ↓
StreamingAggregator (optional)
     ↓
Complete Response

Components

StreamingMiddleware

The main middleware component that enhances provider streams with additional capabilities.

from novacoder.ai.streaming import StreamingMiddleware, StreamingConfig

# Create middleware with custom configuration
config = StreamingConfig(
    enable_token_counting=True,
    enable_progress_callbacks=True,
    chunk_size=1,
    timeout=30.0,
    max_retries=3,
    enable_cancellation=True,
    enable_pause_resume=False
)

middleware = StreamingMiddleware(config)

StreamingToken

Enhanced token with metadata:

@dataclass
class StreamingToken:
    content: str
    token_index: int
    timestamp: datetime
    metadata: dict[str, Any]

StreamingConfig

Configuration for streaming operations:

@dataclass
class StreamingConfig:
    enable_token_counting: bool = True
    enable_progress_callbacks: bool = False
    chunk_size: int = 1
    timeout: float = 30.0
    max_retries: int = 3
    enable_cancellation: bool = True
    enable_pause_resume: bool = False

StreamingStats

Statistics for streaming operations:

@dataclass
class StreamingStats:
    total_tokens: int
    total_characters: int
    start_time: datetime
    end_time: datetime | None
    tokens_per_second: float
    characters_per_second: float
    error_count: int

Usage Examples

Basic Streaming Enhancement

from novacoder.ai.streaming import StreamingMiddleware
from novacoder.ai.provider import ChatMessage
import asyncio

async def stream_with_enhancement():
    middleware = StreamingMiddleware()
    
    # Get base stream from provider
    provider = manager.load("openai")
    messages = [ChatMessage(role="user", content="Hello")]
    base_stream = provider.stream(messages)
    
    # Enhance the stream
    enhanced_stream = middleware.enhance_stream(base_stream, messages)
    
    # Process enhanced tokens
    async for token in enhanced_stream:
        print(f"Token {token.token_index}: {token.content}")
        print(f"Rate: {middleware.get_stats().tokens_per_second:.2f} tokens/sec")

Progress Callbacks

def progress_callback(token: StreamingToken):
    print(f"Progress: {token.token_index} tokens")

def completion_callback(stats: StreamingStats):
    print(f"Completed: {stats.total_tokens} tokens in {stats.tokens_per_second:.2f} tokens/sec")

middleware = StreamingMiddleware(StreamingConfig(enable_progress_callbacks=True))
middleware.set_progress_callback(progress_callback)
middleware.set_completion_callback(completion_callback)

Cancellation

async def stream_with_cancellation():
    middleware = StreamingMiddleware(StreamingConfig(enable_cancellation=True))
    
    # Start streaming
    enhanced_stream = middleware.enhance_stream(base_stream, messages)
    
    # Cancel after some time
    asyncio.create_task(cancel_after_delay(middleware, 5.0))
    
    async for token in enhanced_stream:
        if middleware.get_state() == StreamingState.CANCELLED:
            print("Stream was cancelled")
            break
        print(token.content)

async def cancel_after_delay(middleware, delay):
    await asyncio.sleep(delay)
    middleware.cancel()

Pause/Resume

async def stream_with_pause_resume():
    config = StreamingConfig(enable_pause_resume=True)
    middleware = StreamingMiddleware(config)
    
    enhanced_stream = middleware.enhance_stream(base_stream, messages)
    
    async for token in enhanced_stream:
        print(token.content)
        
        # Pause after 10 tokens
        if token.token_index == 10:
            middleware.pause()
            await asyncio.sleep(2.0)
            middleware.resume()

Streaming Aggregation

from novacoder.ai.streaming import StreamingAggregator

async def aggregate_stream():
    middleware = StreamingMiddleware()
    aggregator = StreamingAggregator()
    
    enhanced_stream = middleware.enhance_stream(base_stream, messages)
    
    # Aggregate tokens into complete response
    complete_response = await aggregator.aggregate(enhanced_stream)
    print(f"Complete response: {complete_response}")
    
    # Get partial response during streaming
    partial = aggregator.get_partial()
    print(f"Partial so far: {partial}")

Integration with Providers

The streaming middleware works with any provider that implements the stream method:

from novacoder.ai.manager import ProviderManager

manager = ProviderManager()
provider = manager.load("openai")

# Use middleware with any provider
middleware = StreamingMiddleware()
enhanced_stream = middleware.enhance_stream(
    provider.stream(messages),
    messages
)

State Management

The streaming middleware tracks the current state:

from novacoder.ai.streaming import StreamingState

state = middleware.get_state()
# StreamingState.IDLE, CONNECTING, STREAMING, PAUSED, COMPLETED, ERROR, CANCELLED

Statistics

Access streaming statistics:

stats = middleware.get_stats()
print(f"Total tokens: {stats.total_tokens}")
print(f"Tokens per second: {stats.tokens_per_second:.2f}")
print(f"Characters per second: {stats.characters_per_second:.2f}")
print(f"Error count: {stats.error_count}")

Error Handling

The streaming middleware includes error callbacks:

def error_callback(error: Exception):
    print(f"Streaming error: {error}")

middleware.set_error_callback(error_callback)

Best Practices

  1. Enable Cancellation: Always enable cancellation for long-running streams
  2. Use Progress Callbacks: For UI applications, use progress callbacks to update the interface
  3. Monitor Statistics: Track streaming statistics to detect performance issues
  4. Handle Timeouts: Set appropriate timeout values based on expected response sizes
  5. Use Aggregation: Use StreamingAggregator when you need the complete response

Performance Considerations

  • Token Counting: Adds minimal overhead to streaming operations
  • Progress Callbacks: May impact performance if callback logic is heavy
  • Chunk Size: Larger chunk sizes can improve performance but reduce granularity
  • Memory Usage: Streaming uses constant memory regardless of response size

Configuration

Configure streaming behavior:

# High-performance configuration
config = StreamingConfig(
    enable_token_counting=False,  # Disable for maximum performance
    enable_progress_callbacks=False,
    chunk_size=10,  # Larger chunks
    timeout=60.0,
    enable_cancellation=True
)

# Feature-rich configuration
config = StreamingConfig(
    enable_token_counting=True,
    enable_progress_callbacks=True,
    chunk_size=1,  # Token-level granularity
    timeout=30.0,
    enable_cancellation=True,
    enable_pause_resume=True
)

Integration with AIService

The streaming system is integrated into the AIService for seamless use:

from novacoder.ai.service import AIService
from novacoder.ai.provider import ChatMessage

ai_service = AIService()
ai_service.initialize()

# Stream with circuit breaker protection
messages = [ChatMessage(role="user", content="Hello")]
async for token in ai_service.stream_chat(messages, task="chat"):
    print(token)

The stream_chat() method includes:

  • Circuit Breaker Protection: Checks circuit breaker state before streaming
  • Error Handling: Records failures and attempts recovery
  • Fallback Support: Automatically switches to fallback providers on failure

API Endpoints

GET /api/stream

Stream AI tokens as server-sent events (EventSource compatible).

Query Parameters:

  • message: The message to send
  • provider: The AI provider to use (optional)
  • model: The model to use (optional)

Response: Server-sent events with token chunks

POST /api/stream

Stream AI tokens as server-sent events with JSON payload.

Request Body:

{
  "message": "Hello",
  "provider": "openai",
  "model": "gpt-4"
}

Response: Server-sent events with token chunks

GET /api/ai/stream-metrics

Sanitized streaming telemetry (no prompt/response content, no credentials).

Response:

{
  "success": true,
  "data": {
    "sample_count": 7,
    "ttft_ms":  {"p50": 5400.6, "p95": 11562.3, "p99": 11562.3, "mean": 5930.5},
    "total_ms": {"p50": 13134.4, "p95": 76166.7, "mean": null},
    "prompt_ms_mean": 1.4,
    "tok_per_s_mean": 5.4,
    "errors": 0,
    "cancellations": 1,
    "recent": [ {"source": "agent", "ttft_ms": 718.4, "tokens": 17, "cancelled": true, ...} ]
  }
}

Ring buffer holds the last 500 requests. source is agent (default /api/stream path) or stream (direct provider path); prompt_ms is server-side message assembly, on this stack it is ~1 ms, so ttft_ms − prompt_ms is provider prefill+queueing.

Performance Notes (2026-10)

  • Provider clients are pooled. AIProvider._client_ctx(timeout) yields a shared httpx.AsyncClient, use it instead of async with httpx.AsyncClient(...) in provider code so TCP/TLS is not re-established per request.
  • Ollama requests hit /api/chat (native chat template) with a sticky fallback to /api/generate on 404; keep_alive=-1 keeps the model resident.
  • History context sent to the model is bounded (_HISTORY_CONTEXT_MESSAGES = 4 in routes_ai_2.py); _chat_history itself is capped at 500 entries.
  • Frontend renders are rAF-batched, Chat.tsx, AiPanel.tsx, Runtime.tsx coalesce token events into ≤1 React render per frame.
  • Ollama -np 1: one inference slot, concurrent requests serialize. Never run two bench_chat.py instances at once; queueing inflates TTFT.
  • Adaptive concurrency gate (ai/concurrency.py::AdaptiveLimiter): AIService.chat/stream_chat and RuntimeService.stream share one FIFO slot gate bounded by model.max_concurrent_streams (default 4). The effective limit sheds 4→2→1 under CPU/memory pressure (psutil, non-blocking) and recovers automatically. Wait time is recorded into stream-metrics.queue (inflight, queued, effective_limit, wait_ms_p50/p95). The slot is held per provider attempt, retry backoff never starves the gate.
  • Rolling history digest: the 12 turns just beyond the 4-message context window are injected as a compact system digest (_HISTORY_DIGEST_TURNS/_HISTORY_DIGEST_CHARS in routes_ai_2.py), older context is compressed, not dropped.
  • Benchmark: .venv/bin/python scripts/bench_chat.py --runs 2 --out reports/ai-chat-performance/run.json. System bench (boot/parallel/API-under-load/RSS): .venv/bin/python scripts/bench_system.py. Regression scanner: .venv/bin/python -m scan --only chat_performance. Audits: backups/reports_archive_2026-10-13/ai-chat-performance/33…35 (archived; consolidated into reports/NOVACODER_MASTER_DEVELOPMENT_ROADMAP.md).

Record 20 / 48 // Part III · Intelligence

AI Function Calling System

Tool-call plumbing · source wiki/ai-function-calling.md

The AI Function Calling System enables AI providers to call external functions and tools, allowing for more sophisticated interactions and real-world actions.

Overview

The function calling system provides:

  • Function Registry: Central registry for callable functions
  • Schema Validation: JSON schema validation for function parameters
  • Function Execution: Safe execution of function calls with error handling
  • Result Streaming: Streaming of function results back to AI
  • Call Parsing: Automatic parsing of function calls from AI responses
  • Middleware Integration: Seamless integration with AI provider middleware

Architecture

AI Response
     ↓
FunctionCallParser
     ↓
FunctionCallExecutor
     ↓
FunctionRegistry
     ↓
External Function
     ↓
FunctionResult
     ↓
Formatted Response

Components

FunctionRegistry

Central registry for managing callable functions:

from novacoder.ai.function_calling import FunctionRegistry, FunctionDefinition, FunctionParameter

registry = FunctionRegistry()

def add_numbers(x: int, y: int) -> int:
    return x + y

func_def = FunctionDefinition(
    name="add_numbers",
    description="Add two numbers together",
    parameters=[
        FunctionParameter("x", "number", "First number"),
        FunctionParameter("y", "number", "Second number")
    ],
    handler=add_numbers
)

registry.register(func_def)

FunctionDefinition

Definition of a callable function:

@dataclass
class FunctionDefinition:
    name: str
    description: str
    parameters: list[FunctionParameter]
    handler: Callable[..., Any]
    metadata: dict[str, Any]

FunctionParameter

Parameter definition for function schema:

@dataclass
class FunctionParameter:
    name: str
    type: str  # "string", "number", "boolean", "object", "array"
    description: str
    required: bool = True
    default: Any = None
    enum: list[Any] | None = None

FunctionCallExecutor

Executor for function calls with validation:

from novacoder.ai.function_calling import FunctionCallExecutor

executor = FunctionCallExecutor(registry)
result = await executor.execute(function_call)

FunctionCallParser

Parser for extracting function calls from AI responses:

from novacoder.ai.function_calling import FunctionCallParser

parser = FunctionCallParser()
calls = parser.parse_function_calls(ai_response)

FunctionCallingMiddleware

Middleware for handling function calling in AI interactions:

from novacoder.ai.function_calling import FunctionCallingMiddleware

middleware = FunctionCallingMiddleware()
formatted_response, results = await middleware.process_response(ai_response)

Usage Examples

Basic Function Registration

from novacoder.ai.function_calling import FunctionCallingMiddleware, FunctionDefinition, FunctionParameter

middleware = FunctionCallingMiddleware()

def get_weather(location: str) -> str:
    # Simulate weather API call
    return f"The weather in {location} is sunny"

func_def = FunctionDefinition(
    name="get_weather",
    description="Get current weather for a location",
    parameters=[
        FunctionParameter("location", "string", "City name")
    ],
    handler=get_weather
)

middleware.registry.register(func_def)

Processing AI Responses

import asyncio

async def process_with_function_calling():
    middleware = FunctionCallingMiddleware()
    
    # Register functions
    middleware.registry.register(get_weather_func)
    
    # AI response that includes function call
    ai_response = 'I need to call get_weather(location="New York")'
    
    # Process response
    formatted_response, results = await middleware.process_response(ai_response)
    
    print(f"Formatted response: {formatted_response}")
    print(f"Results: {results}")

Function Schema Generation

# Get JSON schema for a function
schema = middleware.registry.get_schema("get_weather")
print(schema)
# {
#     "name": "get_weather",
#     "description": "Get current weather for a location",
#     "parameters": {
#         "type": "object",
#         "properties": {
#             "location": {
#                 "type": "string",
#                 "description": "City name"
#             }
#         },
#         "required": ["location"]
#     }
# }

# Get all function schemas
all_schemas = middleware.registry.get_all_schemas()

Function Execution

from novacoder.ai.function_calling import FunctionCall

async def execute_function():
    call = FunctionCall(
        name="get_weather",
        arguments={"location": "Boston"}
    )
    
    result = await middleware.executor.execute(call)
    
    if result.success:
        print(f"Result: {result.result}")
        print(f"Execution time: {result.execution_time}s")
    else:
        print(f"Error: {result.error}")

Function History

# Get call history for a function
history = middleware.registry.get_call_history("get_weather", limit=10)

# Get all call history
all_history = middleware.registry.get_call_history(limit=100)

Tools Schema for AI Providers

# Get tools schema for AI providers (OpenAI, Anthropic, etc.)
tools_schema = middleware.get_tools_schema()
print(tools_schema)

Function Types

Simple Functions

def simple_function(text: str) -> str:
    return text.upper()

func_def = FunctionDefinition(
    name="uppercase",
    description="Convert text to uppercase",
    parameters=[
        FunctionParameter("text", "string", "Text to convert")
    ],
    handler=simple_function
)

Async Functions

async def async_function(url: str) -> str:
    import httpx
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        return response.text

func_def = FunctionDefinition(
    name="fetch_url",
    description="Fetch content from URL",
    parameters=[
        FunctionParameter("url", "string", "URL to fetch")
    ],
    handler=async_function
)

Functions with Enums

func_def = FunctionDefinition(
    name="set_status",
    description="Set status",
    parameters=[
        FunctionParameter(
            "status",
            "string",
            "Status value",
            enum=["active", "inactive", "pending"]
        )
    ],
    handler=set_status
)

Functions with Optional Parameters

func_def = FunctionDefinition(
    name="search",
    description="Search database",
    parameters=[
        FunctionParameter("query", "string", "Search query", required=True),
        FunctionParameter("limit", "number", "Result limit", required=False, default=10)
    ],
    handler=search_function
)

Error Handling

The function calling system includes comprehensive error handling:

# Function validation
errors = middleware.executor._validator.validate_call(function_call, function_def)
if errors:
    print(f"Validation errors: {errors}")

# Execution errors
result = await middleware.executor.execute(function_call)
if not result.success:
    print(f"Execution error: {result.error}")

Integration with AI Providers

OpenAI Function Calling

from novacoder.ai.providers.openai import OpenAIProvider

provider = OpenAIProvider()
middleware = FunctionCallingMiddleware()

# Register functions
middleware.registry.register(my_function)

# Get tools schema
tools = middleware.get_tools_schema()

# Use in OpenAI API call
response = await provider.chat(
    messages,
    tools=tools,
    tool_choice="auto"
)

Anthropic Function Calling

from novacoder.ai.providers.anthropic import AnthropicProvider

provider = AnthropicProvider()
middleware = FunctionCallingMiddleware()

# Similar integration for Anthropic
tools = middleware.get_tools_schema()
response = await provider.chat(messages, tools=tools)

Best Practices

  1. Function Naming: Use clear, descriptive function names
  2. Parameter Validation: Always validate function parameters
  3. Error Handling: Handle errors gracefully in function handlers
  4. Documentation: Provide clear descriptions for functions and parameters
  5. Type Safety: Use proper type hints for function parameters
  6. Async Functions: Use async functions for I/O operations
  7. Security: Validate and sanitize all inputs to functions
  8. Testing: Test functions independently before registering

Security Considerations

  • Input Validation: Always validate function inputs
  • Sandboxing: Consider running functions in a sandboxed environment
  • Permission Checks: Implement permission checks for sensitive operations
  • Rate Limiting: Add rate limiting for expensive operations
  • Logging: Log all function calls for audit purposes

Performance Considerations

  • Async Execution: Use async functions for I/O-bound operations
  • Caching: Cache results of expensive function calls
  • Timeouts: Implement timeouts for long-running functions
  • Resource Limits: Set resource limits for function execution

Configuration

Configure function calling behavior:

# Enable/disable function calling
middleware.enable()
middleware.disable()

# Check if enabled
if middleware.is_enabled():
    # Process with function calling
    pass

Record 21 / 48 // Part III · Intelligence

AI Context Window Management

History windowing and tokens · source wiki/ai-context-window.md

The AI Context Window Management system provides intelligent context management for AI conversations, including token counting, truncation strategies, and context optimization.

Overview

The context window management system provides:

  • Context Window Tracking: Per-provider context window limits
  • Token Counting: Accurate token counting for messages
  • Truncation Strategies: Multiple strategies for handling large contexts
  • Context Compression: Advanced compression with semantic deduplication
  • Dynamic Context Sizing: Automatic adjustment based on conversation complexity
  • Context Optimization: Combined dynamic sizing, compression, and truncation
  • Violation Handling: Graceful handling of context window violations
  • Message Importance: Importance-based message prioritization

Architecture

Messages
     ↓
ContextWindowManager
     ↓
Token Counting
     ↓
Window Check
     ↓
Truncation (if needed)
     ↓
Compressed Messages

Components

ContextWindowManager

Main manager for context window operations:

from novacoder.ai.context_window import ContextWindowManager, ContextWindowConfig

config = ContextWindowConfig(
    max_tokens=4096,
    truncation_strategy=TruncationStrategy.OLDEST_FIRST,
    reserve_tokens=512,
    enable_compression=False,
    compression_ratio=0.7,
    enable_summarization=False
)

manager = ContextWindowManager(config)

TruncationStrategy

Strategies for context truncation:

from novacoder.ai.context_window import TruncationStrategy

# Truncate oldest messages first
TruncationStrategy.OLDEST_FIRST

# Truncate newest messages first
TruncationStrategy.NEWEST_FIRST

# Truncate system messages first (last resort)
TruncationStrategy.SYSTEM_FIRST

# Truncate based on message importance
TruncationStrategy.IMPORTANCE_BASED

# Truncate based on semantic similarity
TruncationStrategy.SEMANTIC

ContextStats

Statistics for context window usage:

@dataclass
class ContextStats:
    total_tokens: int
    used_tokens: int
    available_tokens: int
    utilization: float
    truncation_count: int
    compression_count: int
    summarization_count: int

Usage Examples

Basic Context Management

from novacoder.ai.context_window import ContextWindowManager
from novacoder.ai.provider import ChatMessage

manager = ContextWindowManager()

# Set provider-specific limits
manager.set_provider_limit("openai", "gpt-4", 8192)
manager.set_provider_limit("anthropic", "claude-3-opus", 200000)

messages = [
    ChatMessage(role="system", content="You are a helpful assistant"),
    ChatMessage(role="user", content="Hello"),
    ChatMessage(role="assistant", content="Hi there!"),
]

# Check if messages fit within context window
stats = manager.check_window(messages, "openai", "gpt-4")
print(f"Tokens used: {stats.used_tokens}")
print(f"Tokens available: {stats.available_tokens}")
print(f"Utilization: {stats.utilization:.1%}")

Context Truncation

# Truncate context if it exceeds window
truncated_messages = manager.truncate_context(messages, "openai", "gpt-4")
print(f"Original: {len(messages)} messages")
print(f"Truncated: {len(truncated_messages)} messages")

Different Truncation Strategies

from novacoder.ai.context_window import TruncationStrategy, ContextWindowConfig

# Oldest first (default)
config = ContextWindowConfig(truncation_strategy=TruncationStrategy.OLDEST_FIRST)
manager = ContextWindowManager(config)

# Newest first
config = ContextWindowConfig(truncation_strategy=TruncationStrategy.NEWEST_FIRST)
manager = ContextWindowManager(config)

# Importance-based
config = ContextWindowConfig(truncation_strategy=TruncationStrategy.IMPORTANCE_BASED)
manager = ContextWindowManager(config)

# Set message importance
manager.set_message_importance(important_message, importance=1.0)
manager.set_message_importance(less_important_message, importance=0.5)

Context Compression

# Enable compression
config = ContextWindowConfig(
    enable_compression=True,
    compression_ratio=0.7
)
manager = ContextWindowManager(config)

# Compress context
compressed_messages = manager.compress_context(messages)
print(f"Compression count: {manager.get_stats().compression_count}")

Advanced Compression Strategies

The context compression uses three strategies:

  1. Duplicate Consecutive Removal: Removes duplicate consecutive messages
  2. Similar Message Removal: Removes messages with >80% semantic similarity
  3. Short Message Merging: Merges consecutive short messages (<50 chars) from the same role
# Compression is automatically applied when enabled
config = ContextWindowConfig(enable_compression=True)
manager = ContextWindowManager(config)

# The compress_context method applies all three strategies
compressed = manager.compress_context(messages)

Provider-Specific Limits

# Set limits for different providers and models
manager.set_provider_limit("openai", "gpt-4", 8192)
manager.set_provider_limit("openai", "gpt-4-turbo", 128000)
manager.set_provider_limit("anthropic", "claude-3-opus", 200000)
manager.set_provider_limit("anthropic", "claude-3-sonnet", 200000)
manager.set_provider_limit("google", "gemini-pro", 32000)

# Get limit for a specific provider/model
limit = manager.get_provider_limit("openai", "gpt-4")
print(f"GPT-4 limit: {limit} tokens")

Message Importance

# Set importance for specific messages
system_message = ChatMessage(role="system", content="System instructions")
user_message = ChatMessage(role="user", content="User question")

manager.set_message_importance(system_message, importance=1.0)  # High importance
manager.set_message_importance(user_message, importance=0.8)  # Medium importance

# When using importance-based truncation
config = ContextWindowConfig(truncation_strategy=TruncationStrategy.IMPORTANCE_BASED)
manager = ContextWindowManager(config)
truncated = manager.truncate_context(messages, "openai", "gpt-4")

Statistics and Monitoring

# Get current statistics
stats = manager.get_stats()
print(f"Total tokens: {stats.total_tokens}")
print(f"Used tokens: {stats.used_tokens}")
print(f"Available tokens: {stats.available_tokens}")
print(f"Utilization: {stats.utilization:.1%}")
print(f"Truncation count: {stats.truncation_count}")
print(f"Compression count: {stats.compression_count}")

# Reset statistics
manager.reset_stats()

Dynamic Context Sizing

# Calculate dynamic context window limit based on conversation complexity
dynamic_limit = manager.calculate_dynamic_limit(
    messages,
    provider="openai",
    model="gpt-4",
    conversation_complexity=0.5
)
print(f"Dynamic limit: {dynamic_limit} tokens")

# Calculate conversation complexity score
complexity = manager.calculate_conversation_complexity(messages)
print(f"Conversation complexity: {complexity:.2f} (0.0 to 1.0)")

Context Optimization

# Optimize context with dynamic sizing, compression, and truncation
optimized_messages, stats = manager.optimize_context(
    messages,
    provider="openai",
    model="gpt-4"
)
print(f"Optimized messages: {len(optimized_messages)}")
print(f"Final stats: {stats}")

Integration with AI Providers

Before Making API Calls

from novacoder.ai.manager import ProviderManager
from novacoder.ai.context_window import ContextWindowManager

provider_manager = ProviderManager()
context_manager = ContextWindowManager()

# Get provider
provider = provider_manager.load("openai", model="gpt-4")

# Check context window
stats = context_manager.check_window(messages, "openai", "gpt-4")

if stats.available_tokens < 0:
    # Truncate context
    messages = context_manager.truncate_context(messages, "openai", "gpt-4")

# Make API call with safe context
response = await provider.chat(messages)

With Streaming

# Check context before streaming
stats = context_manager.check_window(messages, "openai", "gpt-4")

if stats.available_tokens >= 0:
    # Safe to stream
    stream = provider.stream(messages)
else:
    # Truncate first
    messages = context_manager.truncate_context(messages, "openai", "gpt-4")
    stream = provider.stream(messages)

Truncation Strategies Explained

Oldest First (Default)

Removes the oldest messages first, keeping the most recent context:

config = ContextWindowConfig(truncation_strategy=TruncationStrategy.OLDEST_FIRST)

Best for: Conversations where recent context is most important

Newest First

Removes the newest messages first, keeping the original context:

config = ContextWindowConfig(truncation_strategy=TruncationStrategy.NEWEST_FIRST)

Best for: Conversations where initial context is most important

System First

Removes system messages first (use as last resort):

config = ContextWindowConfig(truncation_strategy=TruncationStrategy.SYSTEM_FIRST)

Best for: When system messages are less critical than conversation history

Importance-Based

Removes messages based on their importance scores:

config = ContextWindowConfig(truncation_strategy=TruncationStrategy.IMPORTANCE_BASED)
manager.set_message_importance(message, importance=0.9)

Best for: Conversations with clearly defined message priorities

Best Practices

  1. Set Appropriate Limits: Use provider-specific context window limits
  2. Reserve Tokens: Always reserve tokens for the response
  3. Choose Right Strategy: Select truncation strategy based on use case
  4. Monitor Utilization: Track context utilization to detect issues
  5. Use Compression: Enable compression for long conversations
  6. Set Importance: Use message importance for critical messages
  7. Check Before API Calls: Always check context window before API calls

Performance Considerations

  • Token Counting: Token counting is fast but adds overhead
  • Compression: Compression adds overhead but reduces token usage
  • Truncation: Truncation is fast but may lose important context
  • Memory Usage: Context management uses minimal memory

Configuration

Configure context window behavior:

# Conservative configuration
config = ContextWindowConfig(
    max_tokens=4096,
    reserve_tokens=1024,  # Large reserve
    truncation_strategy=TruncationStrategy.OLDEST_FIRST,
    enable_compression=False
)

# Aggressive configuration
config = ContextWindowConfig(
    max_tokens=8192,
    reserve_tokens=256,  # Small reserve
    truncation_strategy=TruncationStrategy.IMPORTANCE_BASED,
    enable_compression=True,
    compression_ratio=0.6
)

Error Handling

The context window manager handles errors gracefully:

# If provider limit is not set, uses default
limit = manager.get_provider_limit("unknown_provider", "unknown_model")
# Returns default max_tokens

# If messages are empty, returns 0 tokens
stats = manager.check_window([], "openai", "gpt-4")
# Returns 0 tokens used

REST API

The ContextWindowManager on AIService is exposed via novacoder/api/routes_ai_prompts.py:

Endpoint Description
GET /api/ai/context/stats Rolling ContextStats (total/used/available, utilization, truncation/compression/summarization counters)
GET /api/ai/context/limit?provider=&model= Effective window limit for a provider/model
POST /api/ai/context/limit Override the limit: {"provider", "model", "limit"}
POST /api/ai/context/check {"messages", "provider?", "model?"} → ContextStats for those messages
POST /api/ai/context/truncate Truncate messages to fit the window (strategy from config)
POST /api/ai/context/compress Compress messages (dedup, merge, code-block compression)
POST /api/ai/context/optimize Dynamic-limit + compress + truncate; returns messages and stats
POST /api/ai/context/complexity Conversation complexity score (0–1)

The React Chat page shows a ctx used/total badge from check (warns above 80% utilization); the AI page renders stats and an optimize action under "Prompts & Context".

Record 22 / 48 // Part IV · Workspace

Workspace

Roots, files and project state · source wiki/workspace.md

The Workspace subsystem gives Nova Coder an understanding of the project it is working on. The indexing pipeline lives in novacoder/indexing/ and is consumed by WorkspaceService to scan directories, detect languages, parse ASTs, extract symbols, and build indexes.

Pipeline

Project Directory
       ↓
Directory Walker
       ↓
Language Detection
       ↓
AST Parser
       ↓
Symbol Extraction
       ↓
Dependency Graph
       ↓
Symbol Index
       ↓
Database

ProjectScanner

ProjectScanner recursively discovers files and produces metadata:

from novacoder.workspace.scanner import ProjectScanner

scanner = ProjectScanner("/path/to/project")
files = scanner.scan()

for path, entry in files.items():
    print(entry.language, entry.size, entry.hash)

print(scanner.summary())

# Incremental scan
changed = scanner.scan(incremental=True)
deleted = scanner.last_deleted

Exclusion Patterns

The scanner skips directories and files matching configured patterns:

workspace:
  exclude_patterns:
    - .git
    - __pycache__
    - node_modules
    - .venv
    - "*.pyc"
    - "test_*.py"
    - "**/*.log"

Language Detection

LanguageDetector maps file extensions to languages:

from novacoder.workspace.languages import LanguageDetector

print(LanguageDetector.detect("main.py"))      # python
print(LanguageDetector.detect("app.js"))         # javascript
print(LanguageDetector.detect("README.md"))      # markdown

Supported languages include Python, JavaScript, TypeScript, Rust, Go, C, C++, Java, C#, PHP, Ruby, Lua, Swift, Kotlin, and more.

Symbol Extraction

SymbolExtractor dispatches to a language-specific extractor. It currently supports Python, JavaScript, and TypeScript (with a regex-based extractor), plus a generic fallback for unsupported languages.

from novacoder.workspace.symbols import SymbolExtractor

extractor = SymbolExtractor()
result = extractor.extract("main.py")

print(result["classes"])
print(result["functions"])
print(result["imports"])

Python extraction uses the ast module with an O(n) parent map to correctly identify methods. JavaScript and TypeScript extractors use regex to capture imports, classes, interfaces, and functions.

SymbolIndex

SymbolIndex stores extracted symbols for fast lookup:

from novacoder.workspace.symbols import SymbolIndex

index = SymbolIndex()
index.add(result["symbols"])

classes = index.find(kind="class")
methods = index.find(name="my_method")

WorkspaceService

WorkspaceService is the kernel service that orchestrates scanning and indexing:

from novacoder.workspace.service import WorkspaceService
from novacoder.config.settings import AppConfig

service = WorkspaceService(config=AppConfig())
service.initialize()
service.start()  # scans if index_on_start is true and not already scanned

print(service.summary())

# Public API
entry = service.get_file("main.py")
files = service.list_files(language="python")
symbols = service.get_symbols(kind="class")
graph = service.import_graph
print(graph.dependents_of("main.py"))

File Entry Format

{
  "path": "src/main.py",
  "language": "python",
  "size": 1024,
  "hash": "a1b2c3d4",
  "imports": ["os", "sys"],
  "classes": ["MyClass"],
  "functions": ["main"],
  "summary": "",
  "dependencies": []
}

Incremental Indexing

ProjectScanner.scan(incremental=True) only re-reads and returns files whose hashes have changed. WorkspaceService uses this to update the SymbolIndex and ImportGraph without rebuilding the entire index. Files read once per scan are reused for symbol extraction, eliminating the previous double-read.

Workspace Events

WorkspaceService publishes events through the EventBus when available:

  • WorkspaceScanned, a scan completed
  • WorkspaceFileChanged, a file was added, modified, or deleted
  • WorkspaceSymbolsUpdated, the symbol index was refreshed

Import Graph

WorkspaceService builds an ImportGraph from file imports. It supports dependency/dependent queries and cycle detection:

from novacoder.graphs import ImportGraph

graph = ImportGraph()
graph.add_imports("main", ["helper"])
print(graph.dependents_of("helper"))  # {'main'}
print(graph.cycle_free())  # True

CLI and TUI Integration

Workspace features are exposed through the CLI and the terminal UI:

# Scan from the command line
python -m novacoder.cli.main scan /path/to/project

In the TUI (novacoder gui or python -m novacoder.cli.main gui), the Workspace page shows the project root, total files, language breakdown, and a searchable symbol table. Clicking Re-scan triggers WorkspaceService.scan() and refreshes the symbol list.

Development Instructions

Adding a New Language Detector Mapping

Edit LanguageDetector.EXTENSIONS in novacoder/workspace/languages.py. If the language needs special handling beyond extension matching, update detect().

Adding a New Symbol Extractor

  1. Create a new extractor class in novacoder/indexing/extractors/ extending LanguageExtractor.
  2. Register it in novacoder/indexing/extractors/__init__.py under EXTRACTORS.
  3. SymbolExtractor will dispatch to it automatically based on LanguageDetector.
  4. Add tests in tests/test_workspace.py.

Testing the Scanner

def test_scanner_finds_files(tmp_path):
    (tmp_path / "main.py").write_text("pass")
    scanner = ProjectScanner(tmp_path)
    files = scanner.scan()
    assert len(files) == 1
    assert files[tmp_path / "main.py"].language == "python"

Testing Symbol Extraction

def test_symbol_extractor(tmp_path):
    file = tmp_path / "module.py"
    file.write_text("class Foo:\n    def bar(self): pass\n")
    result = SymbolExtractor().extract(file)
    assert "Foo" in result["classes"]
    assert "bar" in result["functions"]

Adding Exclusion Patterns

Add patterns to WorkspaceConfig.exclude_patterns in novacoder/config/settings.py and to config/defaults.yaml.

Future Enhancements

  • tree-sitter based multi-language AST parsing
  • Call graph and inheritance graph (implemented)
  • Knowledge graph integration (implemented)
  • Vector embeddings for semantic search (implemented)
  • File watcher for live updates (implemented)
  • Code search capabilities (implemented)
  • Code security analysis (implemented)
  • Code navigation features (implemented)
  • Code refactoring (implemented)
  • Remote workspace support (implemented)
  • Code metrics collection (implemented)
  • Dependency analysis (implemented)
  • Testing integration (implemented)
  • Workspace analytics (implemented)
  • Code documentation generation (implemented)
  • Code formatting (implemented)
  • Code visualization (implemented)
  • Multi-workspace support (implemented)
  • Parallel processing (implemented)

New Workspace Enhancement Systems

The workspace now includes a powerful code search engine with full-text and regex support:

from novacoder.workspace import CodeSearchEngine, SearchQuery

engine = ws_service.search_engine
query = SearchQuery(query="function_name", search_type="text")
results = engine.search(query)

for result in results:
    print(f"{result.file_path}:{result.line_number} - {result.line_content}")

Code Security Analysis

Static application security testing (SAST) with secret detection:

from novacoder.workspace import CodeSecurityAnalyzer

analyzer = ws_service.security_analyzer
vulnerabilities = analyzer.analyze()

for vuln in vulnerabilities:
    print(f"{vuln.severity}: {vuln.vulnerability_type} in {vuln.file_path}:{vuln.line_number}")

Code Navigation

Go-to-definition and find-references capabilities:

from novacoder.workspace import CodeNavigator

navigator = ws_service.code_navigator
location = navigator.go_to_definition("file.py", 10, 5)
references = navigator.find_references("my_function")

Code Refactoring

Safe code refactoring with validation:

from novacoder.workspace import CodeRefactorer

refactorer = ws_service.code_refactorer
result = refactorer.rename_symbol("old_name", "new_name")

Remote Workspace

Git repository cloning and remote repository management:

from novacoder.workspace import RemoteWorkspaceManager, RemoteRepository

manager = ws_service.remote_manager
repo = RemoteRepository(url="https://github.com/user/repo", provider="github")
manager.clone_repository(repo)

Code Metrics

Cyclomatic complexity and maintainability analysis:

from novacoder.workspace import CodeMetricsCollector

collector = ws_service.metrics_collector
metrics = collector.collect("file.py")
print(f"Complexity: {metrics.cyclomatic_complexity}")
print(f"Maintainability: {metrics.maintainability_index}")

Dependency Analysis

Package dependency analysis and vulnerability scanning:

from novacoder.workspace import DependencyAnalyzer

analyzer = ws_service.dependency_analyzer
dependencies = analyzer.analyze()
vulnerabilities = analyzer.check_vulnerabilities()

Testing Integration

Test discovery and coverage analysis:

from novacoder.workspace import TestingIntegration

testing = ws_service.testing_integration
test_files = testing.discover_tests()
coverage = testing.analyze_coverage()

Workspace Analytics

Code growth tracking and contributor activity analysis:

from novacoder.workspace import WorkspaceAnalytics

analytics = ws_service.workspace_analytics
growth = analytics.track_code_growth()
activity = analytics.analyze_contributor_activity()
hot_spots = analytics.detect_hot_spots()

Record 23 / 48 // Part IV · Workspace

Multi-Workspace Support

Multi-root workspaces · source wiki/workspace-multi-workspace.md

Comprehensive multi-workspace management with templates, cloning, snapshots, sharing, archiving, and statistics.

Overview

The MultiWorkspaceManager provides comprehensive multi-workspace management capabilities including:

  • Multiple workspace configuration
  • Workspace templates (empty, python, javascript, web, data_science, full_stack)
  • Workspace switching with status management
  • Workspace cloning
  • Workspace snapshots and restoration
  • Workspace sharing with permissions
  • Workspace archiving
  • JSON persistence for workspace configurations
  • Active workspace tracking
  • Workspace metadata support
  • Comprehensive statistics

Components

from novacoder.workspace.multi_workspace import (
    MultiWorkspaceManager, WorkspaceConfig, WorkspaceStatus,
    WorkspaceTemplate, WorkspaceSnapshot, WorkspaceShare
)

manager = MultiWorkspaceManager("/path/to/base")
config = WorkspaceConfig("project1", "/path/to/project1")
manager.add_workspace(config)

Usage

Create Workspace from Template

Creates a new workspace from a template:

success = manager.create_workspace(
    name="project1",
    path="/path/to/project1",
    template=WorkspaceTemplate.PYTHON
)

Available templates:

  • WorkspaceTemplate.EMPTY - Empty workspace
  • WorkspaceTemplate.PYTHON - Python project with main.py, requirements.txt, .gitignore
  • WorkspaceTemplate.JAVASCRIPT - JavaScript project with index.js, package.json
  • WorkspaceTemplate.WEB - Web project with HTML, CSS, JS files
  • WorkspaceTemplate.DATA_SCIENCE - Data science project with notebook.ipynb
  • WorkspaceTemplate.FULL_STACK - Full-stack project template

Add Workspace

Adds a new workspace configuration:

config = WorkspaceConfig(
    name="project1",
    path="/path/to/project1",
    active=False,
    status=WorkspaceStatus.INACTIVE,
    template=WorkspaceTemplate.PYTHON,
    metadata={"description": "Main project"}
)
success = manager.add_workspace(config)

Switch Workspace

Switches to a different workspace, marking it as active:

success = manager.switch_workspace("project1")
if success:
    print("Switched to project1")

Clone Workspace

Clones an existing workspace:

success = manager.clone_workspace(
    source_name="project1",
    target_name="project1-clone",
    target_path="/path/to/project1-clone"
)

Create Snapshot

Creates a snapshot of a workspace:

snapshot = manager.create_snapshot("project1", description="Before major refactoring")
print(f"Snapshot ID: {snapshot.snapshot_id}")

Restore Snapshot

Restores a workspace from a snapshot:

success = manager.restore_snapshot(
    snapshot_id="snapshot-id",
    target_name="project1-restored",
    target_path="/path/to/project1-restored"
)

Share Workspace

Shares a workspace with another user:

share = manager.share_workspace(
    workspace_name="project1",
    shared_with="user@example.com",
    permissions=["read", "write"]
)
print(f"Share ID: {share.share_id}")

Revoke Share

Revokes a workspace share:

success = manager.revoke_share(share_id="share-id")

Archive Workspace

Archives a workspace:

success = manager.archive_workspace("project1")

List Workspaces

Lists all configured workspaces:

workspaces = manager.list_workspaces()
for ws in workspaces:
    print(f"{ws.name}: {ws.path} (active: {ws.active}, status: {ws.status.value})")

Get Active Workspace

Retrieves the currently active workspace:

active = manager.get_active_workspace()
if active:
    print(f"Active: {active.name}")

Get Specific Workspace

Retrieves a specific workspace by name:

workspace = manager.get_workspace("project1")
if workspace:
    print(f"Path: {workspace.path}")
    print(f"Status: {workspace.status.value}")
    print(f"Template: {workspace.template.value}")

List Snapshots

Lists snapshots for a workspace:

snapshots = manager.list_snapshots("project1")
for snap in snapshots:
    print(f"{snap.snapshot_id}: {snap.description}")

List Shares

Lists shares for a workspace:

shares = manager.list_shares("project1")
for share in shares:
    print(f"{share.shared_with}: {share.permissions}")

Get Statistics

Gets workspace statistics:

stats = manager.get_statistics()
print(f"Total workspaces: {stats['total_workspaces']}")
print(f"Active workspaces: {stats['active_workspaces']}")
print(f"Archived workspaces: {stats['archived_workspaces']}")
print(f"Shared workspaces: {stats['shared_workspaces']}")
print(f"Total snapshots: {stats['total_snapshots']}")
print(f"Total shares: {stats['total_shares']}")

Remove Workspace

Removes a workspace configuration:

success = manager.remove_workspace("project1", delete_files=True)

Data Structures

WorkspaceConfig

Represents a workspace configuration:

  • name: Unique workspace name
  • path: Path to the workspace directory
  • active: Whether this is the active workspace
  • status: Workspace status (ACTIVE, INACTIVE, ARCHIVED, CLONED, SHARED)
  • template: Workspace template used
  • created_at: Creation timestamp
  • last_accessed: Last access timestamp
  • metadata: Additional metadata dictionary
  • dependencies: List of workspace dependencies
  • shared_with: List of users workspace is shared with

WorkspaceStatus

Enum for workspace status:

  • ACTIVE - Currently active workspace
  • INACTIVE - Not active
  • ARCHIVED - Archived workspace
  • CLONED - Cloned workspace
  • SHARED - Shared workspace

WorkspaceTemplate

Enum for workspace templates:

  • EMPTY - Empty workspace
  • PYTHON - Python project
  • JAVASCRIPT - JavaScript project
  • WEB - Web project
  • DATA_SCIENCE - Data science project
  • FULL_STACK - Full-stack project

WorkspaceSnapshot

Represents a workspace snapshot:

  • snapshot_id: Unique snapshot identifier
  • workspace_name: Name of the workspace
  • created_at: Creation timestamp
  • description: Snapshot description
  • metadata: Additional metadata

WorkspaceShare

Represents a workspace share:

  • share_id: Unique share identifier
  • workspace_name: Name of the workspace
  • shared_with: User to share with
  • permissions: List of permissions (read, write, admin)
  • shared_at: Share timestamp
  • expires_at: Expiration timestamp

Integration

WorkspaceService

from novacoder.workspace.service import WorkspaceService

service = WorkspaceService()
service.initialize()
manager = service.multi_workspace_manager

Web API

GET /api/workspace/workspaces
POST /api/workspace/create-workspace
POST /api/workspace/clone-workspace
POST /api/workspace/create-snapshot
POST /api/workspace/restore-snapshot
POST /api/workspace/share-workspace
DELETE /api/workspace/revoke-share
POST /api/workspace/archive-workspace
GET /api/workspace/statistics

CLI

novacoder workspace list-workspaces
novacoder workspace add-workspace project1 /path/to/project1
novacoder workspace switch-workspace project1
novacoder workspace create-workspace project1 /path/to/project1 --template python
novacoder workspace clone-workspace project1 project1-clone /path/to/clone
novacoder workspace create-snapshot project1 "Before refactoring"
novacoder workspace restore-snapshot snapshot-id project1-restored /path/to/restored
novacoder workspace share-workspace project1 user@example.com read,write
novacoder workspace archive-workspace project1

TUI

View workspaces table in the Workspace page with status, template, and actions.

Features

  • Workspace Templates: Pre-configured templates for different project types
  • Workspace Cloning: Clone existing workspaces with metadata tracking
  • Workspace Snapshots: Create and restore workspace snapshots
  • Workspace Sharing: Share workspaces with granular permissions
  • Workspace Archiving: Archive workspaces without deleting files
  • JSON Persistence: Automatically saves workspace configurations to .novacoder/workspaces.json
  • Snapshot Persistence: Automatically saves snapshots to .novacoder/snapshots.json
  • Share Persistence: Automatically saves shares to .novacoder/shares.json
  • Active Tracking: Tracks which workspace is currently active
  • Status Management: Track workspace status (active, inactive, archived, cloned, shared)
  • Metadata Support: Stores additional metadata with each workspace
  • Path Validation: Validates workspace paths before adding
  • Error Handling: Gracefully handles non-existent workspaces
  • Comprehensive Statistics: Detailed statistics on workspaces, snapshots, and shares

Configuration Files

Workspace Configurations

Stored in:

~/.config/novacoder/workspaces.json

Format:

{
  "project1": {
    "name": "project1",
    "path": "/path/to/project1",
    "active": true,
    "status": "active",
    "template": "python",
    "created_at": "2026-07-31T00:00:00",
    "last_accessed": "2026-07-31T12:00:00",
    "metadata": {},
    "dependencies": [],
    "shared_with": []
  }
}

Snapshots

Stored in:

~/.config/novacoder/snapshots.json

Format:

[
  {
    "snapshot_id": "uuid",
    "workspace_name": "project1",
    "created_at": "2026-07-31T00:00:00",
    "description": "Before refactoring",
    "metadata": {}
  }
]

Shares

Stored in:

~/.config/novacoder/shares.json

Format:

[
  {
    "share_id": "uuid",
    "workspace_name": "project1",
    "shared_with": "user@example.com",
    "permissions": ["read", "write"],
    "shared_at": "2026-07-31T00:00:00",
    "expires_at": ""
  }
]

REST API

The manager is exposed via novacoder/api/routes_workspace_multi.py:

Endpoint Description
GET /api/workspace/workspaces List configured workspaces
POST /api/workspace/workspaces Add ({"name","path"}) or create ("create":true + "template") a workspace
GET /api/workspace/workspaces/active Currently active workspace
POST /api/workspace/workspaces/{name}/switch Mark a workspace active
DELETE /api/workspace/workspaces/{name} Remove (optional ?delete_files=true)
POST /api/workspace/workspaces/{name}/clone Clone to {"target_name","target_path"}
POST /api/workspace/workspaces/{name}/archive Archive a workspace
GET/POST /api/workspace/workspaces/{name}/snapshots List / create snapshots
POST /api/workspace/snapshots/{id}/restore Restore to {"target_name","target_path"}
GET/POST /api/workspace/workspaces/{name}/share List / create shares ({"shared_with","permissions"})
DELETE /api/workspace/shares/{share_id} Revoke a share
POST /api/workspace/merge Merge two paths, strategies copy, git-merge, manual (dry-run plan)

File-watcher control (the workspace.watch flag still controls boot-time auto-start):

Endpoint Description
GET /api/workspace/watcher {running, path}
POST /api/workspace/watcher/start Start the watcher thread
POST /api/workspace/watcher/stop Stop the watcher thread

The React Workspace page surfaces all of this under "Multi-Workspace & Watcher" (add form, per-workspace switch/snapshot/archive/remove, merge form, watcher toggle).

  • Workspace
  • Advanced Workspace
  • Workspace Analytics

IDE Integration (multi-root)

The React IDE is multi-root aware. GET /api/ide/info now returns a roots array, the primary workspace plus every configured MultiWorkspaceManager workspace, and the toolbar root selector switches the active root via POST /api/workspace/switch with {"name": "<workspace>"} (the sentinel "__primary__" selects the primary workspace).

Switching calls WorkspaceService.set_active_root(path) which retargets service.workspace, _project_path, and the path-scoped engines (indexer/symbol graph) so IDE file reads, tree browsing, search, and debug sessions resolve against the newly active root. Removing the active workspace falls back to the primary root via MultiWorkspaceManager.clear_active(). The pre-existing bare-array GET /api/workspace/workspaces contract in routes_workspace_enhancement_systems.py is preserved.

On a root switch the IDE closes all open tabs (paths are root-relative), clears breakpoints/diagnostics/decorations, and invalidates the editor/tree React Query caches.

Tests: tests/test_ide_roots.py (6 tests).

Record 24 / 48 // Part IV · Workspace

Remote Workspace

Confined remote clones · source wiki/workspace-remote.md

Git repository cloning and remote repository management support with production-quality git integration.

Components

from novacoder.workspace import RemoteWorkspaceManager, RemoteRepository

manager = RemoteWorkspaceManager("/path/to/workspace")
repo = RemoteRepository(url="https://github.com/user/repo", provider="github", branch="main")
manager.clone_repository(repo)

Features

  • Git Integration: Full git clone and pull functionality using subprocess
  • Error Handling: Comprehensive error logging for all git operations
  • Repository Info: Get repository information including current branch, latest commit, and remote URL
  • Branch Support: Clone specific branches from remote repositories
  • Provider Support: Works with GitHub, GitLab, Bitbucket, and other git providers

Usage

Clone Repository

repo = RemoteRepository(
    url="https://github.com/user/repo",
    provider="github",
    branch="main",
    local_path="my-project"
)
success = manager.clone_repository(repo)
if success:
    print("Repository cloned successfully")

Pull Changes

repo = RemoteRepository(
    url="https://github.com/user/repo",
    provider="github",
    branch="main",
    local_path="my-project"
)
success = manager.pull_changes(repo)
if success:
    print("Changes pulled successfully")

Get Repository Information

info = manager.get_repository_info(repo)
if info:
    print(f"Current branch: {info['current_branch']}")
    print(f"Latest commit: {info['latest_commit']['hash']}")
    print(f"Remote URL: {info['remote_url']}")

Integration

service = WorkspaceService()
manager = service.remote_manager

Error Handling

All git operations include comprehensive error handling and logging:

  • Git availability checks before operations
  • Detailed error messages for failed operations
  • Debug-level logging for troubleshooting
  • Graceful degradation when git is not available

API Endpoints

  • GET /api/workspace/remote/health, Remote workspace manager status.
  • POST /api/workspace/remote/clone, Clone a Git repository into the workspace.
  • POST /api/workspace/remote/status, Get status of a cloned repository.

Hardening & IDE Clone Flow

RemoteWorkspaceManager was hardened (see report 27):

  • Clone destinations are confined to the manager's base directory, local_path/names containing .. or absolute paths are rejected.
  • url and branch are validated before reaching git: URLs must be http(s)/ssh/git/file or a local path, and any argument starting with - is rejected, preventing git option injection (e.g. --upload-pack=). Branch names are restricted to git ref characters.
  • All git subprocess calls run with timeouts.
  • RemoteRepository.provider defaults to "generic".

POST /api/workspace/remote/clone accepts {url, branch?, local_path?, name?, open?}; the blocking clone runs via run_in_threadpool. With open: true a successful clone is registered as a multi-workspace root and switched active, the React IDE toolbar exposes a "clone" form that uses this flow (Repository URL + optional branch/directory + "Clone & open").

Tests: tests/test_ide_remote.py (8 tests, offline, uses local git repos as clone sources).

Record 26 / 48 // Part IV · Workspace

Code Visualization

Graph visualization · source wiki/workspace-visualization.md

Graph visualization and diagram generation for code structure visualization with DOT format support.

Overview

The CodeVisualizer provides comprehensive code visualization capabilities including:

  • Graph visualization (call, inheritance, knowledge graphs)
  • DOT diagram generation for Graphviz
  • Dependency tree generation
  • Configurable diagram styles and layouts

Components

from novacoder.workspace.visualization import CodeVisualizer, GraphVisualization, DiagramConfig

visualizer = CodeVisualizer("/path/to/workspace")
graph = visualizer.visualize_graph("call")

Usage

Visualize Graph

Generates a graph visualization with nodes and edges:

graph = visualizer.visualize_graph("call")
print(f"Graph type: {graph.graph_type}")
print(f"Nodes: {len(graph.nodes)}")
print(f"Edges: {len(graph.edges)}")
print(f"Layout: {graph.layout}")

Generate Diagram

Generates a DOT format diagram for Graphviz:

config = DiagramConfig(
    diagram_type="dependency",
    include_labels=True,
    include_edges=True,
    style="dot"
)
diagram = visualizer.generate_diagram(config)
print(diagram)

Generate Dependency Tree

Generates a text-based dependency tree for a file:

tree = visualizer.generate_dependency_tree("my_module.py")
print(tree)

Data Structures

GraphVisualization

Represents a graph visualization:

  • graph_type: Type of graph (call, inheritance, knowledge)
  • nodes: List of node dictionaries
  • edges: List of edge dictionaries
  • layout: Graph layout algorithm (dot, neato, etc.)

DiagramConfig

Configuration for diagram generation:

  • diagram_type: Type of diagram to generate
  • include_labels: Whether to include node labels
  • include_edges: Whether to include edges
  • style: Diagram style

Integration

WorkspaceService

from novacoder.workspace.service import WorkspaceService

service = WorkspaceService()
service.initialize()
visualizer = service.code_visualizer

Web API

GET /api/workspace/visualize?graph_type=call

CLI

novacoder code visualize call

Features

  • Multiple Graph Types: Supports call, inheritance, and knowledge graphs
  • DOT Format: Generates Graphviz-compatible DOT output
  • Dependency Trees: Text-based dependency visualization
  • Configurable Layouts: Supports different graph layout algorithms
  • Error Handling: Gracefully handles non-existent files

Graph Types

  • call: Function call graph
  • inheritance: Class inheritance hierarchy
  • knowledge: Knowledge graph relationships

Example Output

graph = visualizer.visualize_graph("call")
# Returns:
# GraphVisualization(
#     graph_type="call",
#     nodes=[{"id": "func1", "label": "func1"}],
#     edges=[{"source": "func1", "target": "func2"}],
#     layout="dot"
# )

Record 27 / 48 // Part IV · Workspace

Workspace Security

Workspace-level boundaries · source wiki/workspace-security.md

The workspace security system provides static application security testing (SAST) capabilities including secret detection, vulnerability scanning, and security vulnerability reporting.

Overview

The CodeSecurityAnalyzer enables comprehensive security analysis of the workspace codebase with support for:

  • Static application security testing (SAST)
  • Secret detection (API keys, passwords)
  • Security vulnerability reporting
  • Severity classification (Critical, High, Medium, Low)

Components

CodeSecurityAnalyzer

The main security analyzer that performs security scans across the workspace:

from novacoder.workspace import CodeSecurityAnalyzer

analyzer = CodeSecurityAnalyzer("/path/to/workspace")
vulnerabilities = analyzer.analyze()

SecurityVulnerability

Represents a single security vulnerability:

@dataclass
class SecurityVulnerability:
    vulnerability_type: str
    severity: SecuritySeverity
    file_path: str
    line_number: int
    description: str

SecuritySeverity

Enumeration of severity levels:

class SecuritySeverity(str, Enum):
    CRITICAL = "critical"
    HIGH = "high"
    MEDIUM = "medium"
    LOW = "low"

Usage Examples

Basic Security Analysis

from novacoder.workspace import CodeSecurityAnalyzer

analyzer = CodeSecurityAnalyzer("/path/to/project")
vulnerabilities = analyzer.analyze()

for vuln in vulnerabilities:
    print(f"{vuln.severity}: {vuln.vulnerability_type}")
    print(f"  File: {vuln.file_path}:{vuln.line_number}")
    print(f"  Description: {vuln.description}")

Filter by Severity

vulnerabilities = analyzer.analyze()
critical_vulns = [v for v in vulnerabilities if v.severity == SecuritySeverity.CRITICAL]

for vuln in critical_vulns:
    print(f"CRITICAL: {vuln.file_path}:{vuln.line_number}")

Secret Detection

The analyzer includes built-in patterns for detecting common secrets:

  • API keys
  • Passwords
vulnerabilities = analyzer.analyze()
secret_vulns = [v for v in vulnerabilities if v.vulnerability_type.startswith("hardcoded_")]

Integration with WorkspaceService

The security analyzer is integrated into the WorkspaceService and accessible as a property:

from novacoder.workspace.service import WorkspaceService

service = WorkspaceService()
service.initialize()

# Access the security analyzer
analyzer = service.security_analyzer
vulnerabilities = analyzer.analyze()

Security Checks

Secret Detection Patterns

The analyzer uses regex patterns to detect secrets assigned in code:

  • API keys: api_key/apikey/api-key assigned a 20+ character string literal (critical)
  • Passwords: password assigned an 8+ character string literal (high)

Vulnerability Types Detected

The analyzer ships five built-in patterns:

  • hardcoded_password — password assigned a string literal (high)
  • hardcoded_api_key — API key assigned a long string literal (critical)
  • sql_injection_risk — execute() calls using % formatting or + concatenation (high)
  • eval_usage — use of eval() (high)
  • shell_command — os.system/subprocess.call/subprocess.run with %-formatted strings (high)

Severity Classification

  • Critical: Immediate security risk requiring immediate action
  • High: Significant security risk that should be addressed soon
  • Medium: Moderate security risk that should be addressed
  • Low: Minor security issue that should be addressed when possible

Best Practices

  1. Run security analysis regularly as part of CI/CD pipeline
  2. Address critical vulnerabilities immediately
  3. Review high and medium severity vulnerabilities promptly
  4. Use environment variables for secrets instead of hardcoding
  5. Implement secret scanning in pre-commit hooks

Security Report Generation

from novacoder.workspace import CodeSecurityAnalyzer

analyzer = CodeSecurityAnalyzer("/path/to/project")
vulnerabilities = analyzer.analyze()

# Generate summary
critical_count = sum(1 for v in vulnerabilities if v.severity == SecuritySeverity.CRITICAL)
high_count = sum(1 for v in vulnerabilities if v.severity == SecuritySeverity.HIGH)

print(f"Security Analysis Report")
print(f"Critical: {critical_count}")
print(f"High: {high_count}")
print(f"Total: {len(vulnerabilities)}")

Future Enhancements

  • Integration with dependency vulnerability databases
  • Custom security rule configuration
  • Security policy enforcement
  • Automated vulnerability remediation suggestions
  • Integration with security scanning tools (Snyk, SonarQube)

Record 28 / 48 // Part IV · Workspace

Editor System

Editor engine internals · source wiki/editor-system.md

Overview

The Editor System provides a comprehensive file editing interface for the Nova Coder web application. It allows users to browse files, read file contents, save file changes, and apply text-based edits. The system integrates with the workspace service to provide seamless file management capabilities.

Features

File Browsing

  • Directory Navigation - Navigate through workspace directory structures
  • File Listing - List files and directories with metadata
  • Path Traversal - Support for relative and absolute paths
  • File Metadata - Display file size, type, and modification information

File Operations

  • Read File - Retrieve file contents for viewing and editing
  • Save File - Save file contents with automatic directory creation
  • Apply Edit - Apply text replacement edits to files
  • File Validation - Validate file paths and permissions

Code Search & Analysis

  • Code Search - Search for code patterns across files in the workspace
  • Symbol Extraction - Extract code symbols (functions, classes, variables) from files
  • Code Formatting - Format code according to language-specific rules
  • Collaboration - Handle real-time collaboration events for multi-user editing

API Endpoints

GET /api/editor/files

  • Summary: List Files
  • Description: Lists files in the workspace with optional path parameter
  • Query Parameters:
    • path (optional) - Directory path to list
  • Response:
    {
      "files": [
        {
          "name": "example.py",
          "path": "src/example.py",
          "type": "file",
          "size": 1024
        },
        {
          "name": "tests",
          "path": "src/tests",
          "type": "directory",
          "size": 0
        }
      ],
      "total": 2,
      "current_path": "src"
    }
    

GET /api/editor/file

  • Summary: Get File Content
  • Description: Returns the content of a file
  • Query Parameters:
    • path (required) - File path
  • Response:
    {
      "path": "src/example.py",
      "content": "print('hello world')",
      "size": 20
    }
    

POST /api/editor/file

  • Summary: Save File Content
  • Description: Saves content to a file (creates parent directories as needed)
  • Request Body:
    {
      "path": "src/example.py",
      "content": "print('hello world')"
    }
    
  • Response:
    {
      "success": true,
      "path": "src/example.py",
      "size": 20
    }
    

POST /api/editor/apply-edit

  • Summary: Apply Edit
  • Description: Applies a text replacement edit to a file
  • Request Body:
    {
      "path": "src/example.py",
      "old_text": "print('hello')",
      "new_text": "print('hello world')"
    }
    
  • Response:
    {
      "success": true,
      "path": "src/example.py",
      "changes": 1
    }
    
  • Summary: Search Code
  • Description: Search for code across files in the workspace
  • Query Parameters:
    • query (required) - Search query string
    • regex (optional) - Enable regex search (default: false)
    • file_pattern (optional) - File pattern to search (default: "*")
  • Response:
    {
      "results": [
        {
          "file": "src/example.py",
          "line": 10,
          "content": "print('hello world')",
          "match": "hello"
        }
      ],
      "total": 1
    }
    

GET /api/editor/symbols

  • Summary: Get File Symbols
  • Description: Extract code symbols from a file
  • Query Parameters:
    • path (required) - File path
  • Response:
    {
      "path": "src/example.py",
      "symbols": [
        {
          "name": "main",
          "type": "function",
          "line": 1,
          "column": 0
        },
        {
          "name": "MyClass",
          "type": "class",
          "line": 10,
          "column": 0
        }
      ],
      "total": 2
    }
    

POST /api/editor/format

  • Summary: Format Code
  • Description: Format code in a file according to language-specific rules
  • Request Body:
    {
      "path": "src/example.py"
    }
    
  • Response:
    {
      "path": "src/example.py",
      "formatted": true,
      "changes": 5
    }
    

POST /api/editor/collaborate

  • Summary: Collaborate on File
  • Description: Handle real-time collaboration events for multi-user editing
  • Request Body:
    {
      "event_type": "cursor_update",
      "path": "src/example.py",
      "data": {
        "line": 10,
        "column": 5
      },
      "timestamp": "2024-01-15T10:30:00Z"
    }
    
  • Response:
    {
      "event_type": "cursor_update",
      "path": "src/example.py",
      "broadcast": true
    }
    

API Usage

Listing Files

// List files in root directory
const files = await api('/api/editor/files');
console.log('Files:', files.files);

// List files in specific directory
const srcFiles = await api('/api/editor/files?path=src');
console.log('Source files:', srcFiles.files);

Reading File Content

// Read file content
const file = await api('/api/editor/file?path=src/example.py');
console.log('Content:', file.content);
console.log('Size:', file.size);

Saving File Content

// Save file content
await api('/api/editor/file', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    path: 'src/new_file.py',
    content: 'print("new file")'
  })
});

Applying Edits

// Apply text replacement edit
await api('/api/editor/apply-edit', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    path: 'src/example.py',
    old_text: 'print("hello")',
    new_text: 'print("hello world")'
  })
});

Searching Code

// Search for code pattern
const results = await api('/api/editor/search?query=hello&file_pattern=*.py');
console.log('Search results:', results.results);

// Search with regex
const regexResults = await api('/api/editor/search?query=def.*test&regex=true');
console.log('Regex results:', regexResults.results);

Getting File Symbols

// Get symbols from a file
const symbols = await api('/api/editor/symbols?path=src/example.py');
console.log('Symbols:', symbols.symbols);

Formatting Code

// Format code in a file
await api('/api/editor/format', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    path: 'src/example.py'
  })
});

Collaboration Events

// Send cursor update
await api('/api/editor/collaborate', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    event_type: 'cursor_update',
    path: 'src/example.py',
    data: { line: 10, column: 5 },
    timestamp: new Date().toISOString()
  })
});

// Send edit event
await api('/api/editor/collaborate', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    event_type: 'edit',
    path: 'src/example.py',
    data: { changes: [...] },
    timestamp: new Date().toISOString()
  })
});

Web UI Integration

Location: novacoder/web/react/src/pages/Editor.tsx - renderEditor() function

Web UI Features

  • File Browser: Tree view of workspace files and directories
  • Code Editor: Syntax-highlighted code editor with line numbers
  • File Operations: Create, read, save, and edit files
  • Code Search: Search across files with regex support
  • Symbol Navigation: Extract and navigate code symbols
  • Code Formatting: Auto-format code according to language rules
  • Real-time Collaboration: Multi-user editing with cursor sync
  • Auto-save: Optional automatic file saving
  • Language Detection: Automatic language detection based on file extension

Web UI API Integration

  • GET /api/editor/files - List files in directory
  • GET /api/editor/file - Get file content
  • POST /api/editor/file - Save file content
  • POST /api/editor/upload - Upload file (multipart/form-data)
  • POST /api/editor/apply-edit - Apply text replacement edits
  • GET /api/editor/search - Search code across files
  • GET /api/editor/symbols - Extract code symbols from file
  • POST /api/editor/format - Format code in file
  • POST /api/editor/collaborate - Handle collaboration events

Web UI Usage

// The renderEditor() function is called when navigating to the Editor page
async function renderEditor(){
  // Render UI structure with file browser and code editor
  $('content').innerHTML = `...`;

  // Load initial file list
  const files = await api('/api/editor/files');
  renderFileTree(files.files);

  // Load file content when selected
  async function loadFile(path){
    const file = await api(`/api/editor/file?path=${path}`);
    editor.setValue(file.content);
  }

  // Save file content
  async function saveFile(path, content){
    await api('/api/editor/file', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ path, content })
    });
  }

  // Apply edit
  async function applyEdit(path, oldText, newText){
    await api('/api/editor/apply-edit', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ path, old_text: oldText, new_text: newText })
    });
  }
}

TUI Integration

The Editor system is integrated into the Terminal User Interface (TUI) through the Files and Editor pages.

TUI Features

  • File Browser: Navigate and select files
  • File Viewer: View file contents with syntax highlighting
  • File Editor: Edit file contents directly in TUI
  • File Operations: Create, delete, rename, and move files

TUI Usage

Access the editor in the TUI:

  • Navigate to the Files page to browse
  • Select a file to view its contents
  • Press 'E' to edit the file
  • Save changes with Ctrl+S
  • Navigate directories with arrow keys

Service Integration

The Editor system integrates with the following services:

  • WorkspaceService - Provides workspace path and file operations
  • File System - Direct file system access for file operations

Service Resolution

from novacoder.workspace.service import WorkspaceService

workspace_service = _nova_app.container.resolve(WorkspaceService)

Configuration

Default Configuration

The Editor system uses the default workspace configuration. No specific configuration is required for the editor endpoints.

Customization

To customize editor behavior, modify the endpoint implementations in novacoder/api/routes_editor_system.py:

  • Add file validation rules
  • Implement file type restrictions
  • Add file size limits
  • Customize error messages

Error Handling

Application Not Running

If the application is not running, the endpoints return:

{
  "error": "Application not running"
}

Status code: 503

Invalid Path

If the path is invalid or does not exist, the endpoints return:

{
  "error": "Invalid path"
}

Status code: 400

File Not Found

If the file does not exist, the endpoints return:

{
  "error": "File not found"
}

Status code: 404

Missing Parameters

If required parameters are missing, the endpoints return:

{
  "error": "Path is required"
}

Status code: 400

Edit Not Found

If the old text is not found in the file, the endpoints return:

{
  "error": "Old text not found in file"
}

Status code: 400

Service Errors

If a service encounters an error, the endpoints return:

{
  "error": "Error message"
}

Status code: 500

Security

  • Authentication: Editor endpoints require authentication
  • Authorization: Only authorized users can access file operations
  • Path Traversal: File paths are validated to prevent path traversal attacks
  • File Access: File access is restricted to workspace directory
  • Edit Validation: Old text is validated before applying edits
  • Directory Creation: Parent directory creation is restricted to workspace

Performance Considerations

  • Large Files: Reading large files may be slow
  • File Count: Listing directories with many files may be slow
  • Edit Operations: Text replacement operations scan entire file
  • Caching: Consider caching file contents for better performance
  • Batch Operations: Consider batch operations for multiple file edits

Limitations

  • Binary Files: Binary file editing is not supported
  • Large Files: File size limits may apply
  • Concurrent Edits: No support for concurrent editing
  • File Locking: No file locking mechanism
  • Undo/Redo: No undo/redo functionality
  • Diff View: No diff view for changes

Future Enhancements

  • Add binary file support
  • Implement file locking mechanism
  • Add undo/redo functionality
  • Implement diff view for changes
  • Support for concurrent editing
  • Add file versioning integration
  • Implement file search and replace
  • Add file compression support
  • Implement file upload/download
  • Support for multiple file editing
  • Add file sharing capabilities
  • Implement file collaboration features
  • Web Interface
  • Web Interface File Browser
  • Web Interface Code Editor
  • REST API
  • Workspace System
  • File Browser

Record 29 / 48 // Part IV · Workspace

Indexing

Incremental scanner and cache · source wiki/indexing.md

The novacoder/indexing/ package is the incremental indexing pipeline for Nova Coder. It is consumed by WorkspaceService to build project understanding.

Status: IMPLEMENTED ✅

The indexing pipeline supports:

  • File scanning with hash-based change detection
  • Language detection from file extensions
  • Symbol extraction for Python, JavaScript, and TypeScript
  • Generic symbol extraction via regex for unsupported languages (imports, classes, functions)
  • Tree-sitter extraction (optional), accurate multi-language parsing with incremental re-parsing when the treesitter extra is installed (pip install "novacoder[treesitter]"). SymbolExtractor prefers TreeSitterExtractor per language and falls back to the built-in extractors when a grammar is unavailable or parsing fails.
  • Incremental scanning, only changed and deleted files are reprocessed
  • Symbol index for fast lookup
  • Import extraction for dependency graph building

Package Layout

novacoder/indexing/
├── __init__.py       # Public re-exports
├── languages.py      # LanguageDetector
├── scanner.py        # ProjectScanner, FileEntry
├── symbols.py        # Symbol, SymbolExtractor, SymbolIndex
└── extractors/
    ├── __init__.py   # EXTRACTORS registry
    ├── base.py       # LanguageExtractor ABC
    ├── generic.py
    ├── javascript.py
    ├── python.py
    └── typescript.py

ProjectScanner

ProjectScanner discovers files and returns only changed files on incremental scans.

from novacoder.indexing import ProjectScanner

scanner = ProjectScanner("/path/to/project")
files = scanner.scan()

# Incremental re-scan
changed = scanner.scan(incremental=True)
deleted = scanner.last_deleted

Performance semantics (post-Report 34)

  • Metadata fast-path: scan() stats each file and skips read_bytes + sha256 + symbol extraction when (mtime, size) match the stored entry, in both incremental and non-incremental modes. A no-change rescan of this repo (~1800 indexed files) went from ~15–48s to ~0.5s.
  • Pruned traversal: the scanner walks with os.walk and prunes excluded directories (node_modules, .venv, .git, …) before descending, dependency trees are never entered. Path.rglob used to stat all ~30k excluded files first.
  • Single extraction: _index_file extracts symbols once; consumers reuse entry.symbols (WorkspaceService.scan, _run_scan) instead of re-extracting.
  • entry.content is transient: set only for changed/new files and released by consumers after use. Callers must not assume content persists.
  • Lazy graphs: WorkspaceService marks its four symbol graphs dirty on changes and rebuilds them on first property access, not per scan.
  • Change key caveat: mtime+size is the fast-path key; a same-size same-mtime edit is the accepted edge case (hash check catches mtime-only touches cheaply).

See backups/reports_archive_2026-10-13/ai-chat-performance/34_large_project_performance.md for measurements and scripts/bench_indexing.py for the benchmark harness.

Symbol Extraction

SymbolExtractor dispatches to a language-specific extractor.

from novacoder.indexing import SymbolExtractor, SymbolIndex

result = SymbolExtractor().extract("main.py")
print(result["classes"])
print(result["functions"])
print(result["imports"])

index = SymbolIndex()
index.add(result["symbols"])
print(index.find(kind="class"))

Language Detection

LanguageDetector maps file extensions to language identifiers.

from novacoder.indexing import LanguageDetector

print(LanguageDetector.detect("main.py"))      # python
print(LanguageDetector.detect("app.js"))       # javascript
print(LanguageDetector.detect("app.ts"))       # typescript

Integration with WorkspaceService

WorkspaceService uses ProjectScanner and SymbolExtractor from novacoder/indexing/ to maintain the project index. It publishes WorkspaceScanned, WorkspaceFileChanged, and WorkspaceSymbolsUpdated events.

The FileWatcher debounces filesystem events (default 1s quiet period, one trailing run if changes arrive during a scan) and its polling fallback prunes the scanner's literal exclude dirs. IndexingService.ingest() runs the scan + graph builds in a threadpool and bounds embedding concurrency (asyncio.Semaphore(8)); VectorMemoryStore is capacity-bounded (max_entries=50_000, FIFO) and skips re-embedding identical text.

Development Instructions

Adding a New Language

  1. Edit LanguageDetector.EXTENSIONS in novacoder/indexing/languages.py.
  2. Add a new extractor in novacoder/indexing/extractors/ if needed.
  3. Register the extractor in novacoder/indexing/extractors/__init__.py.

Adding a New Extractor

  1. Create a class extending LanguageExtractor.
  2. Implement extract(path, content) -> dict[str, Any] returning imports, classes, functions, symbols.
  3. Register it in EXTRACTORS under the language identifier.
  4. Add tests in tests/test_indexing.py.

Record 30 / 48 // Part IV · Workspace

IDE Debugger (DAP)

DAP debugging · source wiki/ide-debugger.md

Overview

The IDE ships a real Debug Adapter Protocol client so the Monaco editor can debug workspace programs, the same protocol used by VS Code. The built-in adapter is debugpy (python -m debugpy.adapter), giving breakpoint debugging, stepping, stack inspection, and expression evaluation for Python files. Sessions run as local subprocesses managed by the backend; the UI talks to them over REST plus the /ws/debug event channel.

Architecture

Monaco IDE (React)
  │  gutter clicks → POST /api/ide/debug/breakpoints
  │  Run & Debug panel → REST control + /ws/debug events
  ▼
novacoder/api/routes_debug.py        REST surface (/api/ide/debug/*)
novacoder/api/routes_websocket.py    /ws/debug channel (Debug* bus events)
novacoder/dap/session.py             DebugSession, adapter process lifecycle,
                                     breakpoint queue/flush, state machine
novacoder/dap/client.py              DapClient, async Content-Length framing,
                                     seq tracking, events, reverse requests
        │
        ▼
python -m debugpy.adapter  ──launches──▶  debuggee process
  • DapClient implements the wire protocol: 8-byte Content-Length framed JSON messages, monotonically increasing seq for requests and responses (per the DAP spec), adapter event dispatch, and safe handling of adapter reverse requests (e.g. runInTerminal, handshake). All I/O is asyncio, nothing blocks the API event loop.
  • DebugSession owns one adapter subprocess. Breakpoints set before launch are queued, sent during configurationDone, and flushed through an internal path so the "not live" gate can't swallow them. Breakpoints persist across sessions (standard IDE semantics) until the user removes them.
  • Terminated sessions stay inspectable, state, exit_code, and captured output remain available until the next start or stop.

REST API

All routes require the normal API token / session auth and are under the workspace RBAC resource.

Method Route Purpose
GET /api/ide/debug/status Session state, threads, breakpoints, capabilities, debugpy availability
POST /api/ide/debug/start Launch debug session. Body: {path, args?, cwd?}, path is workspace-relative
POST /api/ide/debug/stop Terminate the session and adapter
POST /api/ide/debug/breakpoints Replace a file's breakpoints. Body: {path, lines:[int]}
POST /api/ide/debug/continue Continue. Body: {thread_id?}
POST /api/ide/debug/pause Pause. Body: {thread_id?}
POST /api/ide/debug/next Step over
POST /api/ide/debug/step_in Step into
POST /api/ide/debug/step_out Step out
GET /api/ide/debug/threads List debuggee threads
GET /api/ide/debug/stack Stack trace. Query: thread_id? (defaults to stopped/first thread), levels
GET /api/ide/debug/scopes Scopes for a frame. Query: frame_id (required)
GET /api/ide/debug/variables Variables. Query: variables_reference (required)
POST /api/ide/debug/evaluate Evaluate expression. Body: {expression, frame_id?}
GET /api/ide/debug/output Captured stdout/stderr/console/telemetry. Query: limit

Status state values: idle, starting, running, stopped, terminated, error. The stopped payload carries {thread_id, reason, description, all_threads_stopped}.

WebSocket events, GET /ws/debug

Session operations emit kernel Debug* events bridged to the debug channel (see _EVENT_CHANNEL_MAP in novacoder/api/websocket.py):

Event Payload
DebugSessionStarted {program}
DebugSessionStopped {program} (session/adapter teardown)
DebugStopped stop details, thread_id, reason, location
DebugContinued {thread_id}
DebugBreakpoints updated breakpoint map for a source
DebugBreakpointChanged adapter-verified change for one breakpoint
DebugOutput {category, output} chunk from the debuggee
DebugProcess adapter process metadata (name, pid, …)
DebugExited {exit_code}
DebugTerminated {program, reason?}

The IDE panel subscribes via useEventStream('debug') and invalidates its status/stack/variable queries on any Debug* event, so stops and output appear immediately. Polling remains as a fallback.

UI, Run and Debug panel

Sidebar view 🐞 in the IDE:

  • Controls, ▶ Debug (enabled for *.py active files), ⏸ pause, step over / into / out, ■ stop. State chip shows the live session state.
  • Breakpoints, click the editor glyph margin or line numbers to toggle; verified breakpoints are solid red, pending ones translucent. The panel lists all breakpoints with verified state and removal buttons.
  • Call stack, frames for the stopped thread; clicking a frame opens the file and selects it for variables/evaluate.
  • Variables, scopes (Locals/Globals) with lazily-expandable child variables.
  • Evaluate, arbitrary expression evaluated in the selected frame.
  • Output, debuggee stdout/stderr tail.
  • The current stop location is highlighted in the editor (yellow line + gutter wedge) and the file auto-opens when the debugger stops.
  • Status bar shows debug:<state>.

Dependencies

  • debugpy, required for Python debugging. GET status reports debugpy: false and disables launch when it is absent (pip install debugpy).
  • Adapter capabilities are surfaced verbatim in the status response (conditional breakpoints, setVariable, evaluateForHovers, etc.).

Limitations

  • Single concurrent session (one debuggee at a time), matching the panel UX.
  • Only the debugpy launch config is exposed (program, args, cwd, console=internalConsole). Attach/remote debugging and other language adapters can be added by extending DebugSession's launch request.
  • runInTerminal reverse requests are answered with an error response, debuggee output always goes through the output event channel, not the PTY terminal.

Testing

tests/test_ide_debug_api.py, 26 tests covering status, breakpoint queueing/persistence, launch, stop, and a real debugpy session: breakpoint hit → stack → scopes → variables → evaluate → step → continue → terminate. Offline-safe; real-adapter cases skip when debugpy is unavailable.

  • Editor System, underlying file/editor API
  • Web Interface Code Editor, legacy editor UI
  • VS Code Extension, external editor bridge
  • Report: backups/reports_archive_2026-10-13/26_ide_debugger.md (archived; consolidated into reports/NOVACODER_MASTER_DEVELOPMENT_ROADMAP.md)

Record 31 / 48 // Part IV · Workspace

Memory

Memory service and store · source wiki/memory.md

Nova Coder separates memory into distinct layers to improve context handling and retrieval. Each layer has a different lifetime and scope.

Memory Layers

┌────────────────────────────────────────┐
│           Session Memory               │
│  Current conversation, open files      │
├────────────────────────────────────────┤
│           Working Memory               │
│  Current task, intermediate results    │
├────────────────────────────────────────┤
│           Project Memory               │
│  Architecture, symbol index, decisions │
├────────────────────────────────────────┤
│          Persistent Memory             │
│  User preferences, settings, plugins   │
└────────────────────────────────────────┘

MemoryStore

MemoryStore is a thread-safe SQLite-backed key-value store with enhanced concurrency and security features. All SQL operations are protected by a threading.Lock, and the database uses Write-Ahead Logging (WAL) mode for better performance and concurrency.

from novacoder.memory import MemoryStore, MemoryScope

store = MemoryStore('~/.config/novacoder/memory.db')
store.initialize()

store.set('project.summary', 'Flask API', scope=MemoryScope.PROJECT)
entry = store.get('project.summary', scope=MemoryScope.PROJECT)
print(entry.value)  # Flask API
print(entry.created_at)

Thread Safety Enhancements

The MemoryStore implements several thread safety improvements:

  • WAL Mode: Write-Ahead Logging enabled for better concurrency
  • Busy Timeout: Configured 5-second timeout for concurrent access
  • Synchronous Mode: Set to NORMAL for performance balance
  • Comprehensive Logging: All database operations logged for debugging and security
  • Thread Lock: All operations protected by threading.Lock

Database Configuration

The SQLite connection is configured with the following PRAGMA settings for optimal performance and safety:

PRAGMA journal_mode=WAL        # Write-Ahead Logging for better concurrency
PRAGMA synchronous=NORMAL       # Balance between safety and performance
PRAGMA busy_timeout=5000        # 5-second timeout for concurrent access

Logging

All memory operations are logged with appropriate context:

  • Set operations: Logged with key, scope, and value length
  • Get operations: Logged with key, scope, and found status
  • Delete operations: Logged with key and scope
  • Purge operations: Logged with count of expired entries removed

This logging aids in debugging, security auditing, and performance monitoring.

Memory Scopes

Scope Use Case Default TTL
session Current conversation 24 hours
working Current task scratchpad 2 hours
project Project architecture and index never
persistent User preferences and settings never
agent Agent-specific state 48 hours

MemoryService

MemoryService is the kernel service that manages the memory store. It exposes a service-level API and delegates to MemoryStore:

from novacoder.memory import MemoryService
from novacoder.config.settings import AppConfig

service = MemoryService(config=AppConfig())
service.initialize()

service.remember('key', 'value', scope=MemoryScope.SESSION)
print(service.recall('key'))
print(service.recall_all(scope=MemoryScope.SESSION))
service.forget('key')

Service API

  • remember(key, value, scope=SESSION, ttl_seconds=None), store a value
  • recall(key, scope=SESSION), return a value or None
  • forget(key, scope=SESSION), delete a single entry
  • clear(scope=SESSION), delete all entries in a scope
  • recall_all(scope=SESSION), return {key: value} for non-expired entries
  • recall_all_entries(scope=SESSION), return {key: MemoryEntry}
  • purge_expired(), delete expired entries and return the count

CLI

Clear every entry in a scope:

novacoder memory clear --scope session

TUI

The Memory page lists entries for the selected scope. A Delete Entry button removes the currently selected row by calling MemoryService.forget(). A Clear Scope button calls MemoryService.clear() for the selected scope.

TUI Backup Integration

The TUI Memory page includes backup and restore functionality:

  • Backup Button: Creates a backup for the currently selected scope
  • List Backups Button: Displays all available backups in a table
  • Restore Button: Restores the selected backup to the current scope
  • Backup DataTable: Shows backup ID, time, size, entries, and type

The backup system is integrated through MemoryService.backup with automatic handler registration for all memory scopes. See Memory Backup and Recovery for detailed information.

SessionContext

SessionContext wraps MemoryService to give each agent run a private session namespace. All keys are prefixed with the session id.

from novacoder.memory import SessionContext

ctx = SessionContext('session-1', service)
ctx.store('user', 'alice')
print(ctx.retrieve('user'))  # alice
ctx.close()

AgentManager creates a new SessionContext for every run() call and sets it on the agent via agent.set_session_context(). Agents can access it through self.session_context. See Session Context for more details.

Configuration

memory:
  database: sqlite
  db_path: ~/.config/novacoder/memory.db

Database Schema

The SQLite store uses a single table with created_at and expires_at columns:

CREATE TABLE memory (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    scope TEXT NOT NULL,
    key TEXT NOT NULL,
    value TEXT NOT NULL,
    timestamp TEXT NOT NULL,
    metadata TEXT,
    created_at REAL,
    expires_at REAL
);

TTL and Expiry

set() and remember() accept an optional ttl_seconds argument. When omitted, the default TTL for the scope is used. get() and get_all() filter out expired entries. Expired rows are removed by purge_expired().

MemoryService.start() schedules a daily purge through the kernel Scheduler.

store.set('temp', 'data', scope=MemoryScope.WORKING, ttl_seconds=3600)

Closing the Store

close() terminates the connection and marks the store as closed. Subsequent calls to get() or set() raise RuntimeError.

store.clear()

Development Instructions

Adding a New Memory Scope

  1. Add a new value to MemoryScope in novacoder/memory/memory.py.
  2. Update DEFAULT_SCOPE_TTL if needed.
  3. Add tests verifying scope isolation and TTL.
  4. Update this wiki page and the glossary.

Adding a New Memory Backend

  1. Define a backend interface (e.g., MemoryBackend) in novacoder/memory/backends/.
  2. Refactor MemoryStore to delegate to the backend.
  3. Implement the SQLite backend as the default.
  4. Add a backend factory selected by MemoryConfig.database.

Testing Memory

def test_memory_store(tmp_path):
    from novacoder.memory import MemoryStore, MemoryScope
    store = MemoryStore(tmp_path / 'memory.db')
    store.initialize()
    store.set('key', 'value', scope=MemoryScope.PROJECT)
    entry = store.get('key', scope=MemoryScope.PROJECT)
    assert entry.value == 'value'
    store.clear()

Vector Memory

Nova Coder includes a lightweight in-memory vector store for semantic retrieval. It is enabled by setting memory.vector_db to memory:

memory:
  vector_db: memory

The VectorMemoryStore lives in novacoder.embeddings and uses an AIProvider that supports embed:

from novacoder.embeddings import VectorMemoryStore
from novacoder.ai.provider import AIProvider

store = VectorMemoryStore()
await store.embed_and_store('greeting', 'hello world', provider)
keys = await store.search('hi', provider, top_k=3)

MemoryService exposes vector memory when configured:

await memory_service.vector_embed_and_store('greeting', 'hello world', provider)
keys = await memory_service.vector_search('hi', provider)

MemoryService uses ModelRouter.select("embeddings") to choose an embedding-capable provider. OllamaProvider calls /api/embed and OpenAIProvider calls /embeddings when an API key is configured. With the memory vector backend, embeddings are persisted alongside the memory store.

Advanced Memory Systems

Nova Coder's memory system has been significantly enhanced with 15 new production-grade systems for security, reliability, and scalability:

High Priority Systems

  • Vector Databases - Production vector database support (Pinecone, Weaviate, ChromaDB, Qdrant, Milvus)
  • Memory Encryption - AES-256 encryption with key management and rotation
  • Backup and Recovery - Automated backup with point-in-time recovery and verification
  • Access Control - Role-based access control (RBAC) with key-level permissions
  • Memory Validation - Schema-based validation with custom business rules

Medium Priority Systems

  • Memory Compression - zlib and lz4 compression with statistics
  • Memory Analytics - Access pattern analysis, hot key detection, and monitoring
  • Memory Indexing - Full-text search, metadata indexing, and composite indexes
  • Memory Replication - Master-slave replication with health monitoring
  • Memory Query Capabilities - Pattern search, metadata queries, and time-range queries
  • Memory Transactions - Atomic multi-key operations with savepoints and isolation levels
  • Memory Caching - In-memory caching with LRU, LFU, FIFO, and TTL eviction policies

Low Priority Systems

  • Memory Export/Import - JSON, CSV, and SQLite format support
  • Memory Versioning - Change tracking, rollback, and version comparison
  • Memory Sharding - Horizontal sharding with consistent hashing
  • Distributed Memory - Distributed memory storage for horizontal scaling
  • Memory Streams - Stream-based memory operations for real-time data
  • Memory Graph - Graph-based memory for relationship tracking
  • Memory Federation - Federation across multiple memory stores

Integration

All new systems are integrated into MemoryService and accessible via property accessors:

from novacoder.memory import MemoryService

service = MemoryService(config)
service.initialize()

# Access new systems
service.compression.compress(data)
service.encryption.encrypt(data)
service.backup.create_backup(["session"], BackupType.FULL)
service.access_control.check_permission("user", "key", Permission.READ, "project")
service.analytics.get_access_statistics()
service.cache.get_default_cache().get("key")

TUI Integration

The Memory page in the TUI now includes:

  • Real-time statistics cards (compression, encryption, cache, backups)
  • Analytics button to view memory analytics
  • Backup button to create memory backups
  • All operations run in background threads

Future Enhancements

  • Conversation summarization
  • Cross-project memory with user consent
  • Memory decay and importance scoring
  • Episodic memory for past mistakes
  • Configuration
  • Workspace
  • Agents
  • Memory Advanced Systems - Comprehensive overview of all advanced memory systems
  • Memory Vector Databases
  • Memory Compression
  • Memory Encryption
  • Memory Backup and Recovery
  • Memory Access Control
  • Memory Analytics
  • Memory Indexing
  • Memory Replication
  • Memory Query Capabilities
  • Memory Transactions
  • Memory Validation
  • Memory Caching
  • Memory Export/Import
  • Memory Versioning
  • Memory Sharding
  • Distributed Memory
  • Memory Federation
  • Memory Graph
  • Memory Streams

Record 32 / 48 // Part V · Security

Security

Security subsystem overview · source wiki/security.md

Nova Coder's security subsystem provides a comprehensive security platform with 24 security rules and 34 complete security subsystems covering authentication, authorization, audit logging, secret management, input validation, monitoring, encryption, permissions, rate limiting, testing, policies, incident response, compliance, permission management, dependency scanning, IaC security scanning, container security scanning, SAST/DAST integration, security dashboard, AST-based analysis, dedicated secret scanning, rule validation, data privacy controls, rule sandboxing, AI provider security, scanning cache, pattern cache, AI batch processing, zero trust architecture, ML-based threat detection, behavioral analysis, supply chain security, and ML training data generation.

Overview

The security system has evolved from a basic foundation with static security rule scanning and permission checking to a production-ready security platform. All 15 identified security gaps have been successfully implemented and integrated into the Nova Coder platform.

Security Subsystems

0. Advanced Security System

  • File: novacoder/security/advanced.py
  • Features: Runtime security monitoring, threat detection with multiple types, policy enforcement with rules, compliance reporting for GDPR, HIPAA, PCI DSS, SOC2, ISO27001, threat history tracking, event callbacks for custom handling
  • Components: AdvancedSecurity, Threat, ThreatLevel, ThreatType, SecurityPolicy, PolicyType, PolicyViolation, ComplianceReport, ComplianceStandard
  • Threat Types: ANOMALY, MALWARE, PHISHING, DDOS, INJECTION, XSS, CSRF, BRUTE_FORCE, DATA_EXFILTRATION, PRIVILEGE_ESCALATION
  • Policy Types: ACCESS_CONTROL, DATA_PROTECTION, NETWORK_SECURITY, COMPLIANCE, CUSTOM
  • Compliance Standards: GDPR, HIPAA, PCI_DSS, SOC2, ISO27001

1. Enhanced Security Rules

  • File: novacoder/security/enhanced_rules.py
  • Features: 19 enhanced security rules covering XSS, CSRF, command injection, path traversal, XXE, SSRF, dependency vulnerabilities
  • Custom Rule Language: Define custom security patterns with variable substitution
  • Total Rules: 30 (11 default + 19 enhanced)

2. Dynamic Security Analysis

  • File: novacoder/security/dynamic_analysis.py
  • Features: Runtime vulnerability detection, taint analysis, data flow tracking, runtime security monitoring
  • Components: TaintAnalyzer, DataFlowTracker, RuntimeSecurityMonitor, RuntimeVulnerabilityDetector

3. Authentication and Authorization

  • File: novacoder/security/auth.py
  • Features: User authentication with PBKDF2 password hashing, RBAC with predefined roles, session management with expiration, multi-factor authentication support, user management
  • Components: AuthenticationManager, AuthorizationManager, SessionManager, User, Role

4. Comprehensive Audit Logging

  • File: novacoder/security/audit_logging.py
  • Features: Security event tracking with multiple event types, log aggregation from multiple sources, security analytics for pattern detection, audit trail management with archival capabilities
  • Components: AuditLogger, LogAggregator, SecurityAnalytics, AuditTrailManager

5. Secret Management

  • File: novacoder/security/secret_management.py
  • Features: Secret storage with encryption, secret rotation with configurable intervals, secret encryption with master key, secret access logging for audit trail, API key generation
  • Components: SecretManager, SecretRotationScheduler, Secret, SecretType

6. Input Validation Framework

  • File: novacoder/security/input_validation.py
  • Features: Input validation with multiple rule types, output encoding for HTML/JavaScript/URLs/CSS, input sanitization for various contexts, SQL injection prevention, validation rule library
  • Components: InputValidator, OutputEncoder, Sanitizer, ValidationRule, ValidationResult

7. Security Monitoring

  • File: novacoder/security/monitoring.py
  • Features: Real-time security monitoring, security alerting with threat levels, threat detection (brute force, suspicious IPs, data exfiltration), security dashboards with metrics, security analytics and anomaly detection
  • Components: SecurityMonitor, ThreatDetector, AlertManager, SecurityDashboard, SecurityAlert

8. Encryption Capabilities

  • File: novacoder/security/encryption.py
  • Features: Data encryption at rest, data encryption in transit, key management with rotation, certificate management for SSL/TLS, encryption policies with algorithm selection
  • Components: EncryptionManager, KeyManager, CertificateManager, EncryptionPolicy

9. Enhanced Permission Granularity

  • File: novacoder/security/permissions.py
  • Features: Resource-level permissions, action-specific permissions (READ, WRITE, DELETE, EXECUTE, etc.), time-based permissions with scheduling, context-aware permissions based on conditions, permission inheritance
  • Components: EnhancedPermissionManager, ResourcePermission, TimeBasedPermission, ContextPermission, PermissionAction

10. Rate Limiting

  • File: novacoder/security/rate_limiting.py
  • Features: API rate limiting with token bucket algorithm, authentication rate limiting, operation rate limiting, adaptive rate limiting based on system load, rate limiting configuration
  • Components: RateLimiter, AdaptiveRateLimiter, RateLimitManager, RateLimitConfig

11. Security Testing Framework

  • File: novacoder/security/testing.py
  • Features: Penetration testing tools, vulnerability scanning for code and dependencies, security regression testing, extensible security test suite
  • Components: SecurityTestFramework, VulnerabilityScanner, SecurityTest, SecurityTestResult

12. Security Policy Framework

  • File: novacoder/security/policies.py
  • Features: Security policy enforcement, policy compliance checking, policy violation detection, policy management with default policies
  • Components: PolicyManager, PolicyEnforcement, Policy, PolicyViolation

13. Incident Response System

  • File: novacoder/security/incident_response.py
  • Features: Incident response workflow, automated incident handling, security incident tracking, incident reporting with statistics, response playbooks for common incident types
  • Components: IncidentManager, ResponsePlaybook, Incident, IncidentStatus

14. Security Compliance

  • File: novacoder/security/compliance.py
  • Features: Compliance frameworks (SOC2, HIPAA, GDPR, PCI-DSS, ISO-27001), compliance reporting with scoring, compliance monitoring, compliance automation and dashboards
  • Components: ComplianceManager, ComplianceReport, ComplianceFramework, ComplianceStatus

15. Enhanced Permission Management

  • File: novacoder/security/permission_management.py
  • Features: Permission management UI components, permission templates for common roles, permission auditing with change tracking, permission request workflow with approval, permission analytics with anomaly detection
  • Components: EnhancedPermissionManagementSystem, PermissionTemplateManager, PermissionRequestWorkflow, PermissionAuditor, PermissionAnalytics

16. Dependency Scanning

  • File: novacoder/security/dependency_scanning.py
  • Features: Dependency vulnerability detection for CVEs, outdated package checking, multiple scan sources (requirements.txt, pyproject.toml, pip list), policy compliance validation, comprehensive reporting and JSON export
  • Components: DependencyScanner, DependencyPolicy, DependencyInfo, ScanResult, Vulnerability, SeverityLevel

17. IaC Security Scanning

  • File: novacoder/security/iac_scanning.py
  • Features: Multi-platform IaC scanning for Terraform, Kubernetes, Docker Compose, and CloudFormation, comprehensive security checks, severity classification, remediation recommendations
  • Components: IaCScanner, IaCFinding, IaCScanResult, IaCPlatform, SeverityLevel, CheckCategory

18. Container Security Scanning

  • File: novacoder/security/container_scanning.py
  • Features: Docker image vulnerability scanning, Dockerfile security analysis, compliance scoring, secret detection, layer analysis
  • Components: ContainerScanner, ContainerVulnerability, ContainerImage, ContainerScanResult, VulnerabilityType

19. SAST/DAST Integration

  • File: novacoder/security/sast_dast.py
  • Features: Static application security testing (Bandit, SonarQube), dynamic application security testing (OWASP ZAP, Burp Suite), OWASP Top 10 categorization, compliance scoring
  • Components: SASTScanner, DASTScanner, SASTDASTManager, SecurityFinding, SecurityTestResult, TestType

20. Security Dashboard

  • File: novacoder/security/dashboard.py
  • Features: Real-time security metrics, customizable widgets (overview cards, charts, gauges, tables, alerts), trend analysis, overall compliance score calculation, JSON export/import
  • Components: SecurityDashboardManager, SecurityDashboard, DashboardWidget, SecurityMetric, SecurityTrend

21. AST-Based Security Analysis

  • File: novacoder/security/ast_analysis.py
  • Features: Context-aware security analysis using Python AST, accurate line and column information, detection of code injection, SQL injection, XSS, path traversal, insecure deserialization, weak cryptography, hardcoded credentials, insecure random, SSRF, and XXE
  • Components: ASTSecurityAnalyzer, ASTAnalysisManager, ASTFinding, ASTAnalysisResult, VulnerabilityType, SeverityLevel

22. Dedicated Secret Scanning

  • File: novacoder/security/secret_scanning.py
  • Features: Specialized secret detection for AWS keys, API keys, passwords, tokens, database URLs, JWT tokens, Slack tokens, GitHub tokens, Google API keys, Stripe keys, SendGrid keys, Twitter keys, SSH keys, and private keys, compliance checking, secret masking
  • Components: SecretScanner, SecretFinding, SecretScanResult, SecretScanPolicy, SecretPattern, SecretType

23. Rule Validation System

  • File: novacoder/security/rule_validation.py
  • Features: Comprehensive validation for security rules including syntax validation, security checking, performance analysis, and best practice enforcement. Validates rule ID format, regex pattern syntax, severity levels, and dangerous pattern detection.
  • Components: RuleValidator, RuleValidationManager, ValidationIssue, ValidationResult, ValidationSeverity, ValidationCategory

24. Data Privacy Controls

  • File: novacoder/security/data_privacy.py
  • Features: Data privacy controls with masking and redaction for emails, IP addresses, API keys, and AWS keys. Privacy policy management with multiple privacy levels (public, internal, confidential, restricted), data category classification, and compliance checking.
  • Components: DataPrivacyManager, PrivacyPolicy, DataMaskingRule, PrivacyLevel, DataCategory

25. Rule Sandbox

  • File: novacoder/security/rule_sandbox.py
  • Features: Security sandboxing for custom rules with configurable sandboxing levels (none, basic, strict). Validates custom rules for dangerous modules, functions, and AST constructs. Provides violation tracking and sandbox validation reports.
  • Components: RuleSandbox, RuleSandboxManager, SandboxViolation, SandboxResult, SandboxLevel, RuleOperation

26. AI Provider Security

  • File: novacoder/security/ai_provider_security.py
  • Features: AI provider validation and rate limiting with trusted provider checking, suspicious pattern detection, and configurable validation levels (none, basic, strict). Rate limiting with configurable limits per minute/hour/day, usage statistics, and provider blocking/suspension capabilities.
  • Components: AIProviderValidator, RateLimiter, AIProviderSecurityManager, ProviderStatus, ValidationLevel, RateLimitConfig, ProviderValidation, RateLimitInfo

27. Scanning Cache

  • File: novacoder/security/scanning_cache.py
  • Features: Incremental scanning and caching with file hash-based change detection, configurable caching strategies (none, memory, disk, hybrid), LRU cache eviction, and scan metadata tracking. Supports incremental scanning to only re-scan changed files.
  • Components: ScanningCache, IncrementalScanner, ScanningCacheManager, CacheStrategy, CacheEntry, ScanMetadata

28. Pattern Cache

  • File: novacoder/security/pattern_cache.py
  • Features: Pattern caching and optimization with compiled pattern caching with LRU eviction, pattern optimization (greedy to non-greedy, character class shorthands, redundant escaping), configurable optimization levels (none, basic, aggressive), and batch pattern compilation.
  • Components: PatternCache, PatternOptimizer, PatternCacheManager, OptimizationLevel, CompiledPattern, PatternOptimization

29. AI Batch Processing

  • File: novacoder/security/ai_batch_processor.py
  • Features: Async processing and batching with configurable batching strategies (size-based, time-based, hybrid), priority-based task queuing, concurrent scan limiting, and async directory scanning. Includes batch processing statistics and performance monitoring.
  • Components: BatchProcessor, AsyncAIScanner, AIBatchProcessingManager, BatchStrategy, ProcessingPriority, BatchTask, BatchResult

30. Zero Trust Architecture

  • File: novacoder/security/zero_trust.py
  • Features: Identity and access management with trust levels, device trust verification, mutual TLS for secure communication, continuous verification and monitoring, access request workflow, session management
  • Components: IdentityAccessManager, DeviceTrustManager, MutualTLSManager, ContinuousVerification, Identity, Device, AccessRequest, TrustLevel, DeviceStatus

31. ML Threat Detection

  • File: novacoder/security/ml_threats.py
  • Features: Machine learning-based threat detection with multiple model types (anomaly detection, behavioral analysis, pattern recognition, sequence analysis, classification), model training and prediction, threat scoring, model performance tracking
  • Components: MLThreatDetector, ThreatModel, ModelType, ModelStatus, PredictionResult, ThreatScore

32. Behavioral Analysis

  • File: novacoder/security/behavioral_analysis.py
  • Features: User behavior profiling and anomaly detection, event recording and analysis, alert generation based on behavioral patterns, risk scoring, user profile management
  • Components: BehavioralAnalyzer, UserProfile, EventRecord, Alert, RiskLevel, AlertType

33. Security Automation

  • File: novacoder/security/automation.py
  • Features: Automated security response with rule-based triggers, action execution, event processing, rule management, execution tracking, success rate monitoring
  • Components: SecurityAutomation, AutomationRule, AutomationAction, AutomationTrigger, ActionExecution, ActionType, TriggerType, ActionStatus

34. Supply Chain Security

  • File: novacoder/security/supply_chain.py
  • Features: Software Bill of Materials (SBOM) generation, dependency analysis for security issues, package verification with hash and signature checking, attack path analysis through dependency graph, vulnerability tracking
  • Components: SupplyChainSecurity, SBOM, SBOMComponent, Vulnerability, VulnerabilitySeverity, PackageStatus, AttackPath

35. Compliance Automation

  • File: novacoder/security/compliance_automation.py
  • Features: Compliance rule management for multiple standards (GDPR, HIPAA, PCI DSS, SOC2, ISO27001, NIST, CIS), automated compliance checks, report generation, remediation action management, check function registration
  • Components: ComplianceAutomation, ComplianceRule, ComplianceCheck, ComplianceReport, ComplianceStandard, ComplianceStatus, RemediationAction, RemediationStatus

Components

  • novacoder/security/service.py, SecurityService with regex-based static rules and scan_with_ai() for AI-assisted analysis
  • novacoder/security/agent.py, SecurityAgent that uses AI first and falls back to SecurityService
  • novacoder/security/enhanced_rules.py, Enhanced security rules and custom rule language
  • novacoder/security/dynamic_analysis.py, Runtime vulnerability detection and taint analysis
  • novacoder/security/auth.py, Authentication, authorization, and session management
  • novacoder/security/audit_logging.py, Comprehensive audit logging and analytics
  • novacoder/security/secret_management.py, Secret storage, rotation, and encryption
  • novacoder/security/input_validation.py, Input validation, sanitization, and output encoding
  • novacoder/security/monitoring.py, Real-time security monitoring and alerting
  • novacoder/security/encryption.py, Data encryption, key management, and certificates
  • novacoder/security/permissions.py, Enhanced permission granularity
  • novacoder/security/rate_limiting.py, Rate limiting with adaptive capabilities
  • novacoder/security/testing.py, Security testing framework and vulnerability scanning
  • novacoder/security/policies.py, Security policy framework
  • novacoder/security/incident_response.py, Incident response system
  • novacoder/security/compliance.py, Compliance frameworks (SOC2, HIPAA, GDPR)
  • novacoder/security/permission_management.py, Permission templates, auditing, and analytics
  • novacoder/security/dependency_scanning.py, Dependency vulnerability detection and supply chain security
  • novacoder/security/iac_scanning.py, Infrastructure-as-Code security misconfiguration detection
  • novacoder/security/container_scanning.py, Docker image and Dockerfile security scanning
  • novacoder/security/sast_dast.py, Static and dynamic application security testing
  • novacoder/security/dashboard.py, Security visualization and metrics dashboard
  • novacoder/security/ast_analysis.py, Context-aware security analysis using Python AST
  • novacoder/security/secret_scanning.py, Dedicated secret detection for credentials and sensitive data
  • novacoder/security/rule_validation.py, Security rule validation system for syntax, security, performance, and best practice checking
  • novacoder/security/data_privacy.py, Data privacy controls with masking, redaction, and privacy policy enforcement
  • novacoder/security/rule_sandbox.py, Security sandboxing for custom rules with configurable sandboxing levels
  • novacoder/security/ai_provider_security.py, AI provider validation and rate limiting with trusted provider checking
  • novacoder/security/scanning_cache.py, Incremental scanning and caching with file hash-based change detection
  • novacoder/security/pattern_cache.py, Pattern caching and optimization with compiled pattern caching
  • novacoder/security/ai_batch_processor.py, Async processing and batching for AI security scanning
  • novacoder/security/zero_trust.py, Zero trust architecture with identity management, device trust, and mutual TLS
  • novacoder/security/ml_threats.py, ML-based threat detection with multiple model types
  • novacoder/security/behavioral_analysis.py, User behavior profiling and anomaly detection
  • novacoder/security/automation.py, Automated security response with rule-based triggers
  • novacoder/security/supply_chain.py, Supply chain security with SBOM generation and attack path analysis
  • novacoder/security/compliance_automation.py, Compliance automation for multiple security standards
  • novacoder/security/ml_training_data.py, ML training data generation and management for threat detection models

SecurityService

SecurityService scans source code for known security issues. It is language-agnostic and operates line-by-line with a configurable rule set.

from novacoder.security.service import SecurityService

service = SecurityService()
findings = service.scan_code("import os; os.system('rm -rf /')", language="python")
report = service.aggregate(findings)
print(report["risk_level"], report["recommendations"])

Advanced Security System

The Advanced Security System provides runtime security monitoring, threat detection, policy enforcement, and compliance reporting.

from novacoder.security import AdvancedSecurity, ThreatType, ThreatLevel, PolicyType, ComplianceStandard

# Create advanced security manager
security = AdvancedSecurity()
security.start()

# Threat detection
threat = security.detect_threat(
    threat_type=ThreatType.ANOMALY,
    source='source-1',
    target='target-1',
    description='Unusual activity detected',
    level=ThreatLevel.MEDIUM
)
print(f"Threat ID: {threat.threat_id}")

# Policy management
from novacoder.security.advanced import SecurityPolicy
policy = SecurityPolicy(
    name='Access Control Policy',
    policy_type=PolicyType.ACCESS_CONTROL,
    description='Enforce access control rules'
)
security.add_policy(policy)

# Policy enforcement
context = {'user': 'test', 'action': 'read', 'resource': 'data'}
enforced = security.enforce_policy(policy.policy_id, context)
print(f"Policy enforced: {enforced}")

# Compliance reporting
report = security.generate_compliance_report(ComplianceStandard.GDPR)
print(f"Compliance score: {report.compliance_score}")

# Get security statistics
stats = security.get_security_stats()
print(f"Total threats: {stats['total_threats']}")
print(f"Total policies: {stats['total_policies']}")

security.stop()

Default Rules

Rule ID Severity Issue
DANGEROUS_EVAL high Use of eval()
DANGEROUS_EXEC high Use of exec()
OS_SYSTEM high os.system, os.popen, os.spawn, os.exec
SHELL_TRUE high subprocess.*(..., shell=True)
PICKLE_LOAD high pickle.loads() / pickle.load()
UNSAFE_YAML high yaml.load() without a safe loader
DYNAMIC_IMPORT medium __import__ / importlib.import_module
HARDCODED_SECRET medium Possible hardcoded password / secret / token
SQL_FORMAT medium SQL string formatting (%s, f"...", .format)
INSECURE_TEMP medium tempfile.mktemp()
DEBUG_TRUE low app.run(..., debug=True)

Enhanced Rules

Rule ID Severity Issue
XSS_REFLECTED high Reflected XSS vulnerabilities
XSS_DOM high DOM-based XSS vulnerabilities
CSRF_MISSING_TOKEN high Disabled CSRF protection
CSRF_STATE_CHANGE high State-changing operations without CSRF
COMMAND_INJECTION high Command injection patterns
COMMAND_INJECTION_PIPE high Command chaining
PATH_TRAVERSAL high Path traversal patterns
PATH_TRAVERSAL_USER_INPUT high User-controlled file paths
XXE_VULNERABILITY high XML External Entity vulnerabilities
SSRF_URL_USER_INPUT high SSRF via user input
SSRF_INTERNAL_IP high Internal IP addresses in URLs
OUTDATED_DEPENDENCY medium Potentially outdated dependencies
INSECURE_PROTOCOL medium Insecure HTTP usage
HARDCODED_API_KEY medium Hardcoded API keys
WEAK_CRYPTO medium Weak cryptographic algorithms
RANDOM_NOT_SECURE medium Non-cryptographically secure random
SSL_VERIFICATION_DISABLED medium Disabled SSL verification
INSECURE_COOKIE medium Insecure cookie configuration
INFORMATION_DISCLOSURE low Potential information disclosure

SecurityAgent

SecurityAgent is a built-in agent that scans files from the workspace or from task.context["files"].

Enabling

agents:
  security: true

Or via environment variable:

NOVACODER_AGENTS__SECURITY=true

Usage

from novacoder.agents.agent import AgentTask
from novacoder.agents.service import AgentService

service = AgentService(config)
service.initialize()

task = AgentTask(
    id="scan-1",
    description="Scan for security issues",
    goal="Review project files",
    context={"files": ["app.py"]},
)
result = service.manager.run("security", task)
print(result.output)

AI vs Static Analysis

The agent first delegates to SecurityService.scan_with_ai(), which augments static rule findings with the configured AI provider. If the AI is unavailable or the response is not valid JSON, the agent falls back to SecurityService static scanning. This makes the agent safe to use even when no AI provider is reachable.

Output Format

The agent output follows the same shape whether from AI or static rules:

{
  "risk_level": "high|medium|low",
  "findings": [
    {
      "rule_id": "SHELL_TRUE",
      "file": "app.py",
      "line": 42,
      "severity": "high",
      "issue": "Passing shell=True to subprocess can enable shell injection.",
      "recommendation": "Set shell=False and pass the command as a list of arguments.",
      "match": "subprocess.run('ls', shell=True)",
      "language": "python"
    }
  ],
  "recommendations": [
    "Set shell=False and pass the command as a list of arguments."
  ]
}

Integration

  • The security agent now appears in novacoder agents and the TUI Agents page by default.
  • AgentService.initialize() registers SecurityAgent by default and honors the agents.security flag.
  • AgentManager._register_defaults() also registers security so it is available outside the full service lifecycle.
  • The TUI Chat page loads the agent list dynamically, so security is available when enabled.

Recent Security Improvements (v0.1.0)

API Token Security

  • Token Exposure Resolution: API tokens are no longer exposed in frontend JavaScript
  • Secure Authentication: Token removed from page source to prevent XSS and browser extension access
  • Future Enhancement: HTTP-only cookies recommended for production deployments

Shell Command Hardening

  • Expanded Command Blocking: Additional dangerous commands blocked including process control, user management, and system commands
  • Shell Operator Blocking: Pipes, redirects, and command chaining operators blocked (|, &, ;, $(), `, >, <)
  • Argument Validation: Comprehensive validation for command type, timeout ranges, and working directories
  • Security Logging: All shell commands logged with security context for audit trails
  • Specific Exception Handling: Proper error handling with security-specific error messages

API Protection

  • Rate Limiting: Implemented using slowapi with IP-based client identification
  • Request Validation: Comprehensive Pydantic models with field validators and length constraints
  • Input Sanitization: All API endpoints now validate input against strict schemas
  • Abuse Prevention: Rate limits protect against DoS attacks and API abuse

Database Security

  • WAL Mode: SQLite Write-Ahead Logging enabled for better concurrency and thread safety
  • Busy Timeout: Configured busy timeout for concurrent access handling
  • Comprehensive Logging: All database operations logged for security auditing
  • Thread Safety: Enhanced synchronization with improved locking mechanisms

Security Best Practices

For Users

  • Use the comprehensive security scanning for all code changes
  • Leverage authentication and authorization for access control
  • Monitor security dashboards for threat detection
  • Review audit logs regularly for security events
  • Use secret management for storing sensitive data
  • Implement input validation for all user inputs
  • Enable rate limiting to prevent abuse
  • Use encryption for sensitive data at rest and in transit

For Developers

  • Use the security testing framework for automated security testing
  • Implement security policies for code review
  • Follow incident response playbooks for security incidents
  • Ensure compliance with relevant frameworks (SOC2, HIPAA, GDPR)
  • Use permission templates for consistent access control
  • Monitor compliance dashboards for regulatory requirements
  • Use the dynamic analysis for runtime security testing
  • Implement proper secret rotation policies

Usage Examples

Authentication and Authorization

from novacoder.security.auth import AuthenticationManager, AuthorizationManager

# Create user
auth_manager = AuthenticationManager()
user = auth_manager.create_user("username", "email@example.com", "password")

# Authenticate
authenticated = auth_manager.authenticate("username", "password")

# Check permissions
authz_manager = AuthorizationManager()
has_permission = authz_manager.has_permission(user, "read_files")

Secret Management

from novacoder.security.secret_management import SecretManager

secret_manager = SecretManager()
secret_manager.store_secret("api_key", "secret_value", SecretType.API_KEY)
api_key = secret_manager.get_secret("api_key")

Input Validation

from novacoder.security.input_validation import InputValidator, ValidationRule, ValidationRuleType

validator = InputValidator()
validator.add_rule("email", ValidationRule(
    rule_type=ValidationRuleType.EMAIL,
    error_message="Invalid email"
))
result = validator.validate({"email": "user@example.com"})

Rate Limiting

from novacoder.security.rate_limiting import RateLimitConfig, RateLimitType, RateLimiter

config = RateLimitConfig(
    limit_type=RateLimitType.API,
    max_requests=100,
    window_seconds=60
)
limiter = RateLimiter(config)
result = limiter.check_rate_limit("user_id")

Security Monitoring

from novacoder.security.monitoring import SecurityMonitor, ThreatDetector

monitor = SecurityMonitor()
detector = ThreatDetector()
monitor.get_threat_detector(detector)
monitor.start_monitoring()

Compliance Checking

from novacoder.security.compliance import ComplianceManager, ComplianceFramework

compliance_manager = ComplianceManager()
report = compliance_manager.check_compliance(ComplianceFramework.SOC2)
print(f"Compliance score: {report.compliance_score}")

Integration

  • Service Integration: SecurityService registered in app.py service container
  • UI Integration: SecurityPage in TUI displays all 15 security systems
  • API Integration: Security rules and scanning available via REST API
  • Package Exports: 88 components exported from security package for easy access

TUI Integration

The security system is integrated into the Terminal User Interface (TUI) through the SecurityPage.

SecurityPage Features

The TUI security page provides:

  • Security Systems Overview: Table view of all security subsystems with status and descriptions
  • Security Rules Management: Table view of security rules with rule ID, severity, issue, and pattern
  • Code Scanning: Text area for pasting code to scan for vulnerabilities
  • Language Selection: Input field for specifying programming language for scanning
  • Background Loading: Asynchronous loading of security systems and rules
  • Scan Results: Display of security scan results
  • Refresh Capability: Manual refresh to update security data

Navigation

Access security in the TUI:

  • Keyboard Shortcut: Shift+F1
  • Sidebar: Click "Security" in the ADVANCED section

Usage Example

# In the TUI, navigate to Security page
# View security systems overview in the systems table
# View security rules in the rules table
# Paste code to scan in the code text area
# Optionally specify the programming language
# Click Scan to perform security analysis
# View scan results in the result box

Service Integration

The SecurityPage integrates with the SecurityService:

from novacoder.security.service import SecurityService

# Security service is accessed via service integration
service = SecurityService(config)
service.initialize()

# Access security rules
rules = service._rules

# Scan code for vulnerabilities
results = service.scan_code(code, language)

Web UI Integration

The security system also provides web interface integration:

  • Security Dashboard: Comprehensive security overview with metrics and alerts
  • Rule Management: Interface for managing security rules and policies
  • Scan Results: Detailed vulnerability reports with remediation suggestions
  • Compliance Dashboard: Compliance status and reporting interface
  • Incident Response: Security incident management interface
  • Audit Logs: Security event log viewer with filtering

API Endpoints

The security system provides REST API endpoints:

  • GET /api/security/rules - List all security rules
  • POST /api/security/scan - Scan code for vulnerabilities
  • GET /api/security/components - Get security systems/component status
  • GET /api/security/compliance/{standard} - Get compliance status for a standard (also /api/security/compliance/reports, /api/security/compliance/statistics)
  • GET /api/security/incidents - List security incidents
  • POST /api/security/incidents - Report security incident
  • GET /api/security/audit - Get security audit logs

Zero Trust Architecture API Endpoints

GET /api/security/threats

List all detected security threats with optional filtering.

Query Parameters: threat_type (optional), level (optional), resolved (optional)

Response:

{
  "threats": [
    {
      "id": "threat-1",
      "type": "MALWARE",
      "level": "HIGH",
      "description": "Malware detected",
      "resolved": false
    }
  ]
}

POST /api/security/threats/{threat_id}/resolve

Resolve a security threat.

Response:

{
  "success": true,
  "resolved": true
}

GET /api/security/policies

List all configured security policies.

Response:

{
  "policies": [
    {
      "policy_id": "policy-1",
      "policy_type": "ACCESS_CONTROL",
      "name": "Access Control Policy",
      "enabled": true
    }
  ]
}

POST /api/security/policies

Add a new security policy.

Response:

{
  "success": true,
  "policy_id": "policy-1"
}

DELETE /api/security/policies/{policy_id}

Remove a security policy.

Response:

{
  "success": true
}

GET /api/security/violations

List policy violations with optional filtering.

Response:

{
  "violations": [
    {
      "violation_id": "violation-1",
      "policy_id": "policy-1",
      "description": "Policy violated",
      "resolved": false
    }
  ]
}

POST /api/security/violations/{violation_id}/resolve

Resolve a policy violation.

Response:

{
  "success": true,
  "resolved": true
}

GET /api/security/compliance/{standard}

Generate a compliance report for a standard (gdpr, hipaa, pci_dss, soc2, iso27001).

Response:

{
  "standard": "GDPR",
  "compliance_score": 85,
  "findings": [ /* compliance findings */ ]
}

GET /api/security/statistics

Get overall security statistics.

Response:

{
  "total_threats": 10,
  "resolved_threats": 8,
  "total_policies": 5,
  "total_violations": 3
}

Web UI Integration

The Security Scan system is fully integrated into the Nova Coder Web UI with a dedicated "Security Scan" navigation item under the Administration section.

Security Scan UI Features

The Security Scan UI provides:

  • Security Rules Display: View all configured security scanning rules with patterns, severity levels, and issue descriptions
  • Code Scanning Interface: Submit code for security vulnerability analysis using configured security rules
  • Dependency Vulnerability Scanning: Scan project dependencies for known vulnerabilities and outdated packages
  • IaC Security Scanning: Scan infrastructure-as-code files (Terraform, Kubernetes) for security misconfigurations
  • Container Security Scanning: Scan Docker images and Dockerfiles for security vulnerabilities
  • SAST Scanning: Run static application security testing on source code using Bandit
  • AST Security Analysis: Run AST-based security analysis on Python files
  • Secret Scanning: Scan for hardcoded secrets and credentials in the project

API Endpoints Used

The Security Scan UI integrates with the following API endpoints:

  • GET /api/security/rules - List all configured security scanning rules
  • POST /api/security/scan - Scan code for security issues
  • GET /api/security/dependency/scan - Scan dependencies for vulnerabilities
  • GET /api/security/iac/scan - Scan IaC files for security issues
  • GET /api/security/container/scan - Scan containers for security issues
  • GET /api/security/sast/scan - Run SAST scan
  • GET /api/security/ast/scan - Run AST security analysis
  • GET /api/security/secret/scan - Scan for hardcoded secrets

UI Navigation

Access the Security Scan UI by:

  1. Navigate to the Administration section in the sidebar
  2. Click on "Security Scan"
  3. The UI displays all security scanning options in a grid layout

JavaScript Integration

The Security Scan UI is implemented in novacoder/web/react/src/pages/Security.tsx with the following functions:

  • renderScan() - Main render function for the Security Scan page
  • loadSecurityRules() - Load and display security rules
  • runSecurityScan() - Execute code security scan
  • runDependencyScan() - Execute dependency vulnerability scan
  • runIaCScan() - Execute IaC security scan
  • runContainerScan() - Execute container security scan
  • runSASTScan() - Execute SAST scan
  • runASTAnalysis() - Execute AST security analysis
  • runSecretScan() - Execute secret scan

Response Handling

The UI handles API responses according to the actual response structure from each endpoint:

  • Security Rules: Expects r.rules array with pattern, severity, issue, and recommendation fields
  • Code Scan: Expects r.findings array with rule, severity, and issue fields
  • Dependency Scan: Expects scan_id, total_dependencies, vulnerable_dependencies, and severity counts
  • IaC Scan: Expects scan_id, platform, files_scanned, total_findings, and severity counts
  • Container Scan: Expects scan_id, image_name, total_vulnerabilities, secrets_found, and severity counts
  • SAST Scan: Expects execution_id, test_type, target, total_findings, and severity counts
  • AST Scan: Expects files_analyzed, total_findings, and severity counts
  • Secret Scan: Expects files_scanned, total_secrets, and severity counts
  • Agents
  • Tools
  • Configuration
  • REST API
  • Memory
  • Security Rules
  • Authentication
  • Audit Logging
  • Secret Management
  • Input Validation
  • Security Monitoring
  • Encryption
  • Permissions
  • Rate Limiting
  • Security Testing
  • Security Policies
  • Incident Response
  • Compliance
  • Permission Management
  • Dependency Scanning
  • IaC Scanning
  • Container Scanning
  • SAST/DAST
  • Security Dashboard
  • AST Analysis
  • Secret Scanning
  • Rule Validation
  • Data Privacy
  • Rule Sandbox
  • AI Provider Security
  • Scanning Cache
  • Pattern Cache
  • AI Batch Processing
  • TUI

Record 33 / 48 // Part V · Security

Authentication and Authorization

AuthN mechanisms · source wiki/security-authentication.md

Nova Coder's authentication and authorization system provides comprehensive user authentication with PBKDF2 password hashing, role-based access control (RBAC), session management with expiration, multi-factor authentication support, and user management.

Overview

The authentication and authorization system is implemented in novacoder/security/auth.py and provides:

  • User authentication with secure password hashing
  • Role-based access control (RBAC) with predefined roles
  • Session management with expiration and cleanup
  • Multi-factor authentication (MFA) support
  • User management with CRUD operations

Components

AuthenticationManager

Manages user authentication and user management operations.

from novacoder.security.auth import AuthenticationManager

auth_manager = AuthenticationManager()

Methods:

  • create_user(username, email, password) - Create a new user
  • authenticate(username, password) - Authenticate a user
  • enable_mfa(user_id) - Enable multi-factor authentication
  • verify_mfa(user_id, code) - Verify MFA code
  • change_password(user_id, old_password, new_password) - Change user password

AuthorizationManager

Manages role-based access control and permission checking.

from novacoder.security.auth import AuthorizationManager

authz_manager = AuthorizationManager()

Methods:

  • has_permission(user, permission) - Check if user has permission
  • grant_permission(user_id, permission) - Grant permission to user
  • revoke_permission(user_id, permission) - Revoke permission from user
  • assign_role(user_id, role) - Assign role to user
  • remove_role(user_id, role) - Remove role from user

SessionManager

Manages user sessions with expiration and cleanup.

from novacoder.security.auth import SessionManager

session_manager = SessionManager()

Methods:

  • create_session(user_id, duration_seconds) - Create a new session
  • validate_session(session_id) - Validate a session
  • invalidate_session(session_id) - Invalidate a session
  • cleanup_expired_sessions() - Clean up expired sessions

User Management

Creating Users

from novacoder.security.auth import AuthenticationManager

auth_manager = AuthenticationManager()
user = auth_manager.create_user("username", "email@example.com", "password")
print(f"User created: {user.username}")

Authenticating Users

from novacoder.security.auth import AuthenticationManager

auth_manager = AuthenticationManager()
authenticated = auth_manager.authenticate("username", "password")
if authenticated:
    print("Authentication successful")
else:
    print("Authentication failed")

Changing Passwords

from novacoder.security.auth import AuthenticationManager

auth_manager = AuthenticationManager()
success = auth_manager.hash_password("user_id", "old_password", "new_password")

Role-Based Access Control

Predefined Roles

The system includes predefined roles with default permissions:

  • ADMIN: Full administrative access
  • DEVELOPER: Development access
  • READER: Read-only access
  • USER: Basic user access

Assigning Roles

from novacoder.security.auth import AuthorizationManager, Role

authz_manager = AuthorizationManager()
authz_manager.assign_role("user_id", Role.ADMIN)

Checking Permissions

from novacoder.security.auth import AuthorizationManager

authz_manager = AuthorizationManager()
has_permission = authz_manager.has_permission(user, "read_files")
if has_permission:
    print("User has permission")

Granting Custom Permissions

from novacoder.security.auth import AuthorizationManager

authz_manager = AuthorizationManager()
authz_manager.grant_permission("user_id", "custom_permission")

Session Management

Creating Sessions

from novacoder.security.auth import SessionManager

session_manager = SessionManager()
session_id = session_manager.create_session("user_id", duration_seconds=3600)
print(f"Session created: {session_id}")

Validating Sessions

from novacoder.security.auth import SessionManager

session_manager = SessionManager()
is_valid = session_manager.validate_session("session_id")
if is_valid:
    print("Session is valid")

Invalidating Sessions

from novacoder.security.auth import SessionManager

session_manager = SessionManager()
session_manager.validate_session("session_id")

Multi-Factor Authentication

Enabling MFA

from novacoder.security.auth import AuthenticationManager

auth_manager = AuthenticationManager()
auth_manager.enable_mfa("user_id")

Verifying MFA Codes

from novacoder.security.auth import AuthenticationManager

auth_manager = AuthenticationManager()
is_valid = auth_manager.verify_mfa("user_id", "123456")
if is_valid:
    print("MFA code verified")

Security Features

Password Hashing

The system uses PBKDF2 with SHA-256 for secure password hashing:

  • Salt generation using cryptographically secure random
  • Configurable iteration count (default: 100,000)
  • Secure password comparison using constant-time comparison

Session Security

  • Session IDs generated using cryptographically secure random
  • Configurable session expiration
  • Automatic cleanup of expired sessions
  • Session invalidation on logout

MFA Security

  • Time-based one-time passwords (TOTP)
  • Configurable code expiration
  • Secure code verification
  • Backup codes for recovery

API Token Validation

The web interface includes client-side API token validation to ensure token security:

  • Token Format Validation: Tokens must be 16-256 characters
  • Character Validation: Only alphanumeric characters, hyphens, and underscores allowed
  • Required Field: Token cannot be empty
  • No Hardcoded Tokens: Removed hardcoded default tokens for security
  • No Auto-Login: Removed automatic login functionality to require user consent
// Client-side token validation
function validateToken(token){
  if(!token||!token.trim()){
    return {valid:false,error:'Token is required'};
  }
  const trimmed=token.trim();
  if(trimmed.length<16){
    return {valid:false,error:'Token must be at least 16 characters'};
  }
  if(trimmed.length>256){
    return {valid:false,error:'Token must not exceed 256 characters'};
  }
  if(!/^[a-zA-Z0-9\-_]+$/.test(trimmed)){
    return {valid:false,error:'Token can only contain letters, numbers, hyphens, and underscores'};
  }
  return {valid:true};
}

Best Practices

  1. Strong Passwords: Enforce strong password policies (minimum length, complexity)
  2. Session Expiration: Use appropriate session expiration times
  3. MFA: Enable MFA for sensitive operations
  4. Least Privilege: Grant only necessary permissions
  5. Regular Audits: Regularly audit user permissions and roles
  6. Password Rotation: Implement password rotation policies
  7. Secure Storage: Never store passwords in plain text

Integration

The authentication and authorization system is integrated with:

  • SecurityService: Uses authentication for security operations
  • API Endpoints: Authentication required for sensitive operations
  • TUI: Login page for user authentication
  • Audit Logging: All authentication events logged
  • Security
  • Audit Logging
  • Permissions
  • Security Policies

Record 34 / 48 // Part V · Security

Zero Trust Architecture

Zero-trust posture · source wiki/security-zero-trust.md

Overview

Zero Trust Architecture is a security model centered on the principle that no entity should be trusted by default, regardless of whether they are inside or outside the network perimeter. Nova Coder's Zero Trust implementation provides continuous authentication, least privilege enforcement, micro-segmentation, device trust verification, and session token management.

Components

IdentityAccessManager

The core manager for identities, devices, access policies, and access requests.

Key Features:

  • Identity registration and verification
  • Device management with fingerprinting
  • Access policy enforcement with least privilege
  • Session token lifecycle management
  • Access logging and statistics

Usage:

from novacoder.security.zero_trust import IdentityAccessManager, Identity, Device, DeviceStatus, TrustLevel

manager = IdentityAccessManager()

# Register identity
identity = Identity(
    identity_id="user1",
    email="user1@example.com",
    name="User 1",
    trust_level=TrustLevel.VERIFIED
)
manager.register_identity(identity)

# Register device
device = Device(
    device_id="device1",
    device_name="Laptop",
    fingerprint="abc123",
    status=DeviceStatus.TRUSTED,
    trust_level=TrustLevel.VERIFIED
)
manager.register_device(device)

# Verify identity
verified = manager.verify_identity("user1")

ContinuousVerification

Provides continuous verification of active sessions to maintain security posture.

Key Features:

  • Periodic identity and device verification
  • Automatic session revocation for invalid sessions
  • Verification history tracking
  • Configurable verification intervals

Usage:

from novacoder.security.zero_trust import ContinuousVerification

continuous_verif = ContinuousVerification(identity_manager)

# Start continuous verification
continuous_verif.get_verification_history(interval_seconds=300)

# Verify all active sessions
continuous_verif.verify_all_sessions()

# Stop verification
continuous_verif.get_verification_history()

AccessPolicy

Defines access policies with resource-based permissions and trust level requirements.

Key Features:

  • Resource-based access control
  • Trust level requirements
  • Time-based access windows
  • IP address restrictions
  • Action permissions (read, write, execute, admin)

Usage:

from novacoder.security.zero_trust import AccessPolicy, TrustLevel

policy = AccessPolicy(
    name="Database Access",
    resources=["database:production"],
    required_trust_level=TrustLevel.VERIFIED,
    actions=["read", "write"],
    allowed_ips=["203.0.113.0/24"]
)

Session Tokens

Manages session tokens with expiration and metadata — handled by IdentityAccessManager methods (there is no SessionToken class).

Key Features:

  • Token generation and validation
  • Expiration management
  • Token metadata storage
  • Revocation support

Usage:

from novacoder.security.zero_trust import IdentityAccessManager

manager = IdentityAccessManager()
token_id = manager.create_session_token(
    identity_id="user1",
    device_id="device1",
    ttl=3600,
)
manager.verify_session_token(token_id)

MutualTLSManager

Provides mutual TLS support for secure service-to-service communication.

Key Features:

  • Certificate management
  • Mutual TLS configuration
  • Certificate validation
  • Secure channel establishment

Trust Levels

The system uses a hierarchical trust level model:

  • UNTRUSTED - No trust, no access
  • LOW - Limited access to non-critical resources
  • MEDIUM - Standard access level
  • HIGH - Elevated access for trusted entities
  • VERIFIED - Highest trust level for fully verified entities

Access Request Flow

  1. Request Creation - Create access request with identity, resource, and action
  2. Policy Evaluation - Evaluate against access policies
  3. Trust Check - Verify identity and device trust levels
  4. Approval/Rejection - Approve or reject based on policy compliance
  5. Logging - Log all access requests for audit trail

Configuration

Enable Zero Trust in your security configuration:

security:
  zero_trust:
    enabled: true
    verification_interval: 300
    session_timeout: 3600
    default_trust_level: "untrusted"
    enable_mutual_tls: true

Best Practices

  1. Principle of Least Privilege - Grant minimum necessary permissions
  2. Continuous Verification - Enable continuous verification for sensitive resources
  3. Device Trust - Require device verification for all access
  4. Session Management - Use short session timeouts for high-risk operations
  5. Audit Logging - Regularly review access logs for anomalies

Integration

The Zero Trust system is integrated into the SecurityService:

from novacoder.security.service import SecurityService

security_service = SecurityService(config=config, project_path=project_path)
zero_trust = security_service.get_zero_trust_manager()
continuous_verif = security_service.get_continuous_verification()

API Endpoints

  • GET /api/security/zero-trust/identities - List identities
  • POST /api/security/zero-trust/identities - Register identity
  • GET /api/security/zero-trust/devices - List devices
  • POST /api/security/zero-trust/access-request - Submit access request (singular)
  • GET /api/security/zero-trust/statistics - Zero-trust statistics

(There are no /sessions HTTP routes — session tokens are managed in-process via IdentityAccessManager.)

Monitoring

Access events are logged and can be monitored through the monitoring system:

stats = zero_trust.get_access_statistics()
print(f"Total requests: {stats['total_requests']}")
print(f"Approved: {stats['approved_requests']}")
print(f"Rejected: {stats['rejected_requests']}")

Security Considerations

  • All access requests are logged for audit trails
  • Session tokens are cryptographically secure
  • Device fingerprints use multiple attributes for uniqueness
  • Continuous verification runs in background without performance impact
  • Mutual TLS provides end-to-end encryption for service communication

Record 35 / 48 // Part V · Security

Permissions

RBAC and permission service · source wiki/permissions.md

The Nova Coder permission system controls what tools and agents are allowed to do. It is built around Permission values, PermissionSet, PermissionChecker, and the PermissionsService kernel service.

Permission Values

from novacoder.permissions import Permission

Permission.READ_FILES
Permission.MODIFY_FILES
Permission.RUN_SHELL_COMMANDS
Permission.ACCESS_GIT
Permission.NETWORK_ACCESS
Permission.READ_MEMORY
Permission.WRITE_MEMORY

PermissionSet and PermissionChecker

A PermissionSet represents a collection of granted permissions. A PermissionChecker wraps it and can enforce a tool's required permissions.

from novacoder.permissions import Permission, PermissionChecker, PermissionSet

checker = PermissionChecker({Permission.READ_FILES, Permission.ACCESS_GIT})
checker.check(["read_files", "access_git"])  # True

# Or use PermissionSet directly
ps = PermissionSet()
ps.add(Permission.READ_FILES)
assert ps.has(Permission.READ_FILES)

PermissionsService

PermissionsService is a kernel service that builds the default PermissionChecker from ToolsConfig:

  • read_files is always granted.
  • modify_files is always granted.
  • access_git is granted when tools.git is True.
  • run_shell_commands is granted when tools.shell or tools.python is True.
  • read_memory and write_memory are always granted.

PermissionsService is registered in NovaApplication and runs before ToolService so the tool registry can resolve the checker at boot time.

Wiring with ToolRegistry

ToolRegistry accepts a permission_checker and require_approval flag. When a tool runs, the checker validates the tool's permissions list; the approval callback gates execution when require_approval is enabled.

from novacoder.permissions import Permission, PermissionChecker
from novacoder.tools.registry import ToolRegistry
from novacoder.tools.filesystem import ReadFileTool

checker = PermissionChecker({Permission.READ_FILES})
registry = ToolRegistry(permission_checker=checker)
registry.register(ReadFileTool())

result = registry.execute("read_file", path="main.py")

Wiring with ToolService and NovaApplication

PermissionsService is registered as a kernel service in NovaApplication and initialized before ToolService. ToolService resolves the PermissionsService from the container and passes permissions_service.checker() to ToolRegistry. This means every tool execution is checked against the permission set derived from tools.shell, tools.git, tools.python, and tools.require_approval.

Application boot order:
logging → workspace → memory → ai → permissions → tools → agents → plugins

Configuration

tools:
  shell: false
  git: true
  python: true
  require_approval: true

Custom Approval Callback

For CI or agent contexts, supply a custom approval_callback to ToolRegistry:

registry = ToolRegistry(
    require_approval=True,
    approval_callback=lambda name, kwargs: True,
)

Policy-as-Code API

The PermissionsService exposes a PolicyManager through the REST API:

  • GET /api/policies, Lists all configured policy rules.
  • POST /api/policies, Creates a new policy rule.
  • POST /api/policies/evaluate, Evaluates all policies against a context.
  • GET /api/policies/violations, Lists recorded policy violations.

Record 36 / 48 // Part V · Security

Device Access, Capability Discovery & Authorization

Grant-scoped host operations · source wiki/device-access.md

Nova Coder's device layer (novacoder/device/) gives the AI an accurate, live picture of the machine it runs on, platform, environment, tools, permissions, plus legitimate OS-mediated authorization workflows. It never bypasses operating-system security.

Architecture

novacoder/device/
├── platform_info.py   # OS, version, arch, distro, env context
├── states.py          # PermissionState + AccessLevel
├── discovery.py       # dev-environment inventory
├── probes.py          # os.access, sudo -n, pkexec, UAC, TCC probes
├── registry.py        # live resource → permission-state table
├── grants.py          # persisted scoped authorizations (user-managed)
├── elevation.py       # OS prompt workflows (pkexec/sudo/osascript/UAC)
├── consequential.py   # destructive-operation classification
├── audit.py           # JSONL audit log with secret redaction
├── tools.py           # DeviceOps, guarded fs/exec operation surface
├── capabilities.py    # device.* engine capabilities (11)
└── service.py         # DeviceService (kernel service #38)

Platform & environment detection

detect_platform() reports:

  • OS (linux / darwin / windows), release, version, distro, machine
  • execution context: host, wsl, container (docker/podman/k8s via /proc + env sentinels), vm (DMI vendor strings), ssh, flatpak, snap, sandboxed
  • user, uid, is_root, is_admin (via sudo -n or IsUserAnAdmin, a non-interactive check that never supplies credentials)

discover() inventories the development environment, interpreters, toolchains, package managers, VCS, containers, databases, LSP servers, local AI runtimes, GPUs (nvidia-smi/DRM), shells, mounted volumes (/proc/mounts / mount), user directories (XDG/known-folders), project markers, and local dev services (passive localhost port probe). Read-only: no writes, no file contents outside system probe files, env vars reported as presence-flags (proxy values may embed credentials).

Permission states

Every registry resource reports one of:

available · unavailable · restricted · auth_required · user_denied · temporarily_unavailable · unsupported · externally_managed

Entries are re-probed on refresh or after a staleness TTL, the environment changes, so access is never permanently assumed.

Scoped grants (user-managed)

GrantStore persists to <data_dir>/device_grants.json:

  • Kinds: project (auto-granted workspace root), directory, tool, capability
  • project_only mode (default ON): anything outside granted scopes reports auth_required. Off ⇒ user-home reads allowed, system paths still need grants.
  • Deny shadows: a denied directory blocks every path beneath it, even inside a granted scope.
  • Access ≠ authorization: a granted scope still requires explicit confirmation for consequential operations.
  • The AI-facing capabilities can list grants but cannot create or revoke them, grant mutations exist only on the authenticated API (/api/device/grants*), i.e. the user.

Elevation workflows

ElevationManager.prepare() returns the exact command, mechanism, and instructions, never executes. .launch() invokes the OS prompt:

Platform Mechanism
Linux + display pkexec (PolicyKit dialog)
Linux headless sudo detached → OS terminal prompt; or manual instructions
macOS osascript 'do shell script … with administrator privileges'
Windows ShellExecuteEx runas (UAC consent)
None available honest manual instructions, never faked

Credentials are never accepted, stored, or forwarded, sudo -S is deliberately unused. After the prompt, callers re-probe; denial results in user_denied and graceful degradation.

Consequential-operation gate

classify_command / classify_path_write separate consequence from access:

  • benign, normal dev work inside scope
  • consequential, rm -rf trees, system package/process changes, writes outside scope or to ~/.ssh-class areas → needs confirmed
  • elevated, protected system locations (/etc, C:\Windows, /System…) → needs elevation AND confirmation
  • prohibited, security-control edits (visudo, tccutil, csrutil, bcdedit, firewall/SELinux/apparmor changes) → always refused; the user does these manually

Guarded operations (DeviceOps)

service.ops (tools.py) is the single funnel for device-level file/command work, the "clear tool interfaces" the AI uses instead of raw filesystem/subprocess access:

  • fs_list(path), directory listing inside a granted scope
  • fs_read(path, max_bytes), text read; byte-capped, binary refused
  • fs_write(path, content, confirmed=, create_dirs=), write; confirm-gated when the consequence classifier flags it
  • exec(argv, cwd, timeout, confirmed=), argv only (no shell string interpolation); cwd must be inside a granted scope; timeout-capped

Every operation runs the same gate chain: grant scope → OS probe → consequence classification → audit. The structured result carries {ok, state, data, reason, consequence}, state explains a refusal (auth_required, prohibited, failed) instead of raising. Even a confirmed destructive op still runs as the normal user, the OS's own permission check is a second, independent gate.

Audit

<data_dir>/device_audit.jsonl records tool, category, resource, action, elevation, authorization, outcome, with token/key/password patterns redacted before persisting. Size-capped rotation. Every guarded op attempt (allowed or refused) is recorded.

API

Route Purpose
GET /api/device/info platform + context + grant summary
GET /api/device/inventory?refresh= environment inventory
GET /api/device/registry?refresh= resource state table
POST /api/device/registry/refresh re-probe everything
POST /api/device/access/check probe+grant+consequence for a path
POST /api/device/command/check classify a command
GET/POST /api/device/grants · POST …/grants/revoke grant mgmt
POST /api/device/project_only scope-mode toggle
POST /api/device/elevate prepare (invoke:false) or launch prompt
GET /api/device/audit audit tail
POST /api/device/fs/list guarded directory listing
POST /api/device/fs/read guarded file read (max_bytes cap)
POST /api/device/fs/write guarded write (confirmed when flagged)
POST /api/device/exec guarded command (argv, cwd, timeout, confirmed)

Engine capabilities

Read-only discovery/inspection: device.info, device.inventory, device.check_access, device.request_access (prepare only), device.elevate (launches OS prompt, requires_approval), device.grants, device.audit.

Guarded operations (grant + consequence gated): device.fs.list, device.fs.read, device.fs.write, device.exec.

UI

/device page (View → Device): platform card, environment inventory, live registry with per-resource states and re-probe, grant management with revoke/deny and project-only toggle, access checker, elevation helper, and the audit table.

Boundaries

  • Most operations run with standard user privileges; elevation is per-operation, OS-mediated.
  • Discovery never ingests file contents; grants scope what the AI may touch.
  • macOS/Windows backends are implemented (osascript/TCC probes, runas/UAC) but verified only on Linux, see report 31.

Record 37 / 48 // Part V · Security

Tool Sandboxing System

Sandboxed tool execution · source wiki/tool-sandboxing.md

Overview

The Tool Sandboxing System provides secure execution environments for Nova Coder tools with multiple isolation levels, resource limits, and violation tracking. This system enhances security by isolating tool execution and preventing potential system damage from malicious or buggy tools.

Location

  • File: novacoder/tools/sandboxing.py
  • Components: ToolSandbox, SandboxManager, SandboxLevel, ResourceLimits, SandboxViolation

Key Features

Multi-Level Isolation

The system provides four isolation levels for different security requirements:

  • NONE: No isolation - full system access (for trusted tools)
  • BASIC: Basic import restrictions and resource monitoring
  • STRICT: Full isolation with resource limits and access controls
  • PARANOID: Maximum isolation with strict security policies

Resource Limits

Configurable resource limits for sandboxed execution:

  • Memory Limits: Maximum memory usage in MB
  • CPU Limits: Maximum CPU percentage usage
  • Execution Time: Maximum execution time in seconds
  • File Descriptors: Maximum number of open file descriptors
  • Network Connections: Maximum number of network connections
  • Module Restrictions: Allowed/blocked Python modules
  • Path Restrictions: Allowed/blocked file system paths
  • Network Control: Allow/deny network access
  • File Access Control: Allow/deny file read/write operations

Violation Tracking

Automatic detection and tracking of sandbox violations:

  • Memory limit violations
  • CPU limit violations
  • Time limit violations
  • File access violations
  • Network access violations
  • Import restriction violations
  • System call violations

Components

SandboxLevel

Enum defining isolation levels:

class SandboxLevel(Enum):
    NONE = "none"
    BASIC = "basic"
    STRICT = "strict"
    PARANOID = "paranoid"

ResourceLimits

Dataclass for resource limit configuration:

@dataclass
class ResourceLimits:
    max_memory_mb: Optional[int] = None
    max_cpu_percent: Optional[float] = None
    max_execution_time: Optional[float] = None
    max_file_descriptors: Optional[int] = None
    max_network_connections: Optional[int] = None
    allowed_modules: Optional[Set[str]] = None
    blocked_modules: Optional[Set[str]] = None
    allowed_paths: Optional[Set[str]] = None
    blocked_paths: Optional[Set[str]] = None
    allow_network: bool = True
    allow_file_write: bool = True
    allow_file_read: bool = True

ToolSandbox

Main sandbox execution class with methods:

  • execute_tool(tool, **kwargs): Execute a tool within the sandbox
  • get_violations(): Get all recorded violations
  • clear_violations(): Clear all recorded violations
  • get_active_executions(): Get currently active executions

SandboxManager

Manager for multiple tool sandboxes:

  • create_sandbox(tool_name, level, limits): Create a sandbox for a specific tool
  • get_sandbox(tool_name): Get sandbox for a tool
  • remove_sandbox(tool_name): Remove sandbox for a tool
  • get_all_violations(): Get all violations from all sandboxes
  • get_statistics(): Get sandbox statistics

Usage Example

Basic Sandboxing

from novacoder.tools import SandboxLevel, ResourceLimits, ToolSandbox
from novacoder.tools.filesystem import ReadFileTool

# Create a sandbox with strict isolation
limits = ResourceLimits(
    max_memory_mb=512,
    max_cpu_percent=50.0,
    max_execution_time=30.0,
    allow_network=False,
    allow_file_write=False
)

sandbox = ToolSandbox(level=SandboxLevel.STRICT, limits=limits)

# Execute a tool within the sandbox
tool = ReadFileTool()
result = sandbox.execute_tool(tool, path='/path/to/file.txt')

print(f"Success: {result.success}")
print(f"Output: {result.output}")
print(f"Violations: {len(result.violations)}")
print(f"Execution time: {result.execution_time:.3f}s")
print(f"Memory used: {result.memory_used_mb:.2f}MB")

Sandbox Manager

from novacoder.tools import SandboxManager, SandboxLevel, get_sandbox_manager

# Get the global sandbox manager
manager = get_sandbox_manager()

# Create sandboxes for different tools
manager.create_sandbox('read_file', level=SandboxLevel.BASIC)
manager.create_sandbox('shell', level=SandboxLevel.PARANOID)

# Get sandbox statistics
stats = manager.get_statistics()
print(f"Total sandboxes: {stats['total_sandboxes']}")
print(f"Total violations: {stats['total_violations']}")
print(f"Active executions: {stats['active_executions']}")

Custom Resource Limits

from novacoder.tools import ResourceLimits, SandboxLevel

# Create custom resource limits for a specific tool
limits = ResourceLimits(
    max_memory_mb=1024,  # 1GB memory limit
    max_cpu_percent=75.0,  # 75% CPU limit
    max_execution_time=60.0,  # 60 second timeout
    max_file_descriptors=100,
    allowed_modules={'os', 'sys', 'json'},  # Only allow specific modules
    blocked_modules={'subprocess', 'eval'},  # Block dangerous modules
    allow_network=False,  # Disable network access
    allow_file_write=False,  # Read-only file access
)

sandbox = ToolSandbox(level=SandboxLevel.STRICT, limits=limits)

Registry Pattern

The sandbox system uses a global manager pattern:

from novacoder.tools import get_sandbox_manager, set_sandbox_manager

# Get the global manager (singleton)
manager = get_sandbox_manager()

# Set a custom manager if needed
custom_manager = SandboxManager(default_level=SandboxLevel.PARANOID)
set_sandbox_manager(custom_manager)

Best Practices

  1. Choose Appropriate Isolation Level

    • Use NONE only for trusted, internal tools
    • Use BASIC for tools that need monitoring but aren't dangerous
    • Use STRICT for most user-executable tools
    • Use PARANOID for tools with high security requirements
  2. Set Reasonable Resource Limits

    • Memory limits should be based on expected tool usage
    • CPU limits prevent tools from monopolizing system resources
    • Execution time limits prevent hanging tools
    • File descriptor limits prevent resource exhaustion
  3. Monitor Violations

    • Regularly check violation logs for security issues
    • Use violation patterns to identify problematic tools
    • Adjust resource limits based on violation patterns
  4. Use Sandbox Manager

    • Create dedicated sandboxes for different tool categories
    • Use the manager for centralized sandbox management
    • Track statistics to optimize sandbox configuration

CI/CD Integration

# In CI/CD pipelines, use strict sandboxing for all tool execution
from novacoder.tools import SandboxLevel, ResourceLimits, get_sandbox_manager

ci_limits = ResourceLimits(
    max_memory_mb=2048,
    max_execution_time=300.0,  # 5 minutes
    allow_network=False
)

manager = get_sandbox_manager()
manager.create_sandbox('ci_tool', level=SandboxLevel.STRICT, limits=ci_limits)

Troubleshooting

Common Issues

Tool execution fails with "Execution time limit exceeded"

  • Increase max_execution_time in ResourceLimits
  • Check if tool is actually hanging or just slow
  • Consider optimizing the tool implementation

Tool fails with "Memory limit exceeded"

  • Increase max_memory_mb in ResourceLimits
  • Check for memory leaks in tool implementation
  • Consider processing data in chunks

Module import violations

  • Add required modules to allowed_modules in ResourceLimits
  • Check if module is actually needed for tool functionality
  • Consider alternative implementations that don't require restricted modules

File access violations

  • Add required paths to allowed_paths in ResourceLimits
  • Check if file access is actually necessary
  • Consider using temporary directories for file operations

Security Considerations

  1. Always use sandboxing for untrusted tools
  2. Use PARANOID level for tools with system access
  3. Disable network access for tools that don't need it
  4. Restrict file system access to minimum required paths
  5. Monitor violation logs for security incidents
  6. Regularly audit sandbox configurations

Performance Optimization

  1. Use BASIC level for performance-critical tools
  2. Adjust resource limits based on actual usage patterns
  3. Reuse sandbox instances for repeated tool execution
  4. Monitor sandbox overhead and adjust accordingly
  5. Use violation data to optimize resource limits

Development Instructions

Adding New Isolation Levels

class SandboxLevel(Enum):
    NONE = "none"
    BASIC = "basic"
    STRICT = "strict"
    PARANOID = "paranoid"
    CUSTOM = "custom"  # Add new level

Adding New Violation Types

class SandboxViolationType(Enum):
    MEMORY_LIMIT = "memory_limit"
    CPU_LIMIT = "cpu_limit"
    TIME_LIMIT = "time_limit"
    FILE_ACCESS = "file_access"
    NETWORK_ACCESS = "network_access"
    IMPORT_RESTRICTION = "import_restriction"
    SYSTEM_CALL = "system_call"
    CUSTOM_VIOLATION = "custom_violation"  # Add new type

See Also

Record 38 / 48 // Part VI · Operations

Advanced Monitoring and Observability System

Metrics and dashboards · source wiki/monitoring-system.md

Overview

The Advanced Monitoring and Observability System provides comprehensive monitoring, logging, and observability capabilities with metrics collection, distributed tracing, log aggregation, alerting, and dashboard visualization. The system includes advanced features such as alert notification channels (email, Slack, webhooks), OpenTelemetry-style distributed tracing with context propagation, and Prometheus-compatible metrics collection with aggregation and retention policies.

Components

AdvancedMonitoring

The advanced monitoring manager with comprehensive observability features.

Location: novacoder/monitoring/advanced.py

Key Features:

  • Metrics Collection: Counters, gauges, histograms with automatic aggregation
  • Distributed Tracing: Span-based tracing with parent-child relationships
  • Log Aggregation: Centralized log collection with filtering and querying
  • Alerting: Rule-based alerting with severity levels and status tracking
  • Event Callbacks: Subscribe to monitoring events for custom handling
  • Thread-Safe Operations: All operations are thread-safe for concurrent access

MonitoringManager

Central manager for all monitoring components.

Location: novacoder/monitoring/manager.py

Key Features:

  • Orchestrates all monitoring components
  • Manages alerts, logs, performance, user analytics, and dashboards
  • Provides overall statistics and configuration

MonitoringService

Kernel service that wires MonitoringManager, AdvancedMonitoring, AlertManager, and the OpenTelemetry exporter. get_advanced_monitoring() now lazy-initializes an AdvancedMonitoring instance and registers it with the global registry if initialize() has not yet been called. This prevents the TUI Monitoring page from crashing when it is mounted before the full service lifecycle has run.

AlertManager

Manages alerts and notifications.

Location: novacoder/monitoring/alerts.py

Key Features:

  • Alert rule management
  • Multiple notification channels (Email, Slack, Webhook)
  • Alert severity levels (Critical, High, Medium, Low, Info)
  • Alert status tracking (Active, Acknowledged, Resolved)
  • Notification routing based on severity
  • Custom notification filtering
  • Alert acknowledgment and resolution workflow
  • AlertDeliveryService for background alert delivery
  • Queue-based alert processing with background thread
  • Delivery history tracking with success/failure recording
  • Delivery statistics and monitoring
  • Configurable delivery interval

Documentation: Alert Notification Channels, Alert Delivery

LogAggregator

Aggregates and analyzes logs.

Location: novacoder/monitoring/log_aggregation.py

Key Features:

  • Log collection from multiple sources
  • Log filtering and querying
  • Log analysis and statistics
  • Log level management (Debug, Info, Warning, Error, Critical)

PerformanceMonitor

Monitors system performance metrics.

Location: novacoder/monitoring/performance.py

Key Features:

  • Metric collection (Counter, Gauge, Histogram)
  • Performance threshold management
  • Anomaly detection
  • Trend analysis

UserAnalytics

Tracks user behavior analytics.

Location: novacoder/monitoring/user_analytics.py

Key Features:

  • User session tracking
  • Activity type classification
  • User metrics calculation
  • Behavior analysis

Dashboard

Dashboard manager for visualization.

Location: novacoder/monitoring/dashboard.py

Key Features:

  • Dashboard configuration management
  • Widget system (gauge, line chart, bar chart, pie chart, table, stat card, log viewer, alert list, metric summary)
  • Dashboard templates (system overview, application monitoring, log analysis, performance monitoring, user analytics)
  • HTML rendering with SVG charts
  • JSON and HTML export functionality
  • API endpoints for dashboard data, rendering, and export
  • DashboardRenderer class for HTML generation
  • DashboardExporter class for JSON/HTML export

Documentation: Monitoring Dashboard

Distributed Tracing

OpenTelemetry-style distributed tracing with context propagation.

Location: novacoder/monitoring/tracing.py

Key Features:

  • Tracer and Span management
  • Trace context propagation (traceparent headers)
  • Multiple sampling strategies (Always, Never, Probability, TraceIDRatio, NameBased)
  • Span lifecycle management with context manager
  • Span events and attributes
  • TracerProvider for service-wide tracing
  • Prometheus-compatible export

Documentation: Distributed Tracing

Metrics Collection

Prometheus-compatible metrics collection with aggregation and retention policies.

Location: novacoder/monitoring/metrics.py

Key Features:

  • Counter, Gauge, Histogram, Summary metrics
  • Label support for multi-dimensional metrics
  • MetricsRegistry for central management
  • MetricsAggregator for time-based aggregation
  • MetricsRetentionPolicy for data retention
  • Prometheus format export
  • Thread-safe operations
  • MetricsStorageBackend for persistent metrics storage
  • In-memory and disk-based storage options
  • Time-based filtering and limit controls
  • Automatic retention management (10,000 samples per metric)
  • Storage statistics and metrics

Documentation: Metrics Collection, Metrics Storage

API Endpoints

GET /api/monitoring/dashboards

List available monitoring dashboard templates.

Response:

{
  "dashboards": {
    "system-overview": { /* dashboard config */ },
    "application-monitoring": { /* dashboard config */ },
    "log-analysis": { /* dashboard config */ }
  }
}

GET /api/monitoring/dashboards/{dashboard_id}

Get a specific dashboard with data.

Response:

{
  "dashboard_id": "system-overview",
  "name": "System Overview",
  "config": { /* dashboard config */ },
  "data": { /* widget data */ }
}

GET /api/monitoring/metrics/history

Get historical data for a specific metric.

Query Parameters: metric_name (required), hours (default: 24)

Response:

{
  "metric_name": "cpu_percent",
  "history": [
    { "timestamp": 1234567890, "value": 25.5 }
  ]
}

GET /api/monitoring/traces/{trace_id}

Get all spans in a trace.

Response:

{
  "trace_id": "trace-123",
  "spans": [
    { "span_id": "span-1", "operation": "op1", "duration": 100 }
  ]
}

GET /api/monitoring/logs

Query log entries with optional filtering.

Query Parameters: level (optional), source (optional), limit (default: 100)

Response:

{
  "logs": [
    { "timestamp": 1234567890, "level": "INFO", "message": "Log message" }
  ]
}

POST /api/monitoring/alert-rules

Add a new alert rule.

Response:

{
  "success": true,
  "rule_id": "rule-123"
}

DELETE /api/monitoring/alert-rules/{rule_id}

Remove an alert rule.

Response:

{
  "success": true
}

POST /api/monitoring/alerts/{alert_id}/acknowledge

Acknowledge an alert.

Response:

{
  "success": true
}

POST /api/monitoring/alerts/{alert_id}/resolve

Resolve an alert.

Response:

{
  "success": true
}

GET /api/monitoring/alerts

Returns all monitoring alerts.

GET /api/monitoring/statistics

Returns overall monitoring statistics.

GET /api/monitoring/opentelemetry/export

Export traces, metrics, and logs in OTLP-compatible JSON format.

POST /api/monitoring/opentelemetry/export

Write exported traces, metrics, and logs to a file path provided in the request body ({"file_path": "/path/to/export.json"}).

Usage Example

Advanced Monitoring System

from novacoder.monitoring import AdvancedMonitoring, MetricType, AlertSeverity, AlertStatus

# Create advanced monitoring manager
monitoring = AdvancedMonitoring()
monitoring.start()

# Record metrics
monitoring.record_metric('cpu_usage', 75.5, MetricType.GAUGE, unit='percent')
monitoring.increment_counter('request_count', 1.0)
monitoring.set_gauge('memory_usage', 512.0, unit='MB')

# Distributed tracing
span = monitoring.start_span('api_request', parent_span_id=None, metadata={'endpoint': '/api/users'})
# ... do work ...
monitoring.finish_span(span.span_id)

# Log aggregation
monitoring.add_log('info', 'User logged in', 'auth-service', metadata={'user_id': '123'})

# Alerting
from novacoder.monitoring.advanced import AlertRule
rule = AlertRule(
    name='High CPU Alert',
    metric_name='cpu_usage',
    condition='greater_than',
    threshold=80.0,
    severity=AlertSeverity.WARNING
)
monitoring.add_alert_rule(rule)

# Get monitoring statistics
stats = monitoring.get_monitoring_stats()
print(f"Total metrics: {stats['total_metrics']}")
print(f"Total spans: {stats['total_spans']}")
print(f"Total logs: {stats['total_logs']}")

monitoring.stop()

Traditional Monitoring Manager

from novacoder.monitoring.manager import MonitoringManager, MonitoringConfig
from novacoder.monitoring.alerts import AlertRule, AlertSeverity

# Create manager
config = MonitoringConfig()
manager = MonitoringManager(config)

# Create alert rule
rule = AlertRule(
    name="High CPU",
    condition="cpu_usage > 80",
    severity=AlertSeverity.HIGH
)
manager.add_alert_rule(rule)

# Record performance metric
manager.record_metric("cpu_usage", 75.5)

# Check for alerts
alerts = manager.get_alerts()
for alert in alerts:
    print(f"Alert: {alert.message}")

Integration

Service: MonitoringService in novacoder/monitoring/service.py

The monitoring system is integrated into the NovaApplication and accessible via:

  • Service container: container.resolve(MonitoringService)
  • API endpoints for alerts and statistics
  • Integration with kernel observability features

Service Integration Details

The monitoring service is registered in the application service order and follows the standard Nova Coder service lifecycle:

from novacoder.app import create_app
from novacoder.monitoring.service import MonitoringService

app = create_app()
app.start()

# Access the monitoring service
monitoring_service = app.container.resolve(MonitoringService)
manager = monitoring_service.get_manager()

# Get system statistics
stats = manager.get_overall_statistics()
print(f"Total metrics: {stats['total_metrics']}")
print(f"Active alerts: {stats['active_alerts']}")

API Integration

The monitoring system exposes the following REST API endpoints:

  • GET /api/monitoring/alerts - List all monitoring alerts
  • GET /api/monitoring/statistics - Get overall monitoring statistics
  • GET /api/monitoring/metrics - Get system metrics
  • Additional endpoints for alert management, log aggregation, and performance monitoring

Web UI Integration

The monitoring system is integrated into the web interface with:

  • Navigation menu item under "Administration" section
  • Real-time dashboard with metrics visualization
  • Alert management interface
  • Log aggregation and analysis
  • Performance monitoring and trend analysis

Location: novacoder/web/react/src/pages/Monitoring.tsx - renderMonitoring() function

Web UI Features:

  • System Metrics Cards: Display total alerts, active alerts, resolved alerts, and alerts by severity (critical, warning, info)
  • Service Health Table: View service status, health status, and messages for all Nova Coder services
  • Alerts Table: View all alerts with severity, message, timestamp, and resolution status
  • Monitoring Statistics Table: View all monitoring statistics and metrics
  • Real-time Data Loading: Asynchronous API calls to fetch monitoring data
  • Error Handling: User-friendly error display for failed API calls

Web UI API Integration:

  • GET /api/monitoring/statistics - Fetch overall monitoring statistics
  • GET /api/monitoring/alerts - Fetch all monitoring alerts
  • GET /api/health - Fetch system health metrics

Web UI Usage:

// The renderMonitoring() function is called when navigating to the Monitoring page
async function renderMonitoring(){
  // Render UI structure with metrics cards, service health table, alerts table, and statistics
  $('content').innerHTML = `...`;

  // Fetch data from API endpoints
  const [stats,health,alerts]=await Promise.all([
    api('/api/monitoring/statistics'),
    api('/api/health'),
    api('/api/monitoring/alerts')
  ]);

  // Update UI with fetched data
  set('monitoring-metrics', metricsHTML);
  set('monitoring-services', servicesHTML);
  set('monitoring-alerts', alertsHTML);
  set('monitoring-stats', statsHTML);
}

TUI Integration

The monitoring system is now fully integrated into the Terminal User Interface (TUI) with the MonitoringPage:

Location: novacoder/gui/tui_screens/monitoring_page.py - MonitoringPage class

TUI Features:

  • System Metrics: View CPU, memory, disk, and network metrics
  • Service Health: Monitor health status of all Nova Coder services
  • Alert Management: View and manage active alerts with severity levels
  • Real-time Updates: Auto-refresh every 5 seconds for live monitoring
  • Service Integration: Direct integration with MonitoringService via _get_service()

TUI Navigation:

  • Keyboard Shortcut: Shift+F8 to access Monitoring page
  • Sidebar Navigation: "Monitoring" button under "NEW SYSTEMS" section
  • Page Routing: Integrated into main TUI page navigation system

TUI Usage:

# The TUI page automatically loads metrics on mount
def on_mount(self) -> None:
    self._setup_tables()
    self._load_metrics()
    self._set_refresh_interval(5.0)  # Auto-refresh every 5 seconds

# Background loading with service integration
@work(thread=True)
def _load_metrics(self) -> None:
    from novacoder.monitoring.service import MonitoringService
    
    svc = _get_service(MonitoringService)
    if not svc:
        self.app.call_from_thread(self._show_error, "Monitoring service unavailable")
        return
    
    metrics = svc.manager.get_user_metrics()
    health = svc.manager.get_user_analytics()
    alerts = svc.manager.get_alerts()
    # Update tables with metrics, health status, and alerts

Alert Rules

CPU Usage

AlertRule(
    name="High CPU",
    condition="cpu_usage > 80",
    severity=AlertSeverity.HIGH
)

Memory Usage

AlertRule(
    name="High Memory",
    condition="memory_usage > 90",
    severity=AlertSeverity.CRITICAL
)

Response Time

AlertRule(
    name="Slow Response",
    condition="response_time > 5000",
    severity=AlertSeverity.MEDIUM
)

Dashboard Widgets

Chart Widget

DashboardWidget(
    name="CPU Usage",
    widget_type=WidgetType.CHART,
    config={"metric": "cpu_usage", "time_range": "1h"}
)

Gauge Widget

DashboardWidget(
    name="Memory Usage",
    widget_type=WidgetType.GAUGE,
    config={"metric": "memory_usage", "max": 100}
)

Table Widget

DashboardWidget(
    name="Recent Logs",
    widget_type=WidgetType.TABLE,
    config={"source": "logs", "limit": 10}
)

Benefits

  • System Visibility: Real-time monitoring of system health
  • Proactive Detection: Alert on issues before they become critical
  • Performance Optimization: Identify bottlenecks and optimize
  • Debugging Support: Detailed logs and traces for troubleshooting
  • User Insights: Understand user behavior and patterns
  • Custom Dashboards: Visualize metrics relevant to your needs

Configuration

Monitoring settings can be configured through the application configuration:

{
  "monitoring": {
    "enable_alerts": true,
    "enable_log_aggregation": true,
    "enable_performance_monitoring": true,
    "enable_user_analytics": true,
    "log_retention_days": 30,
    "metric_retention_days": 7,
    "alert_notification_channels": ["email", "slack"]
  }
}

See Also

  • Kernel Observability - Kernel-level observability
  • Health Monitoring - Health check system
  • API Analytics - API-specific analytics
  • Agent Monitoring - Agent performance monitoring
  • Distributed System Architecture - Distributed monitoring integration

Web UI Integration

The Monitoring system is fully integrated into the Nova Coder Web UI with a dedicated "Monitoring" navigation item under the Administration section.

Monitoring UI Features

The Monitoring UI provides:

  • Dashboard Selection: Choose from multiple dashboard templates (System Overview, Application Monitoring, Log Analysis)
  • Auto-Refresh Settings: Configure automatic refresh intervals (Off, 30s, 1m, 5m)
  • Real-Time Metrics Display: CPU, memory, and disk usage metrics in real-time
  • System Health Display: Service status and health indicators
  • Alerts Display: List of monitoring alerts with severity, message, timestamp, and status
  • Monitoring Statistics: Overall monitoring statistics and metrics

API Endpoints Used

The Monitoring UI integrates with the following API endpoints:

  • GET /api/monitoring/alerts - List all monitoring alerts
  • GET /api/monitoring/statistics - Get overall monitoring statistics
  • GET /api/monitoring/dashboards - List available dashboard templates
  • GET /api/monitoring/dashboards/{dashboard_id} - Get specific dashboard configuration
  • GET /api/monitoring/metrics - Get real-time system metrics
  • GET /api/monitoring/metrics/history/{metric_name} - Get historical metric data
  • GET /api/monitoring/traces/{trace_id} - Get distributed trace data
  • GET /api/monitoring/logs - Query log entries with filters
  • POST /api/monitoring/alerts/rules - Add alert rule
  • DELETE /api/monitoring/alerts/rules/{rule_id} - Remove alert rule
  • POST /api/monitoring/alerts/{alert_id}/acknowledge - Acknowledge alert
  • POST /api/monitoring/alerts/{alert_id}/resolve - Resolve alert

UI Navigation

Access the Monitoring UI by:

  1. Navigate to the Administration section in the sidebar
  2. Click on "Monitoring"
  3. The UI displays monitoring dashboard, metrics, alerts, and statistics

JavaScript Integration

The Monitoring UI is implemented in novacoder/web/react/src/pages/Monitoring.tsx with the following functions:

  • renderMonitoring() - Main render function for the Monitoring page
  • loadRealTimeMetrics() - Load and display real-time system metrics
  • loadMonitoringDashboard() - Load and display selected dashboard
  • loadMonitoringAlerts() - Load and display monitoring alerts

Response Handling

The UI handles API responses according to the actual response structure from each endpoint:

  • Monitoring Statistics: Expects stats.data||stats with total_alerts, active_alerts, resolved_alerts, critical_alerts, warning_alerts, info_alerts
  • Monitoring Alerts: Expects alerts.data?.alerts||alerts.alerts||[] with severity, message, timestamp, resolved fields
  • Real-Time Metrics: Expects r.data||r with cpu, memory, disk objects containing percent, count, used, total fields
  • Dashboard Data: Expects r.data||r with config and data objects

OpenTelemetry Export (React UI)

The Monitoring page (/monitoring) includes a dedicated OpenTelemetry Export card:

  • Export OpenTelemetry JSON - Calls GET /api/monitoring/opentelemetry/export and displays the OTLP-formatted JSON response.
  • Export to File - Calls POST /api/monitoring/opentelemetry/export with an optional path field and shows the written file path.

Both controls are wired to useAccessibility for screen-reader announcements and display results in keyboard-focusable <pre> blocks.

Record 39 / 48 // Part VI · Operations

Health Monitoring

Service health evaluation · source wiki/health-monitoring.md

Nova Coder includes a comprehensive health monitoring system that provides real-time metrics for system health, resource usage, and service status. The health monitoring system is accessible via the REST API and displayed in the web dashboard.

Components

  • novacoder/api/routes_system.py, Health check endpoint with detailed metrics
  • novacoder/api/_html.py, Dashboard UI for health metrics display
  • psutil, System metrics collection library

Health Endpoint

The /api/health endpoint provides comprehensive health information. It is intentionally public so load balancers, monitoring probes, and the web dashboard can check status without authentication.

Recent fixes

  • ServicesService recursion: The services monitoring service previously called its own health() while listing other services, causing an exponential cascade of health checks. It now uses super().health() when inspecting itself.
  • AIService.health() thread safety: Async provider health_check() calls now run in a dedicated thread with their own event loop, preventing RuntimeWarning / RecursionError in synchronous health paths.
  • Lifecycle.health() deduplication: Each service's health() is evaluated once per application health check, reducing redundant work such as repeated Ollama provider probes.
curl http://localhost:8000/api/health

Response Format

{
  "status": "healthy",
  "message": "All systems operational",
  "services": {
    "memory": {
      "status": "running",
      "healthy": true,
      "message": "Memory service operational"
    },
    "ai": {
      "status": "running",
      "healthy": true,
      "message": "AI provider available"
    }
  },
  "metrics": {
    "memory": {
      "rss_mb": 125.5,
      "vms_mb": 450.2,
      "percent": 12.3
    },
    "database": {
      "status": "connected"
    },
    "ai_provider": {
      "available": true,
      "provider_count": 1
    },
    "queue_depth": 0
  }
}

Metrics

Memory Metrics

  • RSS (Resident Set Size): Actual physical memory used by the process in MB
  • VMS (Virtual Memory Size): Total virtual memory allocated in MB
  • Memory Percentage: Percentage of total system memory used
import psutil
process = psutil.Process()
memory_info = process.memory_info()
memory_percent = process.memory_percent()

Database Metrics

  • Connection Status: Whether the database connection is active
  • Database Type: SQLite (with WAL mode enabled)
  • Connection Health: Connection validation status

AI Provider Metrics

  • Provider Availability: Whether AI providers are accessible
  • Provider Count: Number of configured AI providers
  • Provider Status: Individual provider health status

Queue Metrics

  • Queue Depth: Number of pending requests in the processing queue
  • Queue Status: Whether the queue is processing normally
  • Backlog Warning: Alert if queue depth exceeds threshold

Dashboard Integration

The web dashboard displays health metrics in real-time:

Dashboard Cards

  • Memory Usage: Shows memory percentage and RSS usage
  • Database Status: Shows database connection status
  • AI Provider Status: Shows provider availability
  • Queue Depth: Shows pending request count
  • Service Status: Overall system health indicator

Auto-Refresh

The dashboard automatically refreshes health metrics every 20 seconds to provide near real-time monitoring.

Health Status Levels

  • healthy: All systems operational, no issues detected
  • degraded: Some services have issues but system is functional
  • error: Critical issues affecting system functionality
  • unknown: Health check failed or metrics unavailable

Fallback Behavior

If detailed metrics collection fails, the health endpoint falls back to basic status reporting:

{
  "status": "unknown",
  "message": "Metrics collection failed",
  "services": {}
}

This ensures the health endpoint remains functional even if metrics collection encounters issues.

Configuration

Health monitoring is automatically enabled when the API server starts. No additional configuration is required.

Dependencies

The health monitoring system requires psutil for system metrics collection:

pip install psutil

This is included in the API optional dependencies:

pip install novacoder[api]

Monitoring Best Practices

For Users

  • Monitor memory usage trends over time
  • Check database status if experiencing memory issues
  • Review queue depth during high-load periods
  • Set up alerts for degraded or error status

For Developers

  • Add custom health checks for new services
  • Log health check failures with context
  • Implement graceful degradation for missing metrics
  • Test health endpoint under load conditions

Adding Custom Health Checks

To add custom health checks for new services:

  1. Add service status to the health endpoint in novacoder/api/routes_system.py
  2. Include service-specific metrics in the response
  3. Add corresponding UI cards in novacoder/api/_html.py
  4. Test health check failure scenarios
# Example custom health check
custom_status = {
    "status": "running",
    "healthy": True,
    "message": "Custom service operational"
}

Troubleshooting

High Memory Usage

  • Check for memory leaks in long-running processes
  • Review memory purge intervals
  • Consider increasing system memory if consistently high

Database Connection Issues

  • Verify database file permissions
  • Check disk space for database growth
  • Review WAL mode checkpoint intervals

AI Provider Unavailable

  • Verify API key configuration
  • Check network connectivity to AI provider
  • Review provider-specific rate limits

Queue Depth Growing

  • Check for stuck requests
  • Review processing bottlenecks
  • Consider scaling resources

Web UI Integration

The Health system is fully integrated into the Nova Coder Web UI with a dedicated "Health" navigation item under the Administration section.

Health UI Features

The Health UI provides:

  • System Status Display: Overall system health status (healthy, degraded, error, unknown)
  • System Message Display: Descriptive message about current system state
  • Memory Metrics Display: RSS memory usage, VMS memory usage, and memory percentage
  • Database Status Display: Database connection status
  • AI Provider Status Display: AI provider availability and status
  • Service Health Counts: Total services count and healthy services count

API Endpoints Used

The Health UI integrates with the following API endpoint:

  • GET /api/health - Get detailed health metrics including memory usage, database status, and AI provider availability

UI Navigation

Access the Health UI by:

  1. Navigate to the Administration section in the sidebar
  2. Click on "Health"
  3. The UI displays health metrics in a grid layout

JavaScript Integration

The Health UI is implemented in novacoder/web/react/src/pages/Monitoring.tsx with the following functions:

  • renderHealth() - Main render function for the Health page
  • loadHealthData() - Load and display health metrics

Response Handling

The UI handles API responses according to the actual response structure from the health endpoint:

  • Health Response: Expects status, message, services (object with service names as keys), and metrics (object containing memory, database, ai_providers, and queue)
  • Memory Metrics: Expects rss_mb, vms_mb, and percent fields
  • Database Metrics: Expects status field
  • AI Provider Metrics: Expects status field
  • Services: Expects object with service names as keys, each containing healthy, status, and message fields

Display Format

The Health UI displays metrics in a grid layout with:

  • Status Badge: Color-coded badge indicating system health (green for healthy, yellow for degraded, red for error)
  • Memory Metrics: RSS and VMS in MB, memory percentage
  • Database Status: Connection status with badge
  • AI Provider Status: Provider availability status
  • Service Counts: Total services and healthy services count

Record 40 / 48 // Part VI · Operations

Logging

Logging service and ring buffer · source wiki/logging.md

Nova Coder uses a structured logging system. Every action is logged with a timestamp, level, logger name, source file, and line number. JSON logging is supported for production environments.

Log Format

Text Format

2026-07-09 12:01:00 [INFO] novacoder.kernel - Planner task created (kernel.py:42)

JSON Format

{
  "timestamp": "2026-07-09T12:01:00+00:00",
  "level": "INFO",
  "logger": "novacoder.kernel",
  "message": "Planner task created",
  "source": "kernel.py",
  "line": 42
}

Configuration

logging:
  level: INFO
  format: text
  file_path: ~/.config/novacoder/novacoder.log
  console: true

Set format: json for machine-readable output.

Using the Logger

from novacoder.logging import get_logger

logger = get_logger("novacoder.workspace")
logger.info("Scanning project")
logger.error("Failed to read file", extra={"path": "main.py"})

The extra context is included in JSON log entries.

LoggingService

LoggingService is a kernel service that configures the root logger from the application configuration during boot. It attaches a BufferHandler that writes formatted records into novacoder.logging.buffer._log_buffer so the API and TUI can share a single log stream.

from novacoder.logging.service import LoggingService
from novacoder.config.settings import AppConfig

service = LoggingService(config=AppConfig())
service.initialize()
service.start()

Correlation IDs

Use ContextAdapter to attach correlation IDs to log entries:

logger = get_logger("novacoder.agents", extra={"correlation_id": "abc-123"})

Development Instructions

Adding a New Logger

  1. Use get_logger("novacoder.<module>") to create a logger in your module.
  2. Include extra metadata for events that need structured querying.
  3. Do not print directly to stdout.

Adding a Custom Formatter

  1. Subclass StructuredFormatter in novacoder/logging/logger.py.
  2. Add a new format name to LoggingConfig.
  3. Update configure_logging() to select the formatter based on config.

Testing Logging

Use caplog or attach a temporary handler in tests. The shared buffer can be inspected in tests via novacoder.logging.buffer.get_log_buffer().

def test_logs_info(caplog):
    with caplog.at_level("INFO"):
        logger.info("Started")
    assert "Started" in caplog.text

Best Practices

  • Always use get_logger instead of print.
  • Include structured extra metadata for important events.
  • Use log levels appropriately: DEBUG for detail, INFO for milestones, WARNING for recoverable issues, ERROR for failures.
  • Rotate log files in production deployments.

Record 41 / 48 // Part VI · Operations

Advanced Backup and Disaster Recovery

Backup and restore · source wiki/backup-disaster-recovery.md

Overview

The Advanced Backup and Disaster Recovery System provides comprehensive backup scheduling, verification, multi-backend storage, and disaster recovery planning with automated recovery execution.

Components

AdvancedBackup

The advanced backup manager with comprehensive backup and disaster recovery features.

Location: novacoder/backup/advanced.py

Key Features:

  • Automated Scheduling: Thread-based backup scheduling with configurable intervals
  • Backup Types: Full, incremental, and differential backups
  • Verification: Checksum verification for backup integrity
  • Replication: Multi-target replication for redundancy
  • Recovery: Automated recovery procedures with status tracking
  • Event Callbacks: Subscribe to backup events for custom handling
  • Thread-Safe Operations: All operations are thread-safe for concurrent access

BackupManager

Central manager for all backup and recovery operations.

Location: novacoder/backup/manager.py

Key Features:

  • Orchestrates scheduling, verification, storage, and recovery
  • Backup job management
  • Overall statistics and configuration
  • Maintenance operations (cleanup)

BackupScheduler

Automated backup scheduling.

Location: novacoder/backup/scheduler.py

Key Features:

  • Multiple schedule types (Immediate, Interval, Cron, Daily, Weekly, Monthly)
  • Schedule management (add, remove, update, enable/disable)
  • Due schedule detection
  • Schedule statistics

BackupVerifier

Backup verification and integrity checking.

Location: novacoder/backup/verification.py

Key Features:

  • Checksum calculation (SHA256, MD5, SHA1)
  • Backup verification with expected checksums
  • Verification result tracking
  • Verification statistics
  • Old verification cleanup

BackupStorage

Multi-backend storage management.

Location: novacoder/backup/storage.py

Key Features:

  • Multiple storage backends (Local, S3, Azure, GCS)
  • Storage location management
  • Backup storing and retrieval
  • Backup deletion and listing
  • Storage statistics

RecoveryManager

Disaster recovery planning and execution.

Location: novacoder/backup/recovery.py

Key Features:

  • Recovery plan management
  • Recovery step definition
  • Recovery execution tracking
  • Recovery statistics

API Endpoints

List Backup Jobs

GET /api/backup/jobs

Returns all backup jobs.

Get Backup Statistics

GET /api/backup/statistics

Returns backup system statistics.

Usage Example

Advanced Backup System

from novacoder.backup import AdvancedBackup, BackupType, BackupStatus
from novacoder.backup.advanced import BackupConfig

# Create advanced backup manager
backup = AdvancedBackup()
backup.start()

# Add backup configuration
config = BackupConfig(
    source_path='~/project',
    destination_path='/backup',
    backup_type=BackupType.FULL,
    schedule_interval=3600.0,  # 1 hour
    retention_count=7,
    enable_verification=True,
    enable_replication=True
)
backup.add_backup_config(config)

# Create backup
backup_result = backup.create_backup(config.backup_id)
print(f"Backup status: {backup_result.status}")
print(f"Backup size: {backup_result.size_bytes}")

# Verify backup
verified = backup.recover_backup(backup_result.backup_id)
print(f"Backup verified: {verified}")

# Replicate backup
replicated = backup.create_backup(backup_result.backup_id, '/backup/replica')
print(f"Backup replicated: {replicated}")

# Get backup statistics
stats = backup.get_backup_stats()
print(f"Total backups: {stats['total_backups']}")
print(f"Total size: {stats['total_size_bytes']}")

backup.stop()

Traditional Backup Manager

from novacoder.backup.manager import BackupManager, BackupConfig, BackupJob
from novacoder.backup.scheduler import BackupSchedule, ScheduleType
from novacoder.backup.verification import BackupVerifier
from novacoder.backup.storage import BackupLocation, StorageBackend
from novacoder.backup.recovery import RecoveryPlan, RecoveryStep

# Create manager
config = BackupConfig()
manager = BackupManager(config)

# Create backup schedule
schedule = BackupSchedule(
    name="daily-backup",
    schedule_type=ScheduleType.DAILY,
    schedule_value="02:00"
)
manager.add_backup_schedule(schedule)

# Create backup job
job = BackupJob(
    name="project-backup",
    source_path="~/project",
    schedule_id=schedule.schedule_id,
    retention_days=30
)
manager.create_backup_job(job)

# Execute backup
manager.execute_backup_job(job.job_id)

# Verify backup
verifier = manager.get_verifier()
result = verifier.verify_backup(
    backup_id=job.job_id,
    backup_path=Path("/backup/project_20240119_020000")
)

# Create recovery plan
plan = RecoveryPlan(
    name="disaster-recovery",
    rto=3600.0,  # 1 hour recovery time objective
    rpo=3600.0   # 1 hour recovery point objective
)
plan.add_step(RecoveryStep(name="Restore Database", order=1))
plan.add_step(RecoveryStep(name="Restore Files", order=2))
manager.create_recovery_plan(plan)

Integration

Manager: BackupManager in novacoder/backup/manager.py

The backup and disaster recovery system is integrated into the NovaApplication and accessible via:

  • Direct instantiation of BackupManager
  • API endpoints for backup jobs and statistics
  • Integration with existing storage backends

Schedule Types

Immediate

Execute backup immediately.

Interval

Execute backup at regular intervals (seconds).

Cron

Execute backup using cron expression.

Daily

Execute backup daily at specified time.

Weekly

Execute backup weekly on specified day and time.

Monthly

Execute backup monthly on specified day and time.

Storage Backends

Local Storage

BackupLocation(
    name="local",
    backend=StorageBackend.LOCAL,
    path="/backup"
)

S3 Storage

BackupLocation(
    name="s3",
    backend=StorageBackend.S3,
    path="s3://my-bucket/backups",
    credentials={"access_key": "...", "secret_key": "..."}
)

Azure Storage

BackupLocation(
    name="azure",
    backend=StorageBackend.AZURE,
    path="azure://my-container/backups",
    credentials={"connection_string": "..."}
)

GCS Storage

BackupLocation(
    name="gcs",
    backend=StorageBackend.GCS,
    path="gs://my-bucket/backups",
    credentials={"credentials_path": "..."}
)

Recovery Planning

Recovery Steps

RecoveryStep(
    name="Restore Database",
    description="Restore database from backup",
    order=1,
    required=True,
    estimated_duration=300.0
)

Recovery Objectives

  • RTO (Recovery Time Objective): Maximum acceptable downtime
  • RPO (Recovery Point Objective): Maximum acceptable data loss

Benefits

  • Data Protection: Automated backup scheduling and verification
  • Business Continuity: Disaster recovery planning ensures quick recovery
  • Compliance: Meet data retention requirements
  • Reduced Risk: Multi-backend storage prevents single point of failure
  • Integrity Verification: Checksum verification ensures backup integrity
  • Flexible Storage: Support for multiple storage backends

Configuration

Backup settings can be configured through the application configuration:

{
  "backup": {
    "enable_scheduling": true,
    "enable_verification": true,
    "enable_storage": true,
    "enable_recovery": true,
    "default_retention_days": 30,
    "auto_cleanup": true,
    "backup_directory": "~/.novacoder/backups"
  }
}

See Also

  • Kernel Backup/Recovery - Kernel-level backup features
  • Memory Backup/Recovery - Memory system backup
  • Deployment - Deployment system

Record 42 / 48 // Part VI · Operations

Testing

Test infrastructure · source wiki/testing.md

Nova Coder uses pytest for testing and ruff / black for linting and formatting. Every subsystem should have unit tests, and integration tests should cover the application lifecycle.

Test Suite

Run all tests:

pytest

Run with coverage:

pytest --cov=novacoder --cov-report=term-missing

Note on coverage

The default addopts no longer enables coverage automatically. Coverage is still available by passing --cov=novacoder explicitly. This avoids pytest-cov / coverage.py collector-stack crashes that can occur when threaded services (scheduler, monitoring, async health checks) start and stop during the test lifecycle.

Latest test run

pytest -q -p no:cacheprovider
1787 passed, 1 skipped, 3283 warnings in 546.90s (0:09:06)

All available tests currently pass. The remaining warnings are non-fatal (PytestReturnNotNoneWarning, DeprecationWarning for datetime.utcnow, and StarletteDeprecationWarning).

Project Layout

tests/
├── test_kernel.py        # Container, event bus, registry, application
├── test_kernel_wiring.py # Regression tests for service wiring and health
├── test_config.py        # Configuration loading and validation
├── test_tools.py         # Tool framework and built-in tools
├── test_permissions.py   # Permission model and tool enforcement
├── test_workspace.py     # Scanner, language detection, symbols
├── test_indexing.py      # Incremental indexing and symbol extraction
├── test_agents.py        # Agent framework and manager
├── test_planner.py       # Planning engine
├── test_workflows.py     # Workflow executor
├── test_cli.py           # CLI command regression tests
├── test_api.py           # FastAPI REST endpoints
├── test_app.py           # Integration tests for the full application
├── test_integration.py   # End-to-end agent workflows
├── test_gui.py           # TUI import and MemoryPage behavior
├── test_vector_memory.py # Vector memory embedding and search
├── test_bug_fixes.py     # Regression tests for the 01-bug-fixes roadmap
└── test_security.py      # Security agent and service

Test Examples

Kernel Test

def test_event_bus_publish_and_subscribe():
    bus = EventBus()
    received = []
    bus.subscribe("TestEvent", lambda e: received.append(e.name))
    bus.publish(Event(name="TestEvent"))
    assert len(received) == 1

Tool Test

def test_read_file_tool(tmp_path):
    path = tmp_path / "test.txt"
    path.write_text("hello")
    result = ReadFileTool().run(path=str(path))
    assert result.output == "hello"

Application Integration Test

def test_app_starts_and_stops(app):
    results = app.start()
    assert app.is_running()
    for name, (ok, error) in results.items():
        assert ok, error
    app.stop()
    assert not app.is_running()

Code Quality

Format code:

black novacoder tests

Lint code:

ruff check novacoder tests

Type checking (optional):

mypy novacoder

CI/CD

The GitHub Actions workflow runs on every push and pull request:

name: CI
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
      - run: pip install -e ".[dev]"
      - run: ruff check novacoder tests
      - run: black --check novacoder tests
      - run: pytest --cov=novacoder

Testing Principles

  • Test behavior, not implementation details.
  • Use tmp_path for filesystem tests.
  • Mock external APIs (AI providers, network calls).
  • Keep integration tests fast and deterministic.
  • Never weaken tests without explicit direction.

Coverage Goals

  • Target 80%+ coverage for core kernel modules.
  • Target 70%+ coverage for tools and workspace.
  • Add integration tests for every CLI command.

Development Instructions

Writing a New Test File

  1. Create tests/test_<subsystem>.py.
  2. Import the subsystem classes and pytest fixtures.
  3. Add test functions with descriptive names.
  4. Run pytest tests/test_<subsystem>.py -v to verify.

Using Fixtures

Use built-in fixtures like tmp_path and event_loop:

def test_file_tool(tmp_path):
    path = tmp_path / "test.txt"
    path.write_text("hello")
    assert path.read_text() == "hello"

Mocking External Services

from unittest.mock import AsyncMock

provider = MockProvider()
provider.chat = AsyncMock(return_value="response")

Running a Single Test

pytest tests/test_kernel.py::test_event_bus_publish_and_subscribe -v

Debugging a Failing Test

pytest tests/test_kernel.py -v --pdb

Adding Coverage

pytest --cov=novacoder --cov-report=term-missing

Discovery Notes

During the latest system-wide debug pass, the test suite was expanded to cover the failures and new systems that were found:

  • tests/test_agents.py verifies that AgentManager registers all default agents and that the new agents run successfully.
  • tests/test_cli.py exercises every CLI command (version, models, tools, agents, chat, memory) with Typer's CliRunner.
  • tests/test_api.py covers the FastAPI endpoints, including POST /api/workspace/scan, GET /api/workspace/files, GET /api/memory, and DELETE /api/memory.
  • tests/test_gui.py mounts the MemoryPage and exercises _store/_clear via textual run_test.
  • tests/test_permissions.py was added for the permission model and ToolRegistry enforcement.
  • tests/test_kernel_wiring.py adds regression tests for service wiring and health propagation.
  • tests/test_integration.py covers end-to-end agent workflows.
  • tests/test_bug_fixes.py remains the regression suite for the roadmaps/01-bug-fixes.md bugs.

After the latest implementation pass, tests/test_agents.py passes (28 passed) and novacoder doctor reports all 22 services healthy. The full suite still enforces a 70% coverage threshold; additional tests are being added to reach it.

UI Testing

WebUITester (novacoder/testing/ui.py) performs lightweight HTTP-level page-load and element-interaction checks using httpx when a browser automation tool is not available. It validates response status, body presence, and supported interaction actions.

Mutation Testing

MutationTestRunner._run_test_for_mutation invokes a configured test function (sync or async) before falling back to a probabilistic mutation-kill estimate when source-level AST mutation is not configured.

  • Setup & Contributing
  • Kernel

Record 43 / 48 // Part VII · Extensibility

Advanced Plugin System

Plugin discovery and lifecycle · source wiki/plugin-system.md

Overview

The Advanced Plugin System provides comprehensive plugin management with marketplace distribution, semantic versioning, dependency resolution, and sandboxing for security isolation. It enables community-driven extensions and third-party integrations.

Components

PluginManager

Central manager for all plugin operations.

Location: novacoder/plugins/manager.py

Key Features:

  • Plugin loading and lifecycle management
  • Marketplace integration
  • Version management
  • Sandbox management
  • Overall statistics

PluginMarketplace

Plugin marketplace for distribution and discovery with enhanced capabilities.

Location: novacoder/plugins/marketplace.py

Key Features:

  • Plugin registration and metadata
  • Plugin search and discovery
  • Plugin reviews and ratings
  • Download tracking
  • Plugin status management (Available, Installed, Outdated, Deprecated, Beta)
  • Security scanning with SecurityScanResult class
  • Usage analytics with UsageAnalytics class
  • Monetization support with MonetizationInfo class
  • Trending plugins detection
  • Recommended plugins
  • Checksum verification for plugin integrity

VersionManager

Semantic versioning and dependency management with enhanced capabilities.

Location: novacoder/plugins/versioning.py

Key Features:

  • Semantic version parsing and comparison
  • Version constraint support (==, >, >=, <, <=, !=, ~=, ^)
  • Dependency resolution
  • Version conflict detection
  • Plugin manifest validation
  • Version history tracking with PluginVersionHistory class
  • Migration steps with MigrationStep class
  • Plugin upgrade/downgrade capabilities
  • Plugin rollback capabilities
  • Dependency graph resolution
  • Data persistence for version information

PluginSandbox

Sandboxing for security isolation with enhanced capabilities.

Location: novacoder/plugins/sandboxing.py

Key Features:

  • Multiple isolation types (thread, process)
  • Multiple sandbox levels (None, Basic, Strict, Paranoid)
  • Resource limits (memory, CPU, execution time, file descriptors, network connections, processes, threads)
  • Capability restrictions (network, filesystem, subprocess, import)
  • Security scanning with dangerous pattern detection
  • Audit logging with SandboxAuditLog class
  • Kill switch for emergency termination
  • Import restrictions
  • File access control
  • Network access control
  • Subprocess execution control
  • Violation tracking

SandboxManager

Manager for plugin sandboxes with enhanced capabilities.

Location: novacoder/plugins/sandboxing.py

Key Features:

  • Sandbox creation and management
  • Violation tracking across all plugins
  • Default sandbox level configuration
  • Sandbox statistics
  • Audit log persistence
  • Emergency shutdown with kill_all_sandboxes()
  • Comprehensive statistics reporting

PluginDependencyResolver

Comprehensive dependency resolution system for plugins.

Location: novacoder/plugins/dependencies.py

Key Features:

  • Dependency graph construction and analysis
  • Circular dependency detection
  • Version constraint validation (==, >, >=, <, <=, !=, ~=, ^)
  • Conflict detection and resolution
  • Installation order calculation
  • Support for multiple dependency types (plugin, python, system, novacoder)
  • Dependency status tracking (satisfied, missing, conflict, incompatible, outdated)
  • Transitive dependency analysis

PluginDocumentationGenerator

Automatic documentation generation for plugins.

Location: novacoder/plugins/documentation.py

Key Features:

  • Automatic code parsing and docstring extraction
  • API reference generation
  • Configuration documentation
  • Markdown and JSON output formats
  • Changelog generation
  • Usage examples extraction
  • Installation guide generation
  • Troubleshooting documentation

PluginTestingFramework

Comprehensive testing and validation framework for plugins.

Location: novacoder/plugins/testing.py

Key Features:

  • Code quality validation (syntax, code smells, PEP 8 compliance)
  • Security scanning (dangerous patterns, hardcoded secrets)
  • Performance validation (anti-patterns detection)
  • Documentation completeness validation
  • Compatibility validation (version constraints)
  • Overall scoring and reporting
  • Multiple validation categories with pass/fail status

Usage Example

Using the Plugin System

from novacoder.plugins import PluginManager, PluginMarketplace, PluginSandbox, ResourceLimits, VersionManager
from novacoder.plugins.marketplace import PluginMetadata, PluginStatus
from novacoder.plugins.versioning import Dependency, Version
from novacoder.plugins.sandboxing import SandboxLevel

# Create manager
config = PluginConfig()
manager = PluginManager(config)

# Register plugin in marketplace
metadata = PluginMetadata(
    plugin_id="my-plugin",
    name="My Plugin",
    version="1.0.0",
    description="A useful plugin",
    author="Developer",
    status=PluginStatus.AVAILABLE,
    dependencies=[Dependency(name="base-plugin", version_constraint=">=1.0.0")]
)
manager.register_plugin_in_marketplace(metadata)

# Create sandbox for plugin
limits = ResourceLimits(
    max_memory_mb=256,
    max_cpu_percent=25.0,
    max_execution_time=10.0,
    max_file_descriptors=100,
    max_network_connections=10,
    max_processes=5,
    max_threads=10,
    allow_network=True,
    allow_filesystem=True,
    allow_subprocess=False
)
sandbox = manager.create_plugin_sandbox("my-plugin", SandboxLevel.STRICT, limits)

# Set isolation type
sandbox.set_isolation_type("process")

# Execute function in sandbox
result = sandbox.execute_function(lambda: "Hello, World!")

# Security scan
scan_result = sandbox.security_scan("def dangerous(): exec('rm -rf /')")
print(f"Vulnerabilities found: {len(scan_result.vulnerabilities)}")

# Get audit logs
logs = sandbox.get_audit_logs()
for log in logs:
    print(f"{log.operation}: {log.message}")

# Kill switch
if sandbox.is_killed():
    print("Sandbox was terminated")
else:
    sandbox.kill()

# Use version manager
version_manager = VersionManager()
version = Version(major=1, minor=0, patch=0)
print(f"Version: {version}")

# Parse version string
parsed = Version.parse("1.2.3")
print(f"Parsed: {parsed}")

# Register plugin with version history
version_manager.unregister_plugin("my-plugin", "1.0.0")

# Upgrade plugin
version_manager.upgrade_plugin("my-plugin", "2.0.0")

# Rollback plugin
version_manager.rollback_plugin("my-plugin", "1.0.0")

# Add migration step
version_manager.add_migration_step("my-plugin", "1.0.0", "2.0.0", "Migrate data")

# Use marketplace with enhanced features
marketplace = PluginMarketplace()

# Security scan plugin
scan_result = marketplace.get_security_scan("my-plugin")
print(f"Security score: {scan_result.security_score}")

# Track usage
marketplace.track_uninstall("my-plugin")
marketplace.track_usage("my-plugin", 3600)  # 1 hour usage

# Get trending plugins
trending = marketplace.get_trending_plugins(limit=10)

# Get recommended plugins
recommended = marketplace.get_recommended_plugins(user_profile="developer")

# Verify checksum
valid = marketplace.verify_plugin_checksum("my-plugin", "sha256:abc123...")

# Use dependency resolver
from novacoder.plugins.dependencies import PluginDependencyResolver, Dependency, DependencyType

resolver = PluginDependencyResolver()

# Register available plugins
resolver.register_available_plugin("base-plugin", "1.0.0")
resolver.register_available_plugin("my-plugin", "1.0.0")

# Register installed plugins
resolver.register_installed_plugin("base-plugin", "1.0.0")

# Analyze dependencies
dependencies = [
    Dependency(name="base-plugin", type=DependencyType.PLUGIN, version_constraint=">=1.0.0")
]
analysis = resolver.analyze_dependencies("my-plugin", dependencies)

# Resolve dependencies
resolution = resolver.resolve_dependencies("my-plugin", dependencies)
print(f"Installation order: {resolution.installation_order}")

# Detect circular dependencies
plugins = [("plugin-a", ["plugin-b"]), ("plugin-b", ["plugin-c"]), ("plugin-c", ["plugin-a"])]
cycles = resolver.detect_circular_dependencies(plugins)
print(f"Circular dependencies: {cycles}")

# Use documentation generator
from novacoder.plugins.documentation import PluginDocumentationGenerator, DocumentationFormat

doc_generator = PluginDocumentationGenerator()

# Generate documentation
doc = await doc_generator.generate_documentation(plugin)

# Publish as Markdown
await doc_generator.publish_documentation(doc, Path("/tmp/my_plugin_docs.md"), DocumentationFormat.MARKDOWN)

# Publish as JSON
await doc_generator.publish_documentation(doc, Path("/tmp/my_plugin_docs.json"), DocumentationFormat.JSON)

# Use testing framework
from novacoder.plugins.testing import PluginTestingFramework

testing_framework = PluginTestingFramework()

# Test plugin
test_report = await testing_framework.test_plugin(plugin)
print(f"Overall score: {test_report.overall_score}")
print(f"Passed: {test_report.passed}")

# Validate plugin
validation = await testing_framework.validate_plugin(plugin)
print(f"Validation passed: {validation['passed']}")
print(f"Code quality score: {validation['validations']['code_quality']['score']}")
print(f"Security score: {validation['validations']['security']['score']}")

Using Individual Components

from novacoder.plugins import PluginMarketplace, PluginMetadata, PluginStatus

# Create marketplace
marketplace = PluginMarketplace()

# Register plugin
metadata = PluginMetadata(
    plugin_id="test-plugin",
    name="Test Plugin",
    version="1.0.0",
    description="Test plugin",
    author="Test Author",
    status=PluginStatus.AVAILABLE
)
marketplace.register_plugin(metadata)

# Search plugins
results = marketplace.search_plugins("test")
print(f"Found {len(results)} plugins")

# Get plugin metadata
plugin = marketplace.get_plugin("test-plugin")
print(f"Plugin: {plugin.name} v{plugin.version}")

Integration

Service: Existing PluginService in novacoder/plugins/service.py

The plugin system is integrated into the NovaApplication with enhanced capabilities:

  • Marketplace distribution via PluginMarketplace
  • Version management via VersionManager
  • Sandboxing via SandboxManager
  • API endpoints for plugin management

Version Constraints

Exact Version

Dependency(name="base-plugin", version_constraint="==1.0.0")

Minimum Version

Dependency(name="base-plugin", version_constraint=">=1.0.0")

Compatible Release

Dependency(name="base-plugin", version_constraint="~=1.2.0")

Caret Version

Dependency(name="base-plugin", version_constraint="^1.0.0")

Sandbox Levels

None

No isolation - full system access.

Basic

Basic import restrictions and resource monitoring.

Strict

Full isolation with resource limits and access controls.

Paranoid

Maximum isolation with strict security policies.

Resource Limits

ResourceLimits(
    max_memory_mb=512,
    max_cpu_percent=50.0,
    max_execution_time=30.0,
    max_file_descriptors=100,
    max_network_connections=10,
    max_processes=5,
    max_threads=10,
    allow_network=True,
    allow_filesystem=True,
    allow_subprocess=False,
    allowed_modules=["json", "os"],
    blocked_modules=["subprocess", "socket"]
)

Security Scanning

The sandbox performs static code analysis to detect dangerous patterns:

  • Dangerous Functions: eval, exec, os.system, subprocess, socket, pickle, marshal, compile
  • File Write Operations: Writes to sensitive paths
  • Hardcoded Secrets: Passwords, API keys, tokens
scan_result = sandbox.security_scan(code)
for vuln in scan_result.vulnerabilities:
    print(f"Type: {vuln.type}, Line: {vuln.line}, Message: {vuln.message}")

Audit Logging

All sandbox operations are logged for security and compliance:

logs = sandbox.get_audit_logs()
for log in logs:
    print(f"{log.timestamp}: {log.operation} - {log.message}")

# Filter logs by operation
filtered = sandbox.get_audit_logs_filtered(operation="execute_function")

Benefits

  • Community Extensions: Enable community-driven plugin development
  • Easy Customization: Customize Nova Coder without core changes
  • Third-Party Integrations: Integrate external tools and services
  • Security Isolation: Sandboxing prevents malicious plugins
  • Version Management: Semantic versioning with dependency resolution
  • Marketplace: Centralized plugin discovery and distribution

Configuration

Plugin settings can be configured through the application configuration:

{
  "plugins": {
    "enable_marketplace": true,
    "enable_versioning": true,
    "enable_sandboxing": true,
    "default_sandbox_level": "basic",
    "auto_update": false,
    "plugin_directory": "~/.novacoder/plugins"
  }
}

Web UI Exposure

The React Plugins page (/plugins) exposes the plugin command endpoints directly:

  • Execute Plugin Command - A form that calls POST /api/plugins/commands/{name}/execute with the selected command and a JSON args object. Results are rendered as JSON.
  • Plugin Results - A dropdown that calls GET /api/plugins/results/{plugin_name} and shows the last execution result for the selected plugin.
  • Sandbox Configuration - A form that calls POST /api/plugins/sandbox to update isolation settings.

Backend fixes

During integration, novacoder/api/routes_plugins.py and several other route modules were updated to import novacoder.api._state instead of the non-existent novacoder.api._routes. Plugin command execution now returns 404 for unknown commands instead of 500.

See Also

  • Plugins - Basic plugin system
  • Plugin Wiring - Plugin integration
  • Kernel Plugin Enhancements - Kernel-level plugin features
  • Agent Marketplace - Agent marketplace

Record 44 / 48 // Part VII · Extensibility

Plugin Authoring, extension points

Writing a plugin · source wiki/plugin-authoring.md

Three supported ways to extend Nova Coder (per reports/Plugin and Extension SDK.md). Pick by where the behavior lives.

1. Route module (new HTTP surface)

# novacoder/api/routes_mysurface.py
from fastapi import APIRouter
router = APIRouter()

@router.get("/api/mysurface/hello")
async def hello() -> dict:
    return {"ok": True}
  • Register the module name in _ROUTE_MODULE_NAMES (novacoder/api/app.py), unregistered modules 404 silently.
  • /api/* paths are token-gated automatically; anything outside /api must be added to non_api_protected or is public (scanner-enforced).
  • Route handlers returning FileResponse|JSONResponse need response_model=None.

2. Kernel service (lifecycle + DI)

from novacoder.kernel.service import NovaService

class MyService(NovaService):
    name = "myservice"
    def initialize(self) -> None: ...
    def start(self) -> None: ...       # must not run async work
    def stop(self) -> None: ...
  • Register in SERVICE_ORDER (app.py); resolve deps via container.
  • start() runs inside synchronous _boot(), async health checks at boot deadlock the API (ADR-002).
  • Heavy work belongs on the scheduler, not in initialize().

3. Capability (model-facing tool)

from novacoder.capabilities.base import Capability
from novacoder.capabilities.descriptor import CapabilityDescriptor, CapabilityResult

class MyCap(Capability):
    descriptor = CapabilityDescriptor(
        id="mine.thing", name="My Thing", description="…",
        keywords=["do my thing"],            # feeds the IntentRouter
        requires_approval=True,              # if it mutates
    )
    async def run(self, args, ctx) -> CapabilityResult: ...
  • Register in builtins/__init__.py::register_builtins (or adopt a legacy tool).
  • Honor the gates: SSRF for egress, path confinement for filesystem, device ops surface for host actions, never raw fs/subprocess.
  • Missing backends must report unavailable, not crash.

Record 45 / 48 // Part VII · Extensibility

Plugins

Plugin subsystem overview · source wiki/plugins.md

The plugin system lets third-party developers extend Nova Coder without modifying the core. Plugins can contribute agents, tools, AI providers, language parsers, workflows, and CLI commands. Custom kernel services remain a future extension point.

Plugin Interface

A plugin implements Plugin:

from novacoder.plugins.plugin import Plugin
from novacoder.tools.tool import Tool
from novacoder.agents.agent import Agent

class MyPlugin(Plugin):
    name = "my_plugin"
    version = "0.1.0"
    description = "Does something useful."

    def initialize(self, memory=None, config=None, workspace=None) -> None:
        super().initialize(memory, config, workspace)

    def shutdown(self) -> None:
        pass

    def register_tools(self) -> list[Tool]:
        return [MyTool()]

    def register_agents(self) -> list[Agent]:
        return [MyAgent()]

    def register_providers(self) -> list[type[AIProvider]]:
        return [MyProvider]

    def register_extractors(self) -> dict[str, type[LanguageExtractor]]:
        return {"my-lang": MyExtractor}

    def register_workflows(self) -> list[Plan]:
        return [my_plan]

    def register_commands(self) -> list[dict[str, Any]]:
        return [
            {"name": "hello", "func": lambda: print("Hello from plugin"), "help": "Say hello"}
        ]

PluginService

PluginService loads and manages plugins and registers all contributions:

from novacoder.plugins.service import PluginService
from novacoder.config.settings import AppConfig

service = PluginService(config=AppConfig())
service.register(MyPlugin())
service.start()

print(service.list_plugins())

Plugin Discovery

Plugins are discovered automatically from two sources:

Entry Points

Installable packages declare a novacoder.plugins entry point in their pyproject.toml:

[project.entry-points."novacoder.plugins"]
my_plugin = "my_package.plugin:MyPlugin"

Plugins Directory

Set plugins.plugins_dir in the configuration to a directory that contains plugin.py files:

plugins:
  plugins_dir: ~/.config/novacoder/plugins
~/.config/novacoder/plugins/
└── my_plugin/
    └── plugin.py

CLI

List active plugins and their contributions:

novacoder plugins

Run from a specific project directory:

novacoder --project /path/to/project plugins

See Plugin System Wiring and Integration for integration details and verification commands.

Extension Points

Wired extension points:

  • Agents, specialist agents
  • Tools, filesystem, network, cloud, or hardware tools
  • Workspace, plugins receive the workspace service via initialize()
  • AI Providers, custom model endpoints via register_providers()
  • Language Parsers, custom symbol extractors via register_extractors()
  • Workflows, YAML-defined agent pipelines via register_workflows()
  • Commands, CLI commands via register_commands()

Future extension points (not yet wired):

  • Services, custom kernel services

Configuration

plugins:
  enabled: true
  plugins_dir: null

plugins_dir can also be set via the environment variable NOVACODER_PLUGINS__PLUGINS_DIR:

export NOVACODER_PLUGINS__PLUGINS_DIR=/path/to/plugins

Plugin settings can be stored in persistent memory:

self._memory.remember("my_plugin.api_key", api_key, scope=MemoryScope.PERSISTENT)

Lifecycle Events

PluginService publishes the following events to the EventBus:

  • PluginDiscovered
  • PluginLoaded
  • PluginStarted
  • PluginFailed
  • PluginStopped

Security

Plugins run with the same permissions as the Nova Coder process. Enhanced sandboxing is now available through the PluginSandbox system with multiple isolation levels (None, Basic, Strict, Paranoid), resource limits, and security scanning. See Advanced Plugin System for details on sandboxing capabilities.

Development Instructions

Creating a Plugin

  1. Create a module in novacoder/plugins/ or an external package.
  2. Implement the Plugin interface.
  3. Override register_tools() and/or register_agents() to contribute capabilities.
  4. Accept workspace in initialize() if your plugin needs project context.
  5. Register the plugin manually or via entry points.
  6. Add tests in tests/test_plugins.py.
  7. Document the plugin in this wiki page.

Plugin Lifecycle

PluginService.initialize() discovers plugins during kernel boot. PluginService.start() calls plugin.initialize() on every registered plugin and wires its tools and agents into ToolService and AgentService. PluginService.stop() calls plugin.shutdown() in reverse order. Failures in one plugin are isolated and do not stop the others.

Testing Plugins

def test_plugin_registers_tool():
    plugin = MyPlugin()
    tools = plugin.register_tools()
    assert len(tools) == 1
    assert tools[0].name == "my_tool"

Example Plugin

See examples/plugins/hello_plugin/ for a complete working plugin with pyproject.toml, a tool, an agent, and tests.

Best Practices

  • Keep plugins focused on one domain.
  • Declare all tools and agents explicitly.
  • Clean up resources in shutdown().
  • Provide clear documentation and examples.

REST API

Endpoint Description
GET /api/plugins Loaded plugins (includes enabled flag)
GET /api/plugins/components Contributed components
GET /api/plugins/commands Plugin commands
POST /api/plugins/commands/{name}/execute Execute a command (blocked when the owning plugin is disabled)
POST /api/plugins/{name}/enable / disable Per-plugin toggle, persisted to ~/.config/novacoder/plugin_state.json; disabled plugins are skipped at startup and cannot execute
GET /api/plugins/marketplace/list?q=&tag=&author=&status= Marketplace registry browse/search
GET /api/plugins/marketplace/{plugin_id} Plugin metadata + reviews + dependencies
GET /api/plugins/marketplace/stats Registry statistics
POST /api/plugins/marketplace/register Publish plugin metadata
POST /api/plugins/marketplace/{plugin_id}/review Add a 1-5 star review

The marketplace registry (~/.novacoder/plugin_registry.json) is metadata-only: PluginMetadata, PluginReview, ratings, download counts. Package signing/verification and binary install are internal.

IDE Extensions View

The React IDE (/ide) has an Extensions sidebar view (puzzle icon in the activity bar) implemented in web/react/src/components/ide/ExtensionsPanel.tsx:

  • Installed section lists GET /api/plugins with name, version, description, contribution counts (tools/agents/commands) and an enable/disable button wired to POST /api/plugins/{name}/enable|disable.
  • Marketplace section searches GET /api/plugins/marketplace/list?q= and renders PluginMetadata (author, version, tags, rating, downloads, status). Entries matching a loaded plugin (by name/plugin_id) are excluded from the marketplace list and shown under Installed instead.
  • The marketplace is a metadata registry only, there is no package download/install endpoint, so uninstalled entries are labeled "registry" rather than offering an Install action. Installing a plugin means placing it on disk under the plugins directory; enable/disable applies to loaded plugins.

Record 46 / 48 // Part VIII · Interfaces

CLI

86 Typer commands mirroring the API · source wiki/cli.md

The Nova Coder CLI is built with Typer and provides commands for interacting with the application, inspecting health, scanning projects, and running agents.

Running the CLI

novacoder --help
python -m novacoder --help

Commands

Command Description
version Show Nova Coder version
doctor Check health of all services
config show Display loaded configuration
config validate Validate the loaded configuration
config backup Back up the current configuration to a JSON file
config restore --file <path> Restore configuration from a .json, .yaml, or .yml file
config diff --file <path> Diff the current configuration against a .json, .yaml, or .yml file
config migrate Run pending configuration schema migrations
scan <path> Scan a project directory
models List available AI providers and models
tools List registered tools (includes linter, package manager, HTTP request)
agents List registered agents (includes security by default)
plan <goal> Generate a structured plan using the Planner agent
plugins List registered plugins and their contributions
run <goal> Execute a goal through the agent pipeline
chat <message> Send a message through the planner agent
stream <message> Stream AI tokens from the configured provider
interactive Start an interactive REPL session
memory Manage session/working/project memory
serve Start the REST API and web dashboard server
gui Launch the terminal UI (TUI)
deployment build-wheel Build a wheel distribution
deployment build-docker Build a Docker image
deployment status Check build status
deployment artifacts List build artifacts

Examples

Check Health

novacoder doctor

Output:

┌───────────┬────────┬─────────┐
│ Service   │ Status │ Message │
├───────────┼────────┼─────────┤
│ config    │ ✓      │         │
│ logging   │ ✓      │         │
│ workspace │ ✓      │         │
│ ai        │ ✓      │         │
│ tools     │ ✓      │         │
│ agents    │ ✓      │         │
└───────────┴────────┴─────────┘
Overall: healthy - All 8 services are healthy.

Scan a Project

novacoder scan /path/to/project

Chat with the Planner

novacoder chat "Build a Flask API"

This produces a structured plan with tasks and dependencies.

Stream AI Tokens

novacoder stream "Explain Python decorators" --provider mock

Output is written to stdout as each token is received from the provider.

List Tools

novacoder tools

Build Wheel Distribution

novacoder deployment build-wheel

Build Docker Image

novacoder deployment build-docker --image novacoder:latest

Check Build Status

novacoder deployment status

List Build Artifacts

novacoder deployment artifacts

Project Path Option

Most commands accept a --project option. When provided, it is used as the working directory for the command. If a command accepts a positional path, the --project flag is used as the default:

novacoder --project /path/to/project scan

Start the REST API Server

novacoder serve

With a custom port and token:

NOVACODER_API__TOKEN=secret novacoder serve --port 8080

CLI Execute API

POST /api/cli/execute runs commands in a sandboxed subprocess (run_shell_commands permission enforced). GET /api/cli/commands lists all invocable commands including Typer sub-app groups:

  • Groups (plugin, security, workflow, deployment, cicd, distributed, infrastructure, workspace, code, memory-advanced, agents-advanced, system) are listed with is_group: true.
  • Sub-commands appear as group sub entries (e.g. workspace merge, system restore) and may be executed either as {"command": "workspace merge"} or {"command": "workspace", "args": ["merge", ...]}.
  • Timeout: 30 seconds; stderr from unknown commands is returned verbatim.

CLI Helper

The internal _get_app() helper in novacoder/cli/main.py creates and starts a NovaApplication. It supports:

  • minimal=True, passes through to create_app() to disable workspace.index_on_start for quick metadata commands.
  • overrides=dict, passes arbitrary config overrides through to create_app().

create_app() now accepts a minimal flag directly, which sets workspace.index_on_start = False in the overrides. Every CLI command uses nova_app = None and a try/finally block so _get_app() failures still clean up resources.

Adding Commands

Commands are defined in novacoder/cli/main.py using Typer decorators:

@app.command()
def my_command(name: str) -> None:
    """Description."""
    console.print(f"Hello {name}")

CLI Architecture

The CLI is the primary user interface for v0.1.0. It creates a NovaApplication, starts it, resolves services from the container, runs the command, and then stops the application cleanly.

from novacoder.app import create_app

app = create_app()
app.start()
# run command...
app.stop()

Development Instructions

Adding a New CLI Command

  1. Add a new function in novacoder/cli/main.py decorated with @app.command().
  2. Use create_app() and app.start() to access services, then app.stop() to clean up.
  3. Resolve services from the container by class name for type safety.
  4. Add a test in tests/ that invokes the Typer command using CliRunner.

Example Command

@app.command()
def stats() -> None:
    """Show project statistics."""
    app = _get_app()
    try:
        workspace = app.container.resolve(WorkspaceService)
        summary = workspace.summary()
        console.print(summary)
    finally:
        app.stop()

Testing Commands

from typer.testing import CliRunner
from novacoder.cli.main import app

runner = CliRunner()
result = runner.invoke(app, ["version"])
assert result.exit_code == 0
assert "Nova Coder" in result.output

CLI Style Guidelines

  • Use rich for tables, panels, and JSON output.
  • Keep command descriptions short and clear.
  • Accept Path objects for filesystem paths.
  • Always shut down the application in a finally block.

Discovery Notes

During the latest system-wide debug pass, the models command failed with TypeError: can only join an iterable and a RuntimeWarning: coroutine 'OllamaProvider.available_models' was never awaited. The provider method available_models() is async, but the CLI was calling it synchronously.

Fix: novacoder/cli/main.py now defines a _run_async() helper that detects whether an event loop is already running and uses asyncio.run() or a thread-pool executor as needed:

models_list = _run_async(provider.available_models())

The global --project flag is now stored in the CLI state and respected by commands that accept a path. Error output is routed to stderr via err_console, and every command wraps service startup in try/finally to stop NovaApplication on failure.

A full suite of CLI regression tests was added in tests/test_cli.py using Typer's CliRunner. The covered commands include version, models, tools, agents, chat, plan, and gui.

The serve command starts the FastAPI/uvicorn server. The REST API and dashboard are documented in REST API.

Record 47 / 48 // Part VIII · Interfaces

Web Interface Terminal

Browser PTY terminal · source wiki/web-interface-terminal.md

Architecture note (2026-11): The command-execution terminal described below (bash/python/node selector, working-directory input, 50-command history) belonged to the removed vanilla-JS UI. The current implementation is a real PTY terminal: xterm.js in novacoder/web/react/src/components/ide/TerminalPanel.tsx attached to the /ws/terminal WebSocket on the /ide page. Feature specifics below are historical.

Overview

The Nova Coder web interface includes a web-based terminal for command execution, allowing users to run shell commands directly from the browser without needing a separate terminal application.

Features

Shell Support

  • Bash - Standard bash shell commands
  • Python - Python REPL execution
  • Node.js - Node.js JavaScript execution

Command Execution

  • Working Directory - Specify the working directory for command execution
  • Command History - Tracks up to 50 executed commands
  • Exit Code Tracking - Displays exit codes for each command
  • Output Display - Shows command output and error messages
  • Timestamp - Records when each command was executed

Output Management

  • Clear Terminal - Clear all command history
  • Download Output - Download terminal output as a text file
  • Color-Coded Results - Green for success, red for failure

Usage

Accessing the Terminal

  1. Navigate to the web interface
  2. Click "Terminal" in the sidebar navigation
  3. Enter the working directory (default is current directory .)
  4. Select the shell type (Bash, Python, Node.js)
  5. Click "Execute" to run the command

Running Commands

  1. Enter the command in the working directory field
  2. Select the appropriate shell
  3. Click "Execute"
  4. View the output in the terminal display area
  5. Exit code indicates success (0) or failure (non-zero)

Managing Terminal History

  • Clear - Click "Clear" to remove all command history
  • Download - Click "Download" to save terminal output as a text file

API Integration

Executing Commands

POST /api/terminal/execute
Content-Type: application/json

{
  "command": "ls -la",
  "cwd": ".",
  "shell": "bash"
}

Authentication: Requires session token via cookie or x-api-token header Rate Limiting: Not configured (low-volume command execution) CSRF Protection: Required for POST requests

Response:

{
  "success": true,
  "data": {
    "output": "file1.txt\nfile2.py",
    "error": "",
    "exit_code": 0
  }
}

Error Response:

{
  "success": false,
  "error": "Command timed out"
}

Shell Types:

  • bash - Standard bash shell commands
  • python - Python REPL execution (uses python3)
  • node - Node.js JavaScript execution

Timeout: Commands have a 30-second timeout to prevent hanging.

Security Features:

  • Command execution with timeout protection
  • Working directory isolation
  • Process isolation via subprocess
  • Error handling for failed commands
  • No direct shell access (uses subprocess)

Testing & Verification

Test Bash Command Execution

# First authenticate
curl -X POST http://localhost:8000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"token":"your_api_token"}' \
  -c /tmp/cookies.txt

# Then test the endpoint
curl -X POST http://localhost:8000/api/terminal/execute \
  -H "Content-Type: application/json" \
  -b /tmp/cookies.txt \
  -d '{"command":"echo hello","cwd":"/path/to/novacoder","shell":"bash"}'

Test Python Command Execution

curl -X POST http://localhost:8000/api/terminal/execute \
  -H "Content-Type: application/json" \
  -b /tmp/cookies.txt \
  -d '{"command":"print(\"hello\")","cwd":"/path/to/novacoder","shell":"python"}'

Test Node.js Command Execution

curl -X POST http://localhost:8000/api/terminal/execute \
  -H "Content-Type: application/json" \
  -b /tmp/cookies.txt \
  -d '{"command":"console.log(\"hello\")","cwd":"/path/to/novacoder","shell":"node"}'

Test Results: All endpoints tested successfully with bash, python, and node. Working directory changes work correctly, output capture and return functioning properly, error handling for invalid commands working, timeout protection prevents long-running commands, and no conflicts with existing systems.

Command History

The terminal maintains a history of executed commands:

  • Maximum of 50 commands stored
  • Each entry includes:
    • Command text
    • Shell type
    • Output
    • Error messages
    • Exit code
    • Timestamp

Shell Types

Bash

Standard bash shell for executing Unix/Linux commands:

ls -la
pwd
cat file.txt

Python

Python REPL for executing Python code:

print("Hello, World!")
import os
os.listdir('.')

Node.js

Node.js for executing JavaScript code:

console.log("Hello, World!");
const fs = require('fs');
fs.readdirSync('.');

Output Format

Each command execution is displayed with:

[bash] ls -la
2026-07-20T15:30:00.000Z
file1.txt
file2.py
Exit code: 0

Error output is displayed in red:

[bash] invalid_command
2026-07-20T15:31:00.000Z
Error: command not found
Exit code: 127

Technical Details

JavaScript Functions

renderTerminal()

Renders the terminal UI with shell selection and command input.

executeTerminalCommand()

Executes a command via the API and displays the result.

renderTerminalHistory()

Renders the command history in the terminal display area.

clearTerminal()

Clears all command history from the terminal.

downloadTerminalOutput()

Downloads the terminal output as a text file.

Limitations

  • No interactive commands (e.g., vim, nano)
  • No command completion or history navigation
  • No file upload/download via terminal
  • No background process support
  • No terminal session persistence

Future Enhancements

  • Add interactive command support using xterm.js
  • Implement command history navigation (up/down arrows)
  • Add tab completion for commands
  • Support for background processes
  • Implement terminal session persistence
  • Add multiple terminal tabs
  • Support for SSH connections
  • Add command aliases
  • Implement command scheduling

Record 48 / 48 // Part VIII · Interfaces

WebSocket Client Library

WS client contract · source wiki/web-interface-websocket-client.md

Architecture note (2026-11): novacoder/web/static/js/websocket-client.js (WebSocketManager) has been removed. In the React SPA, realtime updates use novacoder/web/react/src/hooks/useEventStream.ts, a reconnecting WebSocket hook over the /ws/{channel} channels (/ws/chat, /ws/agents, /ws/workspace, /ws/system) with optional novacoder-token.* subprotocol auth; the interactive terminal uses a direct WebSocket to /ws/terminal in components/ide/TerminalPanel.tsx. The WebSocketManager API documented below no longer exists.

The Nova Coder web interface includes a comprehensive WebSocket client library for real-time communication with the server. The library provides automatic reconnection, message handling, room management, and channel-specific clients for different use cases.

Overview

The WebSocket client library is implemented in novacoder/web/static/js/websocket-client.js and provides:

  • Base WebSocketClient: Core client with automatic reconnection
  • Channel-specific clients: Pre-configured clients for different channels
  • Message handlers: Register handlers for specific message types
  • Room management: Join/leave rooms, send messages to rooms
  • Connection state tracking: Monitor connection status
  • Global WebSocketManager: Manage multiple connections

Usage

The WebSocket client library is loaded in index.html before app.js and is available globally as WebSocketManager:

// Get a client for a specific channel
const chatClient = WebSocketManager.getClient('chat');

// Use the client
chatClient.connect();
chatClient.send({ type: 'message', content: 'Hello' });

Base WebSocketClient

Constructor

const client = new WebSocketClient();

Properties

  • ws (WebSocket): The underlying WebSocket connection
  • connectionId (string): Unique connection ID assigned by server
  • channel (string): Current channel
  • reconnectAttempts (number): Number of reconnection attempts
  • maxReconnectAttempts (number): Maximum reconnection attempts (default: 5)
  • reconnectDelay (number): Reconnection delay in ms (default: 1000)
  • messageHandlers (object): Registered message handlers
  • connectionState (string): Current connection state
  • userId (string): Generated user ID

Methods

connect()

Connect to a WebSocket channel:

client.connect(channel, options)

Parameters:

  • channel (string): Channel to connect to (default: default)
  • options (object): Connection options

Example:

client.connect('chat');

disconnect()

Disconnect from the server:

client.disconnect()

Example:

client.disconnect();

send()

Send a message to the server:

client.send(message)

Parameters:

  • message (object): Message to send

Example:

client.send({ type: 'message', content: 'Hello' });

on()

Register a message handler:

client.on(messageType, handler)

Parameters:

  • messageType (string): Message type to handle
  • handler (function): Handler function

Example:

client.on('connected', (data) => {
    console.log('Connected:', data);
});

off()

Remove a message handler:

client.off(messageType, handler)

Parameters:

  • messageType (string): Message type
  • handler (function): Handler function to remove

Example:

client.off('connected', handler);

getState()

Get current connection state:

const state = client.getState()

Returns: Connection state string (disconnected, connecting, connected, error)

isConnected()

Check if connected:

const connected = client.isConnected()

Returns: Boolean

joinRoom()

Join a collaboration room:

client.joinRoom(roomId)

Parameters:

  • roomId (string): Room ID to join

Example:

client.joinRoom('session_123');

leaveRoom()

Leave a collaboration room:

client.leaveRoom(roomId)

Parameters:

  • roomId (string): Room ID to leave

Example:

client.leaveRoom('session_123');

sendToRoom()

Send a message to a room:

client.sendToRoom(roomId, message)

Parameters:

  • roomId (string): Room ID
  • message (object): Message content

Example:

client.sendToRoom('session_123', { type: 'update', data: {...} });

Channel-Specific Clients

ChatWebSocketClient

Client for chat streaming:

const chatClient = new ChatWebSocketClient();

Methods:

  • sendMessage(content): Send a chat message

Example:

const chatClient = new ChatWebSocketClient();
chatClient.sendMessage('Hello, world!');

AgentWebSocketClient

Client for agent updates:

const agentClient = new AgentWebSocketClient();

Methods:

  • subscribeToAgent(agentId): Subscribe to agent updates
  • unsubscribeFromAgent(agentId): Unsubscribe from agent updates

Example:

const agentClient = new AgentWebSocketClient();
agentClient.subscribeToAgent('coder');

WorkspaceWebSocketClient

Client for workspace updates:

const workspaceClient = new WorkspaceWebSocketClient();

Methods:

  • subscribeToPath(path): Subscribe to path updates

Example:

const workspaceClient = new WorkspaceWebSocketClient();
workspaceClient.subscribeToPath('/src');

SystemWebSocketClient

Client for system monitoring:

const systemClient = new SystemWebSocketClient();

CollaborationWebSocketClient

Client for collaboration features:

const collabClient = new CollaborationWebSocketClient();

Methods:

  • joinSession(sessionId): Join a collaboration session
  • leaveSession(sessionId): Leave a collaboration session
  • sendCursorUpdate(sessionId, position): Send cursor position
  • sendEdit(sessionId, edit): Send edit operation

Example:

const collabClient = new CollaborationWebSocketClient();
collabClient.joinSession('session_123');
collabClient.sendCursorUpdate('session_123', { line: 10, column: 5 });
collabClient.sendEdit('session_123', {
    type: 'text',
    range: { start: 0, end: 10 },
    text: 'replacement'
});

DashboardWebSocketClient

Client for dashboard updates:

const dashboardClient = new DashboardWebSocketClient();

NotificationWebSocketClient

Client for notifications:

const notificationClient = new NotificationWebSocketClient();

Global WebSocketManager

The global WebSocketManager manages multiple WebSocket connections:

getClient()

Get or create a client for a channel:

const client = WebSocketManager.getClient(channel)

Parameters:

  • channel (string): Channel name

Returns: WebSocket client instance

Example:

const chatClient = WebSocketManager.getClient('chat');
const agentClient = WebSocketManager.getClient('agents');

disconnectAll()

Disconnect all clients:

WebSocketManager.disconnectAll()

Example:

WebSocketManager.disconnectAll();

getStatus()

Get connection status for all channels:

const status = WebSocketManager.getStatus()

Returns: Object with channel names and connection states

Example:

const status = WebSocketManager.getStatus();
// Returns: { chat: 'connected', agents: 'disconnected', ... }

Message Handling

Built-in Message Types

The client automatically handles these message types:

  • connected: Connection established
  • disconnected: Connection closed
  • error: Connection error
  • message: Generic message

Custom Message Handlers

Register handlers for custom message types:

client.on('custom_type', (message) => {
    console.log('Custom message:', message);
});

Message Format

Messages from the server include:

{
    "type": "message_type",
    "content": "message content",
    "timestamp": "2024-01-01T00:00:00Z"
}

Connection Events

connected

Fired when connection is established:

client.on('connected', (data) => {
    console.log('Connected:', data.connectionId);
    console.log('Channel:', data.channel);
});

disconnected

Fired when connection is closed:

client.on('disconnected', (data) => {
    console.log('Disconnected:', data.code, data.reason);
});

error

Fired when connection error occurs:

client.on('error', (data) => {
    console.error('Connection error:', data.error);
});

message

Fired for all messages:

client.on('message', (message) => {
    console.log('Received:', message);
});

Automatic Reconnection

The client automatically attempts to reconnect on disconnection:

  • Exponential backoff: Delay doubles with each attempt
  • Maximum attempts: 5 attempts by default
  • Configurable: Can be customized via maxReconnectAttempts and reconnectDelay

Example:

const client = new WebSocketClient();
client.maxReconnectAttempts = 10;
client.reconnectDelay = 2000;

Room Management

Joining a Room

client.joinRoom('session_123');

Server response:

{
    "type": "user_joined",
    "room_id": "session_123",
    "user_id": "user_abc",
    "member_count": 3,
    "timestamp": "2024-01-01T00:00:00Z"
}

Leaving a Room

client.leaveRoom('session_123');

Server response:

{
    "type": "user_left",
    "room_id": "session_123",
    "user_id": "user_abc",
    "member_count": 2,
    "timestamp": "2024-01-01T00:00:00Z"
}

Sending to Room

client.sendToRoom('session_123', { type: 'update', data: {...} });

Example Usage

Basic Chat Client

const chatClient = WebSocketManager.getClient('chat');

// Register handlers
chatClient.on('connected', (data) => {
    console.log('Connected to chat');
});

chatClient.on('message', (message) => {
    if (message.type === 'chat_chunk') {
        console.log('Chat chunk:', message.content);
    }
});

// Send message
chatClient.send({ type: 'message', content: 'Hello' });

Agent Monitoring

const agentClient = WebSocketManager.getClient('agents');

// Subscribe to agent
agentClient.subscribeToAgent('coder');

// Handle agent updates
agentClient.on('message', (message) => {
    if (message.type === 'agent_update') {
        console.log('Agent status:', message.status);
    }
});

Collaboration Session

const collabClient = WebSocketManager.getClient('collaboration');

// Join session
collabClient.joinSession('session_123');

// Handle room events
collabClient.on('message', (message) => {
    if (message.type === 'user_joined') {
        console.log('User joined:', message.user_id);
    } else if (message.type === 'cursor_update') {
        console.log('Cursor moved:', message.position);
    }
});

// Send cursor updates
collabClient.sendCursorUpdate('session_123', { line: 10, column: 5 });

// Send edits
collabClient.sendEdit('session_123', {
    type: 'text',
    range: { start: 0, end: 10 },
    text: 'replacement'
});

// Leave session
collabClient.leaveSession('session_123');

Multiple Connections

// Get multiple clients
const chatClient = WebSocketManager.getClient('chat');
const agentClient = WebSocketManager.getClient('agents');
const systemClient = WebSocketManager.getClient('system');

// Check status
const status = WebSocketManager.getStatus();
console.log('Connection status:', status);

// Disconnect all when done
WebSocketManager.disconnectAll();

Integration

The WebSocket client library is integrated into the web interface through:

  1. HTML Loading: Loaded in index.html before app.js
  2. Global Access: Available as WebSocketManager global object
  3. User ID: Automatically generated and included in connection URL
  4. Protocol Detection: Automatically uses ws:// or wss:// based on page protocol

Best Practices

Connection Management

  • Always disconnect clients when no longer needed
  • Use WebSocketManager.disconnectAll() on page unload
  • Check connection state before sending messages

Error Handling

  • Register error handlers for all clients
  • Handle disconnection gracefully
  • Implement fallback mechanisms for critical features

Performance

  • Reuse clients instead of creating new ones
  • Use channel-specific clients for better organization
  • Clean up message handlers when no longer needed

Security

  • Validate all incoming messages
  • Sanitize message content before rendering
  • Use secure WebSocket (wss://) in production

// signal ends · generated 2026-11-10 from wiki/ · guides · developers //