Metadata-Version: 2.1
Name: neural-state-architecture
Version: 0.4.0
Summary: A state-aware runtime and typed control architecture for LLM applications
Author: Adam
License: MIT
Project-URL: Repository, https://github.com/adamlap/neural-state-architecture
Project-URL: Documentation, https://github.com/adamlap/neural-state-architecture/tree/main/docs
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Provides-Extra: ml
Requires-Dist: torch<2.5.0,>=2.0.0; extra == "ml"
Requires-Dist: transformers>=4.40.0; extra == "ml"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: hypothesis>=6.100.0; extra == "dev"
Requires-Dist: numpy<3.0.0,>=1.24.0; extra == "dev"
Requires-Dist: black>=24.0.0; extra == "dev"
Requires-Dist: ruff>=0.5.0; extra == "dev"
Requires-Dist: mypy>=1.10.0; extra == "dev"
Provides-Extra: research
Requires-Dist: torch<2.5.0,>=2.0.0; extra == "research"
Requires-Dist: transformers>=4.40.0; extra == "research"
Requires-Dist: numpy<3.0.0,>=1.24.0; extra == "research"

# Neural State Architecture (NSA)

> A state-aware runtime and typed control architecture for LLM applications.

NSA wraps a replaceable language model with **persistent explicit state, cognition hooks, policy evaluation, capability boundaries, provenance and auditable execution**. The model remains the intelligence backend; NSA owns the state/control loop.

> **Research status:** NSA is experimental research software. The repository contains validated security/state primitives and live-model experiments, but benchmark results do not establish AGI, consciousness, or universal safety.

## Install

Core NSA has no mandatory ML framework dependency:

```bash
pip install neural-state-architecture
```

Optional model integration:

```bash
pip install "neural-state-architecture[ml]"
```

Development/research:

```bash
pip install "neural-state-architecture[dev,research]"
```

## Five-minute local LLM example

Install [Ollama](https://ollama.com/) and pull a model:

```bash
ollama pull qwen2.5:3b
```

Then:

```python
from nsa import NSA, OllamaBackend

agent = NSA(
    OllamaBackend("qwen2.5:3b"),
    initial_state={"goal": "solve the user's problem accurately and safely"},
)

result = agent.run("Explain how persistent state can improve reasoning over time.")

print(result.text)
print(result.state.summary())
```

The important difference from a normal wrapper is that the runtime retains an explicit canonical state and observation history across calls. The backend never owns that state.

## Add governance

```python
from nsa import NSA, OllamaBackend, NSAPolicy, PolicyEngine

policy = NSAPolicy.from_json("examples/policies/safe_assistant.json")
agent = NSA(
    OllamaBackend("qwen2.5:3b"),
    policy_engine=PolicyEngine(policy),
)

result = agent.run("your request")
if result.blocked:
    print(result.decision.summary())
else:
    print(result.text)
```

Governance produces a typed `SecurityDecision`; it is not inferred from a refusal generated by the model.

## Architecture

```text
                    Replaceable LLM
                  Ollama / HF / API / ...
                           │
                           ▼
┌──────────────────────────────────────────────────────┐
│                    NSA Runtime                       │
│                                                      │
│  observation → state update → cognition → policy    │
│       ↑             ↓              ↓          ↓      │
│       │       CanonicalState   prediction   authority│
│       │       ├─ semantic                   │        │
│       │       ├─ hard                       ▼        │
│       │       ├─ soft                  capability    │
│       │       ├─ provenance              gate        │
│       │       └─ goals                     │         │
│       │                                    ▼         │
│       └──────────── trace / audit ← trusted runtime  │
└──────────────────────────────────────────────────────┘
```

### Core layers

| Layer | Responsibility |
|---|---|
| `nsa.runtime` | Stateful agent loop, observations, prompt/state binding, traces and persistence. |
| `nsa.core` | Canonical typed state and structural transitions. |
| `nsa.cce` | Continuous lifecycle, input events and checkpointing. |
| `nsa.cognition` | Belief/prediction and other cognitive state primitives. |
| `nsa.capabilities` | Capability and authority boundaries. |
| `nsa.policy` / `nsa.enforcement` | Policy compilation, classification and explicit security decisions. |
| `nsa.attention`, `nsa.layers`, `nsa.hf_integration` | Optional PyTorch/Transformer integration. |
| `experiments/` | Research-only benchmarks; never part of the runtime dependency path. |

The central design principle is:

> **Intelligence is not authority.**

A model may propose an action without automatically acquiring permission to execute it.

## Stateful runtime API

`NSA` is an alias for `NSARuntime` and is the stable application-facing entry point.

```python
agent.observe("The database is degraded", source="monitor", confidence=0.8)
result = agent.step(
    "Decide what to do next",
    action="external_side_effect",
    capabilities=["filesystem_write"],
)

snapshot = agent.snapshot()
agent.save()  # when a StateCheckpointStore is configured
```

The state is inspectable and typed:

```python
print(agent.state.summary())
print(agent.trace)
```

## Backends

The backend contract is intentionally tiny:

```python
class ModelBackend(Protocol):
    model: str
    def generate(self, prompt: str, *, state: Mapping[str, Any] | None = None) -> str: ...
```

Included adapters:

- `OllamaBackend` — zero-dependency local Ollama HTTP adapter.
- `CallableBackend` — connect any Python inference function.
- `EchoBackend` — deterministic testing backend.

New providers should implement this protocol rather than modifying the runtime.

## Run the local server

The existing OpenAI/Ollama-compatible server remains available while the runtime is being consolidated:

```bash
make serve-ollama
```

This lets OpenWebUI and other clients use NSA without embedding NSA-specific code in the client.

## Tests and development

```bash
make install-dev
make test
```

Fast runtime-only tests:

```bash
python -m pytest -q tests/test_runtime.py
```

Research experiments are separate from the core test gate:

```bash
make benchmark-nsa64
```

Live NSA 6.4 evidence is generated under `results/` and described in `research/`.

## Research program

The architecture is being developed as a research platform, not merely a prompt wrapper. The current hypothesis is that explicit operational/epistemic/normative state can improve cognition under uncertainty while a trusted capability boundary keeps authority independent of model preferences.

The current research stack is:

```text
Typed state + hard authority
          ↓
CCE / persistent cognitive state
          ↓
belief + prediction + information gain
          ↓
capability / policy governance
          ↓
live-model replication
          ↓
held-out + adversarial validation
```

The strongest current empirical results are documented in the `research/` package. Negative results and benchmark limitations are preserved rather than hidden.

## Repository structure

```text
nsa/          installable runtime library
experiments/  research implementations and benchmark drivers
research/     curated evidence, claims and reproducibility material
tests/        runtime and invariant regression tests
docs/         architecture and developer documentation
results/      generated local/CI experiment artifacts
evidence/     machine-readable claim/evidence records
```

Historical plans and experiment-specific code remain available for provenance, but the public runtime does not depend on them.

## Status and roadmap

Current focus:

1. consolidate the state/CCE/cognition/governance modules behind the stable runtime API;
2. keep the core package dependency-light and PyPI-friendly;
3. add backend adapters and persistence/tracing APIs;
4. make experiments consume the same public runtime rather than maintaining parallel agent implementations;
5. continue live-model research toward reproducible architectural evidence.

See `docs/ARCHITECTURE.md`, `docs/DEVELOPMENT.md` and `research/` for the current technical and scientific material.
