Metadata-Version: 2.4
Name: aicontract
Version: 2.1.0
Summary: AI kod quality gate - yapay zeka koduna mimari kontrol
Home-page: https://github.com/aicontract/aicontract
Author: aicontract
Author-email: hello@aicontract.dev
Project-URL: Bug Tracker, https://github.com/aicontract/aicontract/issues
Keywords: ai code-quality architecture-contract linting security
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyyaml>=6.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license-file
Dynamic: project-url
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# aicontract

**AI Kod Quality Gate** - Yapay zeka koduna mimari kontrol sistemi.

**Version: 2.1.0**

---

## Özellikler

### Temel Özellikler
| Özellik | Açıklama |
|---------|----------|
| `check(code)` | Kodu analiz et |
| `score(code)` | 0-100 şüphe skoru |
| `diff(eski, yeni)` | Ne kırıldı? |
| `learn(".")` | Projeyi öğren (baseline) |
| `anomaly(fn)` | İstatistiksel sapma tespit |
| `intent(fn)` | Fonksiyonun niyeti |
| `hotspot(".")` | Riskli dosyaları bul (Git geçmişi) |
| `check_side_effects()` | Yan etki tespiti |

### Decorator'lar
```python
from aicontract import *

@aicontract.ai_check        # Fonksiyonu otomatik kontrol et
@aicontract.contract(pure=True, max_complexity=5)  # Kural decorator

with aicontract.watch():   # Blok izleyici
    def login(): ...
```

### Yapılandırma
```yaml
# aicontract.yaml
aicontract:
  ignore_functions:
    - _private
    - setup_*
  ignore_rules:
    - STYLE001   # docstring
    - ARCH001    # god function
  thresholds:
    max_lines: 60
    max_complexity: 10
```

### Self-Validation
aicontract kendi kodunu da kontrol edebilir:
```python
from aicontract import check, load_config

cfg = load_config('.aicontract_self.yaml')
result = check(source, config=cfg)
```

---

## Kurulum

```bash
pip install aicontract
```

veya geliştirme için:

```bash
git clone https://github.com/kullanici/aicontract.git
cd aicontract
pip install -e .
```

---

## Proje Yapısı

```
aicontract/
├── core/           # ai_func, Registry
├── rules/          # 22+ kural, Violation
├── tools/          # Scanner, Reporter
├── utils/          # check, diff, learn, anomaly, intent, hotspot, config
├── adapters/       # SQL, Migration
└── plugins/       # Plugin sistemi

experimental/      # Deneysel özellikler
```
├── core/           # Temel: ai_func, Registry
├── rules/          # Validator, Violation
├── tools/          # Scanner, Reporter
├── utils/          # check, diff, learn, anomaly, intent, hotspot, config
├── adapters/       # SQL, Migration
└── plugins/       # Plugin sistemi

experimental/      # Deneysel özellikler
├── cli_v2.py      # Yeni CLI komutları
└── example_usage.py
```

---

## Hızlı Başlangıç

### 1. Kurulum

```bash
pip install aicontract
```

### 2. Kod Analizi

```python
from aicontract import check, score

# Kodu analiz et
result = check("""
def login(user, pw):
    return user == pw
""")

print(result.suspicion)  # {'total': 25, 'level': 'clean', ...}
print(score(code))        # 25
```

### 3. Projeyi Öğren

```python
from aicontract import learn, anomaly

learn(".")  # Baseline oluştur
anomaly(my_function)  # Normal mi?
```

### 4. Risk Analizi

```python
from aicontract import hotspot

hotspot(".")  # En riskli dosyaları bul
```

### 5. Intent Tespiti

```python
from aicontract import intent

i = intent("def get_user(id): pass")
print(i.category)  # READ
print(i.confidence)  # 1.0
```

---

## Örnekler

Daha fazla örnek için `examples/` klasörüne bakın.

### 3. Projeyi Öğren

```python
from aicontract import learn, anomaly

learn(".")  # Baseline oluştur
anomaly(my_function)  # Normal mi?
```

### 4. Risk Analizi

```python
from aicontract import hotspot

hotspot(".")  # En riskli dosyaları bul
```

---

## Kullanım

### CLI Komutları

```bash
# Projeyi tara
aicontract check .

# Registry durumu
aicontract status .

