AI kod quality gate - yapay zeka koduna mimari kontrol
Project description
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
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
# 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:
from aicontract import check, load_config
cfg = load_config('.aicontract_self.yaml')
result = check(source, config=cfg)
Kurulum
pip install aicontract
veya geliştirme için:
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
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
from aicontract import learn, anomaly
learn(".") # Baseline oluştur
anomaly(my_function) # Normal mi?
4. Risk Analizi
from aicontract import hotspot
hotspot(".") # En riskli dosyaları bul
5. Intent Tespiti
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
from aicontract import learn, anomaly
learn(".") # Baseline oluştur
anomaly(my_function) # Normal mi?
4. Risk Analizi
from aicontract import hotspot
hotspot(".") # En riskli dosyaları bul
Kullanım
CLI Komutları
# 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
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 |
aicontract check .
# Output:
# [DANGER] Cok supheyli! Bu kodu yazan AI muhtemelen hata yapiyor.
# [SKOR: 135] Ciddi sorunlar var!
Plugin Sistemi
Kendi kurallarını ekleyebilirsin.
# aicontract.yaml
plugins:
- name: todo_check
pattern: "TODO|FIXME|XXX"
severity: warning
message: "Unresolved marker"
from aicontract import load_plugins, get_plugin_violations
load_plugins("aicontract.yaml")
violations = get_plugin_violations(source_code)
Konfigürasyon
# 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
@ai_func(domain="domain_name", touches=["database"])
def function_name():
"""Docstring gerekli"""
pass
Validator
from aicontract import Validator, Registry
registry = Registry(".")
validator = Validator(registry)
violations = validator.scan_project(".")
Scanner
from aicontract import CallGraphScanner, Registry
registry = Registry(".")
scanner = CallGraphScanner(registry)
result = scanner.scan(".")
# Sonuç:
# {"updated": 10, "calls_found": 50}
Örnek Proje
"""Ö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
- Fork oluştur
- Değişiklik yap
- 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
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
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
# 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
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file aicontract-2.1.0.tar.gz.
File metadata
- Download URL: aicontract-2.1.0.tar.gz
- Upload date:
- Size: 78.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f35cc52c1158b886e58419d2876265832583ee6b20441e86c80387d3dad43ac0
|
|
| MD5 |
f30982c4ced17721d995419606d1dd63
|
|
| BLAKE2b-256 |
f5a027e7bc559b0f6c61bb2d304634be0a7a5d6f455434f167ca91aeceb50899
|
File details
Details for the file aicontract-2.1.0-py3-none-any.whl.
File metadata
- Download URL: aicontract-2.1.0-py3-none-any.whl
- Upload date:
- Size: 81.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c7364c91ff37701d3f9a302afd10367dc6e9826ff1ecdcd6baad7b3c18cf0603
|
|
| MD5 |
444f51afc7db47affa4259d0e1b9535d
|
|
| BLAKE2b-256 |
35728b160d41d4152230591fadea9465f17dddef5bde850244d4cb0d75fc39a2
|