Metadata-Version: 2.4
Name: cognis-core
Version: 0.1.0
Summary: An open-source, local-first, governed agent-native runtime.
Author: Cognis Contributors
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pyyaml>=6.0.0
Requires-Dist: mcp>=1.0.0
Requires-Dist: ollama>=0.1.0
Requires-Dist: httpx>=0.20.0
Requires-Dist: textual>=0.50.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Dynamic: license-file

# Cognis

Cognis is a local-first, governed agent execution runtime.

## What is Cognis?

Cognis is a local-first, governed agent execution runtime. Running on top of existing operating systems, Cognis sits between AI agent reasoning logic and system capabilities, providing:

- **Agent Execution**: Multi-turn execution loop orchestrating model interactions and tool calls.
- **Policy Enforcement**: Declarative YAML governance gating tool invocations before execution.
- **Governed Tool Execution**: Pre-execution security boundary enforcing path, command, working-directory, environment, and timeout controls.
- **MCP Integration**: Protocol-standard capability integration using the Model Context Protocol (MCP).
- **Human Authorization**: Interactive permission request flows for sensitive tool executions.
- **Auditability**: Immutable, append-only JSONL logging of all authorization decisions and tool execution outcomes with automatic secret redaction.
- **Local-First Model Operation**: Default support for local models (e.g., Ollama) with explicit opt-in policies required for remote cloud providers.

Cognis is an execution governance runtime for AI agents. It is not an operating system replacement, kernel, or container hypervisor. Cognis enforces policy and security boundaries at the application runtime level.

## Why Cognis?

Modern AI agents can reason, plan, and dynamically select tools. However, executing AI-generated actions directly against external tools and filesystems requires governance, human authorization, strict security boundaries, and complete auditability.

The Model Context Protocol (MCP) provides a standardized, protocol-level interface connecting model logic to tools and resources. Cognis operates above the MCP layer to provide the governance runtime—ensuring that tool calls proposed by models pass through declarative policy checks, hard security restrictions, human-in-the-loop authorization, and audit logging before reaching external MCP servers.

## Architecture

Cognis structures execution through a deterministic governance loop:

```
User Intent
    ↓
Agent Loop
    ↓
Policy Engine
    ↓
ALLOW / PROMPT / DENY
    ↓
Governed Tool Executor
    ↓
MCP
    ↓
Capability
    ↓
Result + Audit
```

- **User Intent**: Natural language task or command submitted via CLI or TUI.
- **Agent Loop**: Assembles prompt context (`cognis/core/prompt.py`), queries the configured Model Provider, and extracts proposed tool calls.
- **Policy Engine**: Intercepts tool calls and evaluates declarative rules (`ALLOW`, `PROMPT`, or `DENY`) matching tool names and argument constraints (`cognis/policy/evaluator.py`).
- **Governed Tool Executor**: Enforces Phase 9 hard security boundaries (workspace path containment, single-command validation, working-directory restrictions, environment sanitization, remote model policy, and timeouts) prior to tool execution (`cognis/core/executor.py`).
- **MCP**: Manages subprocess server connections and tool invocations via stdio transport using the official Model Context Protocol (`cognis/core/stdio_mcp_client.py`).
- **Capability**: External MCP server processes exposing system tools (filesystem operations, command execution).
- **Result + Audit**: Execution results are returned to the agent loop while a structured audit record is logged to the append-only JSONL audit ledger (`cognis/audit.py`).


## Installation

### Requirements
- Python >= 3.11

### Standard Installation

Clone the repository and install in editable mode:

```bash
git clone https://github.com/AritranexX/cognis.git
cd cognis

python3 -m venv .venv
source .venv/bin/activate

pip install -e .
```

### Development Installation

To install development dependencies (including `pytest` test suite):

```bash
pip install -e ".[dev]"
```

## Quick Start

1. **Inspect CLI options**:
   ```bash
   cognis --help
   ```

2. **Verify program version**:
   ```bash
   cognis --version
   ```

3. **Inspect configured MCP capabilities**:
   ```bash
   cognis mcp list
   ```

4. **Validate active policy rules**:
   ```bash
   cognis policy check
   ```

5. **Run user intent via CLI**:
   ```bash
   cognis run "Inspect this project"
   ```

6. **Launch the Terminal User Interface (TUI)**:
   ```bash
   cognis tui
   # or simply
   cognis
   ```

*Note*: Cognis requires an accessible model provider (such as local Ollama or an OpenAI-compatible endpoint). No language model weights are bundled within Cognis.

## Model Configuration

Cognis supports two model provider backends: `ollama` and `openai-compatible`. Model settings are configured in `config.yaml` under the `model` key:

```yaml
model:
  provider: ollama             # Supported: "ollama", "openai-compatible"
  model: llama3                # Target model name
  endpoint: http://localhost:11434  # Provider endpoint URL (optional)
  api_key_env: OPENAI_API_KEY  # Name of environment variable containing API key
  timeout: 60.0                # Model request timeout in seconds
  allow_remote: false          # Explicitly permit remote cloud endpoints
```