# AI için context oluştur
aicontract context .

# Call graph tara
aicontract scan .

# Registry temizle
aicontract cleanup .

# Projeyi entegre et (otomatik)
aicontract init .
```

### Programatik Kullanım

```python
from aicontract import ai_func, Validator, Registry

# Decorator ile
@ai_func(domain="data", touches=["database"])
def get_user(user_id: int) -> dict:
    return {"id": user_id}

# Manual kontrol
registry = Registry(".")
validator = Validator(registry)
violations = validator.scan_project(".")
```

---

## Kurallar

### Domain Kuralları (DOM)

Fonksiyonların doğru domain'e ait olmasını sağlar.

| ID | Açıklama | Örnek |
|----|----------|-------|
| DOM001 | Yanlış domain | `auth` yerine `data` domain'i |
| DOM002 | Domain tanımlanmamış | `@ai_func(domain="")` |
| DOM003 | Yabancı domain erişimi | `email` domain'i `db` kullanıyor |

### Mimari Kuralları (ARCH)

Kod yapısını kontrol eder.

| ID | Açıklama | Örnek |
|----|----------|-------|
| ARCH001 | God function | 40+ satır |
| ARCH002 | Çok dallanma | 7+ if/elif |
| ARCH003 | Çok parametre | 5+ argüman |
| ARCH004 | Return type yok | `def f():` yerine `def f() -> int:` |

### Performans Kuralları (PERF)

Performans sorunlarını tespit eder.

| ID | Açıklama | Örnek |
|----|----------|-------|
| PERF001 | Loop'ta DB | `for i in items: db.execute()` |
| PERF002 | Loop'ta HTTP | `for u in urls: fetch(u)` |
| PERF003 | Bare exception | `except:` yerine `except ValueError:` |

### Güvenlik Kuralları (SEC)

Güvenlik açıklarını bulur.

| ID | Açıklama | Örnek |
|----|----------|-------|
| SEC001 | Hardcoded secret | `password = "test123"` |
| SEC002 | SQL injection | `f"SELECT * FROM {table}"` |

### Yapay Zeka Kuralları (AI)

AI'ın yaptığı özel hataları tespit eder.

| ID | Açıklama | Örnek |
|----|----------|-------|
| AI001 | Var olmayan import | `import fake_library` |
| AI002 | Happy path only | try/except yok |
| AI003 | Magic numbers | `if x > 999:` |
| AI004 | Input validation yok | Parametre kontrolü yok |
| AI005 | N+1 query | Loop'ta DB sorgusu |
| AI006 | Karışık naming | camelCase + snake_case |
| AI007 | Type hints yok | `def f(a):` |
| AI008 | Resource leak | open() kapatılmamış |
| AI009 | Python uyumsuzluk | Eski syntax |
| AI010 | Deprecated API | Kaldırılmış fonksiyon |

---

## Şüphe Skoru

Her kontrol sonucunda bir "şüphe skoru" hesaplanır:

| Skor | Seviye | Anlamı |
|------|--------|--------|
| 0-24 | [OK] | Kod temiz |
| 25-49 | [CAUTION] | Dikkat |
| 50-99 | [WARNING] | Şüpheli |
| 100+ | [DANGER] | Çok şüpheli |

```bash
aicontract check .
# Output:
# [DANGER] Cok supheyli! Bu kodu yazan AI muhtemelen hata yapiyor.
# [SKOR: 135] Ciddi sorunlar var!
```

---

## Plugin Sistemi

Kendi kurallarını ekleyebilirsin.

```yaml
# aicontract.yaml
plugins:
  - name: todo_check
    pattern: "TODO|FIXME|XXX"
    severity: warning
    message: "Unresolved marker"
```

```python
from aicontract import load_plugins, get_plugin_violations

load_plugins("aicontract.yaml")
violations = get_plugin_violations(source_code)
```

---

## Konfigürasyon

```yaml
# aicontract.yaml
domains:
  authentication:
    owner: auth.py
    owns: [login, logout, verify]
    touches: [database]

  data_access:
    owner: repository.py
    owns: [get_user, create_user]
    touches: [database]

rules:
  error_handling: custom_exceptions
  db_pattern: repository
  async_style: everywhere

plugins:
  - name: custom_rule
    pattern: "SENSITIVE|PASSWORD"
    severity: error
