Metadata-Version: 2.4
Name: lmtrust
Version: 0.5.2
Summary: Deep Blind Spot Testing — systematic discovery and testing of code blind spots
Author: LMTrust Team
License: MIT
Project-URL: Homepage, https://github.com/user/lmtrust
Project-URL: Repository, https://github.com/user/lmtrust
Project-URL: Issues, https://github.com/Aslan008/lmtrust/issues
Keywords: testing,blind-spot,mutation-testing,llm,pytest,test-generation,code-quality
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: click>=8.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: mutmut>=2.4; extra == "dev"
Provides-Extra: hypothesis
Requires-Dist: hypothesis>=6.0; extra == "hypothesis"
Provides-Extra: analyze
Requires-Dist: openai>=1.0; extra == "analyze"

# LMTrust — Deep Blind Spot Testing

[Russian version below](#lmtrust--глубокое-тестирование-слепых-зон-русский)

> A deep blind spot testing system — finds bugs invisible to ordinary tests: violation of implicit assumptions, compositional failures, negative space.

## Installation

```bash
pip install lmtrust

# With LLM analysis support (OpenAI, Ollama, etc.):
pip install lmtrust[analyze]

# With hypothesis property-based testing:
pip install lmtrust[hypothesis]

# Full dev setup:
pip install lmtrust[dev,analyze,hypothesis]
```

## Quick Example

```bash
# Run the full pipeline on a Python file (requires LLM):
lmtrust run src/mymodule.py --base-url http://localhost:11434/v1 --model qwen2.5-coder:7b

# Check test coverage matrix:
lmtrust coverage tests/test_mymodule.py

# Scaffold test skeletons from source:
lmtrust scaffold src/mymodule.py --layers L0,L1,L4,L9
```

## What it is

LMTrust is a methodology and LLM skill that systematically finds blind spots in code and generates violating tests for each of them.

**Ordinary tests ask:** "Does the code do what it should?"

**Blind spot tests ask:** "What does the code do that it SHOULD NOT? What assumptions does it make? What happens when they break? What is NOT tested?"

## Architecture

LMTrust uses an **11-layer × 10-direction coverage matrix** (110 cells) to systematically categorize test coverage:

- **Layers (L0–L9 + L4b):** Smoke, Contract, Boundary, Property, Adversarial, Fallback, State, Cross-System, Compositional, Temporal, Negative Space
- **Directions (D1–D10):** Range, State/Transition, Scale, Error Handling, Resource, Concurrency, Contract, Security, Performance, Negative

The pipeline has 5 steps:

```
Source Code → 1. Analyze → 2. Map → 3. Generate → 4. Verify → 5. Report
```

| Step | What it does | LLM or Mechanical? |
|------|-------------|-------------------|
| Analyze | Extract assumptions and invariants from code | LLM (semantics) |
| Map | Cross-reference assumptions with coverage matrix | Mechanical |
| Generate | Create pytest tests that violate each assumption | LLM (semantics) |
| Verify | Run mutation testing (mutmut) for kill score | Mechanical |
| Report | Generate markdown/JSON report | Mechanical |

**Principle:** Framework = mechanics, LLM = semantics. The framework handles prompt construction, API calls, parsing, coverage matrices, and reporting. The LLM provides the semantic understanding of what assumptions the code makes.

## Quick Start

1. **Read `SKILL.md`** — the main file. It contains the complete methodology:
   - 11 test layers (L0–L9 + L4b)
   - 10 directions (D1–D10) + 2 named patterns
   - Decision tree for selecting layers by code type
   - 4 examples (pure function, stateful object, file I/O, external API)
   - 8 anti-patterns
   - Pre-merge checklist
   - Verification step (mutmut/Stryker)

2. **Use templates** from `templates/` — a starting point for each test layer.

3. **Run Verification** — after generating tests, verify them via mutation testing:
   - Python: `mutmut run --paths-to-mutate=<module> --tests-dir=tests/`
   - C#/.NET: `dotnet stryker --project <project>.csproj`

## Structure

```
LMTrust/
├── SKILL.md              # Main product — LLM skill
├── README.md             # This file
├── references/
│   └── examples/         # Usage examples
├── templates/            # Python templates for each layer
│   ├── l0_smoke.py
│   ├── l1_contract.py
│   ├── l2_boundary.py
│   ├── l3_property.py
│   ├── l4_adversarial.py
│   ├── l4b_fallback.py
│   ├── l5_state.py
│   ├── l6_integration.py
│   ├── l7_compositional.py
│   ├── l8_temporal.py
│   └── l9_negative_space.py
├── src/lmtrust/          # Phase 2 — Python framework + CLI
│   ├── __init__.py
│   ├── analyze.py        # LLM-based assumption extraction (Step 1)
│   ├── map.py            # Cross-reference assumptions → blind spots (Step 2)
│   ├── generate.py       # LLM-based violator tests generation (Step 3)
│   ├── sandbox.py        # Pytest sandbox runner for Runtime Healing
│   ├── cli.py            # CLI entry point (click)
│   ├── scaffold.py       # Test skeletons generator from AST
│   ├── verify.py         # mutmut wrapper: runner, parsing, kill score
│   ├── report.py         # Report generation (markdown/json)
│   └── coverage.py       # Layer × Direction matrix
├── tests/                # Framework unit tests
│   ├── conftest.py
│   ├── test_analyze.py
│   ├── test_map.py
│   ├── test_generate.py
│   ├── test_sandbox.py
│   ├── test_coverage.py
│   ├── test_verify.py
│   ├── test_report.py
│   └── test_scaffold.py
├── tests/dogfood/        # Blind-spot tests (dogfooding)
│   ├── test_analyze.py
│   ├── test_coverage.py
│   ├── test_cross_system.py   # L6+L7+L8: cross-module, compositional, temporal
│   ├── test_fallback.py       # L4b: fallback behavior
│   ├── test_generate.py
│   ├── test_map.py
│   ├── test_property.py       # L3: invariant/property tests
│   ├── test_report.py
│   ├── test_scaffold.py
│   └── test_verify.py
└── pyproject.toml        # Packaging (pip install -e .)
```

## CLI (Phase 2)

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

# Scaffold: extract functions from .py, generate test skeletons
lmtrust scaffold <file.py> [--output tests/] [--layers L0,L1,L4,L9]

# Coverage: show Layer × Direction matrix for a test file
lmtrust coverage <test_file.py> [--format markdown|json]

# Verify: run mutmut on a module, report kill score
lmtrust verify <module> [--tests-dir tests/] [--kill-threshold 0.5]

# Analyze: extract assumptions and invariants via LLM (Step 1)
#   Requires OPENAI_API_KEY or --base-url. Install: pip install lmtrust[analyze]
lmtrust analyze <file.py> [--model gpt-4o-mini] [--format markdown|json] [--output report.md]

# Map: assumptions → blind spots (Step 2) — cross-reference with coverage matrix
lmtrust map <file.py> [--test-file tests/test_foo.py] [--format markdown|json] [--output blind_spots.md]

# Generate: generate violating tests for blind spots (Step 3)
lmtrust generate <file.py> [--test-file tests/test_foo.py] [--output tests/] [--model gpt-4o-mini]

# Report: generate report
lmtrust report <file.py> [--format markdown|json] [--test-file tests/test_foo.py]

# Run: full pipeline in one command (Analyze → Map → Generate → [Verify] → Report)
#   Requires OPENAI_API_KEY or --base-url. Install: pip install lmtrust[analyze]
#   --runtime-heal: run generated tests in sandbox, heal ERRORs
lmtrust run <file.py> [--test-file tests/test_foo.py] [--output tests/] \
           [--report report.md] [--verify] [--model gpt-4o-mini] [--base-url URL] \
           [--format markdown|json] [--runtime-heal] [--heal-retries 3]

# Example with Ollama:
lmtrust run src/lmtrust/coverage.py --base-url http://localhost:11434/v1 \
           --model qwen2.5-coder:7b -o reports/generated -r reports/demo.md
```

### Pipeline (5 steps)

```
Code → 1. Analyze → 2. Map → 3. Generate → 4. Verify → 5. Report
```

| Step | CLI | Module | What it does |
|-----|-----|--------|------------|
| 1. Analyze | `lmtrust analyze` | `analyze.py` | LLM extracts assumptions and invariants |
| 2. Map | `lmtrust map` | `map.py` | Cross-reference with coverage matrix → blind spots |
| 3. Generate | `lmtrust generate` | `generate.py` | LLM generates violator tests |
| 4. Verify | `lmtrust verify` | `verify.py` | mutmut: kill score |
| 5. Report | `lmtrust report` | `report.py` | Markdown/JSON report |
| **All** | **`lmtrust run`** | **all** | **Full pipeline in one command** |

### Analyze (LLM-based)

The `analyze` command sends code to the LLM with the SKILL.md context (assumptions table, layers, directions) and gets a structured JSON. The framework provides the mechanics (prompt, API call, parsing, formatting) — the LLM provides semantics.

Provider-agnostic: any OpenAI-compatible endpoint via `--base-url` (Ollama, LM Studio, Azure). For custom integrations — `CallableProvider`.

### Map (Step 2)

The `map` command takes assumptions from `analyze` (where the LLM already determined `suggested_layer`, `suggested_direction`, `severity`) and cross-references them with the coverage matrix. Uncovered cells = blind spots. Mechanics without heuristics — all semantics come from the LLM.

### Generate (Step 3)

The `generate` command takes uncovered blind spots from `map` and asks the LLM to generate actual pytest tests that violate each assumption. The tests **must fail** — this is how blind spots are found. Each test gets a `@pytest.mark.lmtrust` marker.

### Runtime Healing (Phase 5)

The `--runtime-heal` flag in the `run` command executes generated tests in a pytest sandbox right inside the pipeline. If tests crash with an `ERROR` (bad imports, missing fixtures, wrong mocks), the errors are sent back to the LLM for fixing. The cycle repeats until success or up to `--heal-retries` attempts.

**Important:** Only `ERROR`s (the test itself is broken) are healed. `FAILED`s (blind spot found — test failed on an assertion) are NOT healed — this is the goal of the testing.

```bash
# Example with Runtime Healing:
lmtrust run src/mymodule.py --base-url http://localhost:11434/v1 \
           --model kimi-k2.7-code:cloud --runtime-heal --heal-retries 3
```

### Coverage markers

For accurate coverage tracking, use pytest markers in your tests:

```python
@pytest.mark.lmtrust(layer="L4", direction="D1")
def test_nan_crit(self):
    ...
```

`lmtrust coverage` parses markers from AST — reliable, without false positives. If markers are missing, a fallback is used: class name → layer, method name → direction.

## Test Layers

| Layer | Question | Blind Spot |
| ------ | -------- | ------------- |
| L0: Smoke | Is it alive at all? | Code doesn't run |
| L1: Contract | Does it do what it says? | Violates contract |
| L2: Boundary | What happens at the edges? | Breaks at boundaries |
| L3: Property | What is ALWAYS true? | Violates invariants |
| L4: Adversarial | What if assumptions are false? | Breaks upon violation |
| L4b: Fallback | What when the happy path is unavailable? | Fallback breaks |
| L5: State | Are all states reachable? | Breaks on transitions |
| L6: Cross-System | Does A+B break? | Interaction fails |
| L7: Compositional | Do two things break at once? | Combination of failures |
| L8: Temporal | Does order matter? | Breaks in different order |
| L9: Negative Space | What should NOT happen? | Does unintended things |

## Kern Gate Integration

For critical mathematical and business logic — use [Kern Gate](https://pypi.org/project/kern-gate/) for formal verification of contracts and invariants. LMTrust supplements it.

## License

MIT

---

# LMTrust — Глубокое тестирование слепых зон (Русский)

> Система глубокого тестирования «слепых зон» — находит ошибки, недоступные обычным тестам: нарушение неявных предположений, композиционные сбои, негативное пространство.

## Installation / Установка

```bash
pip install lmtrust

# С поддержкой LLM анализа (OpenAI, Ollama, и т.д.):
pip install lmtrust[analyze]

# С hypothesis (property-based тестирование):
pip install lmtrust[hypothesis]

# Полный набор для разработки:
pip install lmtrust[dev,analyze,hypothesis]
```

## Быстрый пример

```bash
# Полный пайплайн для файла (требует LLM):
lmtrust run src/mymodule.py --base-url http://localhost:11434/v1 --model qwen2.5-coder:7b

# Матрица покрытия:
lmtrust coverage tests/test_mymodule.py

# Генерация скелетов тестов:
lmtrust scaffold src/mymodule.py --layers L0,L1,L4,L9
```

## Что это

LMTrust — методология и скилл для LLM, который систематически находит слепые зоны в коде и генерирует тесты-нарушители для каждой из них.

**Обычные тесты спрашивают:** «Код делает то, что должен?»

**Blind spot тесты спрашивают:** «Что код делает, чего НЕ должен? Какие предположения он делает? Что происходит, когда они ломаются? Что НЕ тестируется?»

## Architecture (Архитектура)

LMTrust uses an **11-layer × 10-direction coverage matrix** (110 cells) to systematically categorize test coverage:

- **Слои (L0–L9 + L4b):** Smoke, Contract, Boundary, Property, Adversarial, Fallback, State, Cross-System, Compositional, Temporal, Negative Space
- **Направления (D1–D10):** Range, State/Transition, Scale, Error Handling, Resource, Concurrency, Contract, Security, Performance, Negative

Пайплайн состоит из 5 шагов:

```
Исходный код → 1. Analyze → 2. Map → 3. Generate → 4. Verify → 5. Report
```

| Шаг | Что делает | LLM или Механика? |
|------|-------------|-------------------|
| Analyze | Извлекает предположения и инварианты | LLM (семантика) |
| Map | Сверяет предположения с матрицей | Механика |
| Generate | Создаёт тесты-нарушители | LLM (семантика) |
| Verify | Мутационное тестирование (mutmut) | Механика |
| Report | Генерация отчётов | Механика |

**Принцип:** Фреймворк = механика, LLM = семантика. Фреймворк берет на себя промпты, API, парсинг и матрицы. LLM дает семантическое понимание логики.

## Быстрый старт

1. **Прочитай `SKILL.md`** — главный файл. Содержит полную методологию:
   - 11 слоёв тестов (L0–L9 + L4b)
   - 10 направлений (D1–D10) + 2 именованных паттерна
   - Дерево решений для выбора слоёв по типу кода
   - 4 примера (чистая функция, stateful объект, файловый I/O, внешний API)
   - 8 антипаттернов
   - Pre-merge checklist
   - Шаг Verification (mutmut/Stryker)

2. **Используй шаблоны** из `templates/` — отправная точка для каждого слоя тестов.

3. **Запусти Verification** — после генерации тестов, проверь их через мутационное тестирование:
   - Python: `mutmut run --paths-to-mutate=<module> --tests-dir=tests/`
   - C#/.NET: `dotnet stryker --project <project>.csproj`

## Структура

```
LMTrust/
├── SKILL.md              # Главный продукт — скилл для LLM
├── README.md             # Этот файл
├── references/
│   └── examples/         # Примеры использования
├── templates/            # Python-шаблоны для каждого слоя
├── src/lmtrust/          # Phase 2 — Python фреймворк + CLI
│   ├── analyze.py        # LLM-based извлечение предположений (Step 1)
│   ├── map.py            # Cross-reference assumptions → blind spots (Step 2)
│   ├── generate.py       # LLM-based генерация тестов-нарушителей (Step 3)
│   ├── sandbox.py        # Pytest sandbox runner для Runtime Healing
│   ├── cli.py            # CLI entry point (click)
│   ├── scaffold.py       # Генератор тестовых скелетов из AST
│   ├── verify.py         # mutmut wrapper: запуск, парсинг, kill score
│   ├── report.py         # Генерация отчётов (markdown/json)
│   └── coverage.py       # Матрица Layer × Direction
├── tests/                # Unit-тесты фреймворка
└── tests/dogfood/        # Blind-spot тесты (dogfooding)
```

## CLI (Phase 2)

```bash
# Установка
pip install -e ".[dev]"

# Scaffold: извлечь функции из .py, сгенерировать скелет тестов
lmtrust scaffold <file.py> [--output tests/] [--layers L0,L1,L4,L9]

# Coverage: показать матрицу Layer × Direction для тестового файла
lmtrust coverage <test_file.py> [--format markdown|json]

# Verify: запустить mutmut на модуле, отчёт kill score
lmtrust verify <module> [--tests-dir tests/] [--kill-threshold 0.5]

# Analyze: извлечь предположения и инварианты через LLM (Step 1)
#   Требует OPENAI_API_KEY или --base-url. Установите: pip install lmtrust[analyze]
lmtrust analyze <file.py> [--model gpt-4o-mini] [--format markdown|json] [--output report.md]

# Map: предположения → слепые зоны (Step 2) — сверка с coverage matrix
lmtrust map <file.py> [--test-file tests/test_foo.py] [--format markdown|json] [--output blind_spots.md]

# Generate: сгенерировать тесты-нарушители для слепых зон (Step 3)
lmtrust generate <file.py> [--test-file tests/test_foo.py] [--output tests/] [--model gpt-4o-mini]

# Report: сгенерировать отчёт
lmtrust report <file.py> [--format markdown|json] [--test-file tests/test_foo.py]

# Run: полный пайплайн в одной команде (Analyze → Map → Generate → [Verify] → Report)
#   Требует OPENAI_API_KEY или --base-url. Установите: pip install lmtrust[analyze]
#   --runtime-heal: запуск сгенерированных тестов в песочнице, лечение ERROR-ошибок
lmtrust run <file.py> [--test-file tests/test_foo.py] [--output tests/] \
           [--report report.md] [--verify] [--model gpt-4o-mini] [--base-url URL] \
           [--format markdown|json] [--runtime-heal] [--heal-retries 3]
```

### Analyze (LLM-based)

Команда `analyze` отправляет код в LLM с контекстом SKILL.md и получает структурированный JSON. Фреймворк предоставляет механику (промпт, API-вызов, парсинг, форматирование) — LLM обеспечивает семантику. Поддерживается любой OpenAI-совместимый endpoint через `--base-url`.

### Map (Step 2)

Команда `map` берёт предположения из `analyze` и сверяет с coverage matrix. Непокрытые ячейки = слепые зоны. Механика без эвристик — вся семантика от LLM.

### Generate (Step 3)

Команда `generate` просит LLM сгенерировать реальные pytest-тесты, которые нарушают каждое предположение. Тесты **должны падать** — так находятся слепые зоны.

### Runtime Healing (Phase 5)

Флаг `--runtime-heal` запускает сгенерированные тесты в песочнице pytest. Если тесты падают с `ERROR` (ошибки импортов, отсутствующие фикстуры), ошибки отправляются обратно в LLM для исправления. `FAILED` (найденная слепая зона) НЕ лечатся — это цель тестирования.

### Coverage markers

Для точного отслеживания покрытия используйте pytest markers в тестах:

```python
@pytest.mark.lmtrust(layer="L4", direction="D1")
def test_nan_crit(self):
    ...
```

## Слои тестов

| Слой | Вопрос | Слепая зона |
| ------ | -------- | ------------- |
| L0: Smoke | Оно вообще живое? | Код не запускается |
| L1: Contract | Делает то, что говорит? | Нарушает контракт |
| L2: Boundary | Что на краях? | Ломается на границах |
| L3: Property | Что ВСЕГДА истинно? | Нарушает инварианты |
| L4: Adversarial | Что если предположения — ложь? | Ломается при нарушении |
| L4b: Fallback | Что когда основной путь недоступен? | Fallback ломается |
| L5: State | Все ли состояния достижимы? | Ломается при переходах |
| L6: Cross-System | A+B ломается? | Взаимодействие проваливается |
| L7: Compositional | Две вещи ломаются одновременно? | Комбинация сбоев |
| L8: Temporal | Зависит ли порядок? | Ломается в другом порядке |
| L9: Negative Space | Что НЕ должно происходить? | Делает лишнее |

## Интеграция с Kern Gate

Для критической математической и бизнес логики — используй [Kern Gate](https://pypi.org/project/kern-gate/) для формальной верификации контрактов и инвариантов. LMTrust дополняет.

## Лицензия

MIT