### Local Model Operation & Remote Policy

- **Local-First Default**: By default, Cognis targets local models (e.g. Ollama at `http://localhost:11434`). Endpoints resolving to `localhost`, `127.0.0.1`, `::1`, single-label hostnames, or private IP spaces are classified as local.
- **Remote Model Governance**: Requests to external cloud endpoints (e.g. `api.openai.com`) are classified as remote. Remote model execution is **denied by default** (`allow_remote: false`). To permit remote endpoints, explicitly set `allow_remote: true` in `config.yaml` or set environment variable `COGNIS_MODEL_ALLOW_REMOTE=true`. Remote connections are never silently enabled.
- **Credential Non-Disclosure**: API keys are referenced strictly via environment variable names (`api_key_env`). Raw key strings are never embedded in configuration files, displayed in logs, or written to audit ledgers.

## MCP Configuration

Cognis declaratively configures Model Context Protocol (MCP) servers under `mcp.servers` in `config.yaml`:

```yaml
mcp:
  servers:
    filesystem:
      transport: stdio
      command: npx
      args:
        - "-y"
        - "@modelcontextprotocol/server-filesystem"
        - "."
      env:
        NODE_ENV: production
      cwd: .
      enabled: true
```

### Server Configuration Schema

- `name`: Identifier for the server (defaults to key name if omitted).
- `transport`: Communication protocol (`stdio` is the supported transport implementation in v0.1).
- `command`: Subprocess executable command (e.g. `npx`, `python3`, `node`).
- `args`: List of command-line argument strings passed to the subprocess executable.
- `env`: Key-value map of environment variables passed to the server process.
- `cwd`: Working directory path for the server process.
- `enabled`: Boolean flag enabling (`true`) or disabling (`false`) the server connection.

List registered MCP servers:

```bash
cognis mcp list
```

## Policy Configuration

Cognis enforces declarative policy rules defined in YAML format (default: `cognis/policy/default.yaml` or specified via `policy.path` in `config.yaml`):

```yaml
version: "0.1"
default_action: DENY

rules:
  - name: allow_filesystem_read
    tool: "read_file"
    action: ALLOW
    reason: "Allow reading file contents within authorized workspace"

  - name: prompt_filesystem_write
    tool: "write_file"
    action: PROMPT
    risk: HIGH
    arguments:
      path: "src/"
    reason: "Require explicit human authorization before writing files"

  - name: deny_shell_execution
    tool: "execute_command"
    action: DENY
    reason: "Block execution of external shell commands"
```

### Policy Actions

- `ALLOW`: Execution may proceed subject to Phase 9 hard security boundaries.
- `PROMPT`: Execution pauses and requests human authorization before proceeding.
- `DENY`: Execution is blocked immediately.

### Evaluation Rules & Precedence

1. **First Matching Rule Wins**: Rules evaluate strictly in declaration order.
2. **Default Action Fallback**: If no rule matches, `default_action` (default `DENY`) is applied.
3. **Tool & Argument Matching**: Rules match target tool names and optional argument constraints (`arguments`).
4. **Risk Classification**: Optional `risk` metadata (`LOW`, `MEDIUM`, `HIGH`, `CRITICAL`) describes action sensitivity for audit and UI presentation without altering policy evaluation.
5. **Un-overridable Hard Security**: Human authorization (`PROMPT` -> `ALLOW`) **cannot** override hard security violations (e.g., path traversal escape or malformed shell commands).


## Security

Cognis provides deterministic runtime execution governance over external capabilities.

### Enforced Security Boundaries