```

---

## API Referansı

### Decorators

```python
@ai_func(domain="domain_name", touches=["database"])
def function_name():
    """Docstring gerekli"""
    pass
```

### Validator

```python
from aicontract import Validator, Registry

registry = Registry(".")
validator = Validator(registry)
violations = validator.scan_project(".")
```

### Scanner

```python
from aicontract import CallGraphScanner, Registry

registry = Registry(".")
scanner = CallGraphScanner(registry)
result = scanner.scan(".")

# Sonuç:
# {"updated": 10, "calls_found": 50}
```

---

## Örnek Proje

```python
"""Örnek: aicontract kullanımı"""
from aicontract import ai_func

@ai_func(domain="authentication", touches=["database"])
def authenticate_user(username: str, password: str) -> dict:
    """Kullanıcı girişi"""
    return {"success": True, "user_id": 1}

@ai_func(domain="data_access", touches=["database"])
def get_user(user_id: int) -> dict:
    """Kullanıcı bilgisi getir"""
    return {"id": user_id, "name": "Test"}

@ai_func(domain="api", touches=["http"])
def fetch_data(url: str) -> dict:
    """Harici API çağrısı"""
    return {"data": []}
```

---

## Katkıda Bulunma

1. Fork oluştur
2. Değişiklik yap
3. Pull request gönder

---

## Lisans

MIT License - Ücretsiz ve açık kaynak.

---

## 📋 Self-Diagnostics: aicontract v2.1.0

### Genel Durum: Temiz (ama 3 somut bug var)

| Metrik | Durum |
|--------|-------|
| Syntax hataları | 0 |
| Type hint coverage | Orta |
| Docstring coverage | İyi |
| Dead code | 1 adet |
| Duplicate logic | 1 adet |

---

### 🐛 Gerçek Sorunlar (Düzeltilmeli)

#### 1. Dead Code - `smart.py:330`
```python
return Intent(...)  # ← buradan döner
return Intent(...)  # ← DEAD CODE, asla çalışmaz
```
**Dosya:** `aicontract/utils/smart.py`  
**Satır:** ~330  
**Fonksiyon:** `extract_intent`

#### 2. Duplicate Block - `reporter.py:60-80`
```python
print("-" * 50)  # ← BU BLOK TEKRARLANMIŞ
# ... suspicion ...

print("-" * 50)  # ← AYNISI BİR ALTTA TEKRAR
# ... suspicion ...
```
**Dosya:** `aicontract/tools/reporter.py`  
**Satır:** ~60-80  
**Fonksiyon:** `summary()`

#### 3. Redundant Import - `context_gen.py`
```python
# Dosyanın başında zaten import edilmiş
# _build_target_context içinde tekrar try/except ile import
```
**Dosya:** `aicontract/tools/context_gen.py`  
**Fonksiyon:** `_build_target_context`

---

### 📊 Mimari Gözlemler

| Sorun | Detay |
|-------|-------|
| God Module | `smart.py` ~700 satır, 10+ fonksiyon, karmaşıklık yüksek |
| Import Path | `inline.py`'deki `suggest()` dinamik import tutarsız |
| Test Coverage | Zayıf - sadece 2 test dosyası |

---

### ❌ Neden aicontract Bunları Bulamadı?

| Sorun | Neden Bulamadı |
|-------|----------------|
| Dead code | **DEAD001** kuralı yok |
| Duplicate block (same-file) | DUP003 sadece cross-file |
| Redundant import | **IMP001** kuralı yok |
| God module (enhanced) | ARCH001 sadece satır sayısına bakıyor |

**Sonuç:** Kendi kurallarımız kendi kodumuzu yakalamıyor.

---

### 🔧 Önerilen Yeni Kurallar

| ID | Açıklama | Hedef |
|----|----------|-------|
| DEAD001 | Unreachable code tespiti | `smart.py` |
| DUP004 | Same-file duplicate blok | `reporter.py` |
| IMP001 | Unused/duplicate imports | `context_gen.py` |
| ARCH001v2 | God module (lines + funcs + complexity) | `smart.py` |

---

## İletişim

- GitHub: https://github.com/kullanici/aicontract
- Sorunlar: https://github.com/kullanici/aicontract/issues