- **Workspace Path Containment (`PathPolicy`)**: Enforces path resolution (`Path.resolve()`) strictly within an authorized workspace root directory. Path traversal attempts (`..`), null bytes (`\x00`), and URL schemes (`file://`, `http://`) are rejected.
- **Command Structure Validation (`CommandPolicy`)**: Enforces single-command execution semantics. Unquoted shell operators (`&&`, `||`, `;`, `|`, `&`), subshell constructs (`$()`, `` ` ``), redirection (`>`, `<`), multi-line strings, and null bytes are rejected prior to execution.
- **Working-Directory Restrictions (`WorkingDirectoryPolicy`)**: Validates that subprocess working directories resolve strictly within the authorized workspace root and protects against symlink escape attempts.
- **Environment Sanitization (`EnvironmentPolicy`)**: Filters subprocess environment variables against a strict allowlist (`PATH`, `LANG`, `TMPDIR`, etc.) and sanitizes custom environment mappings.
- **Secret Filtering & Non-Disclosure (`AuditSanitizer`)**: Automatically redacts sensitive field names (`api_key`, `password`, `token`, `secret`, `credentials`) using `[REDACTED]` markers prior to audit persistence.
- **Remote Model Governance (`RemoteModelPolicy`)**: Blocks requests to external cloud model endpoints unless explicitly enabled by policy.
- **Execution Timeouts (`ExecutionTimeoutPolicy`)**: Enforces explicit execution time limits for tools (`tool_timeout`, default 30s) and model invocations (`model_timeout`, default 60s).
- **Adversarial Regression Suite**: Security boundaries are validated by 60+ dedicated regression tests in `tests/security/`.

*Security Boundary Note*: Cognis governs capability invocation through its runtime boundary. External MCP servers execute as separate subprocesses. Cognis enforces policy boundaries at the runtime level; it is not an OS container hypervisor or hardware sandbox.

## Audit

Cognis writes structured JSONL audit logs to `audit.jsonl` (or configured `audit.path`).

### Logged Fields

- `run_id`: Correlation UUID identifying the specific execution run.
- `timestamp`: Timezone-aware UTC ISO-8601 timestamp.
- `tool_name`: Target tool name string.
- `policy_decision`: Evaluated action (`action`), explanation (`reason`), and matched rule (`rule_matched`).
- `permission_events`: Human permission requests, risk levels, and user authorization decisions.
- `execution_result`: Execution status (`success`), duration in seconds, and normalized output metadata.
- `timeout_events`: Execution timeout details when limits are exceeded.
- `sensitive-value handling`: Credentials, tokens, and secret field values are sanitized to `[REDACTED]`.

### Representative Audit Record

```json
{
  "run_id": "8f0a32d1-4e92-411a-b601-e28a9c2bfb12",
  "timestamp": "2026-09-09T14:30:00.000000+00:00",
  "tool_name": "read_file",
  "policy_decision": {
    "action": "ALLOW",
    "reason": "Allow reading file contents within authorized workspace",
    "rule_matched": "allow_filesystem_read"
  },
  "execution_result": {
    "success": true,
    "duration": 0.012
  }
}
```

## Human Authorization

When a policy rule evaluates to `PROMPT`, Cognis pauses execution and generates a `PermissionRequest`:

```
Policy PROMPT
    ↓
Permission Request (PermissionRequest created)
    ↓
Human Authorization (TUI Prompt Dialog)
    │
    ├── ALLOW → Governed Execution (subject to hard security boundaries)
    └── DENY  → Execution Blocked
```

The Terminal UI presents an interactive dialog displaying tool details, argument payloads, risk level, and policy context. The human decision determines whether execution proceeds (`ALLOW`) or halts (`DENY`).

*Important*: The TUI is a presentation layer. It captures the user's decision and passes it to the runtime engine; the TUI itself does not execute tools.

## Example Project

A complete, working example project is located in [`examples/project_inspector/`](examples/project_inspector/).

The example demonstrates:
- Scanning repository directory structure via governed `list_directory` calls.
- Parsing software project manifests (`pyproject.toml`, `requirements.txt`) via governed `read_file` calls.
- Policy enforcement using `examples/project_inspector/policy.yaml` (`ALLOW` for inspect operations, `PROMPT` for write operations).
- Appending correlated audit records to `audit.jsonl`.

For instructions and execution steps, see [`examples/project_inspector/README.md`](examples/project_inspector/README.md).


## CLI Reference

Cognis provides a clean command-line interface (`cognis`):

```bash
# General Syntax
cognis [OPTIONS] {run,mcp,policy,tui} [COMMAND_ARGS]

# Options
  -h, --help            Show help message and exit
  -v, --version         Show program version and exit
  --config CONFIG       Path to custom YAML configuration file
  --log-level LEVEL     Set log level (DEBUG, INFO, WARNING, ERROR)
  --tui                 Launch Terminal UI mode
  --debug               Display detailed tracebacks on error

# Subcommands
  cognis run "INTENT"   Execute intent through governed agent runtime
  cognis mcp list       List configured MCP servers and status
  cognis policy check   Validate active policy rules and default action
  cognis tui            Launch Terminal User Interface (TUI)
```

## Development

### Test Suite Execution

Run the complete test suite (1,114 tests):

```bash
pytest
```

### Key Subsystems

- `cognis/core/`: Runtime engine, agent loop, governed executor, path/command/environment security boundaries, timeout policy, prompt construction.
- `cognis/policy/`: Declarative schema, YAML parser, matcher, evaluator, and risk classifier.
- `cognis/providers/`: Model provider adapters (`OllamaProvider`, `OpenAICompatibleProvider`).
- `cognis/models/`: Strongly-typed Pydantic v2 domain models.
- `cognis/tui/`: Textual-based Terminal UI (activity stream, permission dialog, diff viewer, structured results).
- `cognis/audit.py`: Append-only JSONL audit logger and sensitive data sanitizer.
- `cognis/config.py`: Configuration foundation and precedence parser.
- `cognis/cli.py`: Command-line interface entry point.
- `ARCHITECTURE.md`: Architectural specification and source of truth.

## Current Scope & Limitations

Cognis v0.1 focuses on establishing a governed execution runtime boundary. The following features are explicitly **out of scope** for v0.1:

- Persistent SQLite context databases or vector memory stores
- Filesystem state snapshotting or automated rollback
- Background daemon execution or scheduled task execution
- Cognis Canvas or dynamic HTML/browser rendering frontend
- Multi-agent swarm delegation or inter-agent coordination
- Distributed network execution across multiple nodes
- Direct OS kernel, hardware driver, or robotics integration


