agenomics 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ https://www.apache.org/licenses/
4
+
5
+ Copyright 2026 Dm.Andreyanov
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ https://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: agenomics
3
+ Version: 0.2.0
4
+ Summary: Genetics for AI Agents — predictability and compatibility scoring for autonomous agent personalities.
5
+ Author: Dm.Andreyanov
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://prizolov.ru
8
+ Project-URL: Repository, https://github.com/GIBDD-DPS/agenomics
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Dynamic: license-file
13
+
14
+ # 🧬 Agenomics
15
+
16
+ **Genetics for AI Agents — predictability and compatibility scoring for autonomous agent personalities.**
17
+
18
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
19
+ [![Python](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/)
20
+ [![Status](https://img.shields.io/badge/status-v0.2--draft-orange.svg)](#)
21
+
22
+ > **Автор**: Dm.Andreyanov
23
+ > **Версия**: 0.2.0
24
+ > **Связанные проекты**: [Prizolov Lab](https://prizolov.ru) / [Agent Genome Mapping (AGM)](https://github.com/GIBDD-DPS/agent-genome-mapping)
25
+
26
+ ---
27
+
28
+ ## Что это
29
+
30
+ **Agenomics** — методология и open-source инструментарий для оценки **предсказуемости личности** ИИ-агента и его **совместимости** с другими агентами в команде, построенные на биологической метафоре генома.
31
+
32
+ В отличие от существующих подходов к «доверию к ИИ-агентам» (криптографическая идентичность, лимиты трат, блокчейн-подписи — см. Agent Passport Standard, AgenticTrust и др.), Agenomics фокусируется на другом вопросе:
33
+
34
+ > Не «можно ли доверить агенту деньги», а **«предсказуемо ли ведёт себя личность агента, и уживётся ли она с другими агентами в команде»**.
35
+
36
+ ## Ключевая идея
37
+
38
+ Каждый агент описывается **геномом** — структурированным набором параметров:
39
+
40
+ - `cognitive_genes` — как агент мыслит (глубина рассуждений, креативность, риск-толерантность)
41
+ - `ethics_genes` — какие ограничения соблюдает (bias threshold, hard constraints)
42
+ - `social_genes` — как взаимодействует (стиль общения, разрешение конфликтов)
43
+ - `meta_genes` — как эволюционирует (скорость мутации, критерий отбора)
44
+
45
+ На основе генома вычисляется:
46
+
47
+ 1. **Trust Score** (0–100) — итоговая оценка предсказуемости и безопасности агента с учётом критичности домена (Impact Tier) и уровня автономности
48
+ 2. **Compatibility Score** — насколько хорошо два и более агентов сработаются в одной команде
49
+
50
+ ## Быстрый старт
51
+
52
+ ```bash
53
+ pip install -e .
54
+ ```
55
+
56
+ ```python
57
+ from agenomics import TrustScorer, AgentGenome
58
+
59
+ genome = AgentGenome(
60
+ id="cashflow-predictor-v1",
61
+ domain="finance",
62
+ autonomy="autonomous", # "advisory" | "autonomous"
63
+ transparency=70,
64
+ bias_control=85,
65
+ data_safety=90,
66
+ drift_rate=0.05,
67
+ has_ledger=True,
68
+ )
69
+
70
+ scorer = TrustScorer()
71
+ result = scorer.score(genome)
72
+
73
+ print(result.score) # 0-100
74
+ print(result.label) # Trusted / Conditional / High Risk
75
+ print(result.breakdown) # разбивка по 5 осям
76
+ print(result.capped_reason) # если применён потолок автономности
77
+ ```
78
+
79
+ ### Compatibility Scorer — совместимость команды агентов
80
+
81
+ ```python
82
+ from agenomics import AgentGenome, CompatibilityScorer
83
+
84
+ sales_agent = AgentGenome(
85
+ id="recommendation-agent",
86
+ bias_control=80, risk_tolerance=50, social_style=15, has_ledger=False,
87
+ )
88
+ support_agent = AgentGenome(
89
+ id="support-agent",
90
+ bias_control=82, risk_tolerance=50, social_style=90, has_ledger=True,
91
+ )
92
+
93
+ result = CompatibilityScorer().score_pair(sales_agent, support_agent)
94
+ print(result.score) # 0-100
95
+ print(result.breakdown) # разбивка по 4 осям: ethics, risk_tolerance, social_style, accountability
96
+ print(result.capped_reason) # если сработал потолок из-за этического конфликта
97
+
98
+ # Для команды из 3+ агентов (добавьте other_agent, third_agent и т.д.):
99
+ team_result = CompatibilityScorer().score_team([sales_agent, support_agent])
100
+ print(team_result.average_score)
101
+ print(team_result.weakest_pair) # самое слабое звено команды
102
+ ```
103
+
104
+ ### Веб-API
105
+
106
+ ```bash
107
+ curl -X POST https://<ваш-адрес-на-amvera>/compatibility \
108
+ -H "Content-Type: application/json" \
109
+ -d '{
110
+ "agents": [
111
+ {"id": "sales", "bias_control": 80, "risk_tolerance": 50, "social_style": 15},
112
+ {"id": "support", "bias_control": 82, "risk_tolerance": 50, "social_style": 90}
113
+ ]
114
+ }'
115
+ ```
116
+
117
+ ## Структура репозитория
118
+
119
+ ```
120
+ agenomics/
121
+ ├── agenomics/ # ядро: AgentGenome, TrustScorer
122
+ ├── prompts/ # системные промпты (Trust Auditor и др.)
123
+ ├── docs/ # методология, whitepaper
124
+ ├── tests/ # тесты
125
+ ├── amvera.yml # конфиг деплоя на Amvera
126
+ └── requirements.txt
127
+ ```
128
+
129
+ ## Методология
130
+
131
+ Полное описание методологии — в [`docs/METHODOLOGY.md`](docs/METHODOLOGY.md).
132
+
133
+ ## Roadmap
134
+
135
+ - [x] v0.1 — формула Trust Score, Tier-множитель, потолок автономности
136
+ - [x] v0.1 — промпт Trust Auditor (см. `prompts/`)
137
+ - [x] v0.2 — Compatibility Scorer между несколькими агентами
138
+ - [x] v0.2 — веб-API (`/score`, `/compatibility`) на Amvera
139
+ - [ ] v0.3 — веб-калькулятор на prizolov.ru (по аналогии с инструментами Prizolov Lab)
140
+ - [ ] v0.3 — публичный реестр верификации (Genome Ledger)
141
+ - [ ] v0.3 — публикация пакета на PyPI
142
+
143
+ ## Лицензия
144
+
145
+ Apache 2.0 — см. [LICENSE](LICENSE).
146
+
147
+ ---
148
+
149
+ © 2026 Dm.Andreyanov. Agenomics — независимый проект, развивающий идеи Agent Genome Mapping™ (Prizolov Lab).
@@ -0,0 +1,136 @@
1
+ # 🧬 Agenomics
2
+
3
+ **Genetics for AI Agents — predictability and compatibility scoring for autonomous agent personalities.**
4
+
5
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
6
+ [![Python](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/)
7
+ [![Status](https://img.shields.io/badge/status-v0.2--draft-orange.svg)](#)
8
+
9
+ > **Автор**: Dm.Andreyanov
10
+ > **Версия**: 0.2.0
11
+ > **Связанные проекты**: [Prizolov Lab](https://prizolov.ru) / [Agent Genome Mapping (AGM)](https://github.com/GIBDD-DPS/agent-genome-mapping)
12
+
13
+ ---
14
+
15
+ ## Что это
16
+
17
+ **Agenomics** — методология и open-source инструментарий для оценки **предсказуемости личности** ИИ-агента и его **совместимости** с другими агентами в команде, построенные на биологической метафоре генома.
18
+
19
+ В отличие от существующих подходов к «доверию к ИИ-агентам» (криптографическая идентичность, лимиты трат, блокчейн-подписи — см. Agent Passport Standard, AgenticTrust и др.), Agenomics фокусируется на другом вопросе:
20
+
21
+ > Не «можно ли доверить агенту деньги», а **«предсказуемо ли ведёт себя личность агента, и уживётся ли она с другими агентами в команде»**.
22
+
23
+ ## Ключевая идея
24
+
25
+ Каждый агент описывается **геномом** — структурированным набором параметров:
26
+
27
+ - `cognitive_genes` — как агент мыслит (глубина рассуждений, креативность, риск-толерантность)
28
+ - `ethics_genes` — какие ограничения соблюдает (bias threshold, hard constraints)
29
+ - `social_genes` — как взаимодействует (стиль общения, разрешение конфликтов)
30
+ - `meta_genes` — как эволюционирует (скорость мутации, критерий отбора)
31
+
32
+ На основе генома вычисляется:
33
+
34
+ 1. **Trust Score** (0–100) — итоговая оценка предсказуемости и безопасности агента с учётом критичности домена (Impact Tier) и уровня автономности
35
+ 2. **Compatibility Score** — насколько хорошо два и более агентов сработаются в одной команде
36
+
37
+ ## Быстрый старт
38
+
39
+ ```bash
40
+ pip install -e .
41
+ ```
42
+
43
+ ```python
44
+ from agenomics import TrustScorer, AgentGenome
45
+
46
+ genome = AgentGenome(
47
+ id="cashflow-predictor-v1",
48
+ domain="finance",
49
+ autonomy="autonomous", # "advisory" | "autonomous"
50
+ transparency=70,
51
+ bias_control=85,
52
+ data_safety=90,
53
+ drift_rate=0.05,
54
+ has_ledger=True,
55
+ )
56
+
57
+ scorer = TrustScorer()
58
+ result = scorer.score(genome)
59
+
60
+ print(result.score) # 0-100
61
+ print(result.label) # Trusted / Conditional / High Risk
62
+ print(result.breakdown) # разбивка по 5 осям
63
+ print(result.capped_reason) # если применён потолок автономности
64
+ ```
65
+
66
+ ### Compatibility Scorer — совместимость команды агентов
67
+
68
+ ```python
69
+ from agenomics import AgentGenome, CompatibilityScorer
70
+
71
+ sales_agent = AgentGenome(
72
+ id="recommendation-agent",
73
+ bias_control=80, risk_tolerance=50, social_style=15, has_ledger=False,
74
+ )
75
+ support_agent = AgentGenome(
76
+ id="support-agent",
77
+ bias_control=82, risk_tolerance=50, social_style=90, has_ledger=True,
78
+ )
79
+
80
+ result = CompatibilityScorer().score_pair(sales_agent, support_agent)
81
+ print(result.score) # 0-100
82
+ print(result.breakdown) # разбивка по 4 осям: ethics, risk_tolerance, social_style, accountability
83
+ print(result.capped_reason) # если сработал потолок из-за этического конфликта
84
+
85
+ # Для команды из 3+ агентов (добавьте other_agent, third_agent и т.д.):
86
+ team_result = CompatibilityScorer().score_team([sales_agent, support_agent])
87
+ print(team_result.average_score)
88
+ print(team_result.weakest_pair) # самое слабое звено команды
89
+ ```
90
+
91
+ ### Веб-API
92
+
93
+ ```bash
94
+ curl -X POST https://<ваш-адрес-на-amvera>/compatibility \
95
+ -H "Content-Type: application/json" \
96
+ -d '{
97
+ "agents": [
98
+ {"id": "sales", "bias_control": 80, "risk_tolerance": 50, "social_style": 15},
99
+ {"id": "support", "bias_control": 82, "risk_tolerance": 50, "social_style": 90}
100
+ ]
101
+ }'
102
+ ```
103
+
104
+ ## Структура репозитория
105
+
106
+ ```
107
+ agenomics/
108
+ ├── agenomics/ # ядро: AgentGenome, TrustScorer
109
+ ├── prompts/ # системные промпты (Trust Auditor и др.)
110
+ ├── docs/ # методология, whitepaper
111
+ ├── tests/ # тесты
112
+ ├── amvera.yml # конфиг деплоя на Amvera
113
+ └── requirements.txt
114
+ ```
115
+
116
+ ## Методология
117
+
118
+ Полное описание методологии — в [`docs/METHODOLOGY.md`](docs/METHODOLOGY.md).
119
+
120
+ ## Roadmap
121
+
122
+ - [x] v0.1 — формула Trust Score, Tier-множитель, потолок автономности
123
+ - [x] v0.1 — промпт Trust Auditor (см. `prompts/`)
124
+ - [x] v0.2 — Compatibility Scorer между несколькими агентами
125
+ - [x] v0.2 — веб-API (`/score`, `/compatibility`) на Amvera
126
+ - [ ] v0.3 — веб-калькулятор на prizolov.ru (по аналогии с инструментами Prizolov Lab)
127
+ - [ ] v0.3 — публичный реестр верификации (Genome Ledger)
128
+ - [ ] v0.3 — публикация пакета на PyPI
129
+
130
+ ## Лицензия
131
+
132
+ Apache 2.0 — см. [LICENSE](LICENSE).
133
+
134
+ ---
135
+
136
+ © 2026 Dm.Andreyanov. Agenomics — независимый проект, развивающий идеи Agent Genome Mapping™ (Prizolov Lab).
@@ -0,0 +1,20 @@
1
+ """
2
+ Agenomics — Genetics for AI Agents.
3
+
4
+ Оценка предсказуемости и совместимости личности ИИ-агентов
5
+ на основе методологии Agenomics (развитие Agent Genome Mapping™).
6
+
7
+ Автор: Dm.Andreyanov
8
+ Проект: Prizolov Lab
9
+ Версия: 0.2.0
10
+ """
11
+
12
+ from .trust_score import AgentGenome, TrustScorer, TrustResult, ImpactTier, Autonomy
13
+ from .compatibility import CompatibilityScorer, PairCompatibilityResult, TeamCompatibilityResult
14
+
15
+ __all__ = [
16
+ "AgentGenome", "TrustScorer", "TrustResult", "ImpactTier", "Autonomy",
17
+ "CompatibilityScorer", "PairCompatibilityResult", "TeamCompatibilityResult",
18
+ ]
19
+
20
+ __version__ = "0.2.0"
@@ -0,0 +1,208 @@
1
+ """
2
+ api.py — минимальный веб-API методологии Agenomics.
3
+
4
+ Автор: Dm.Andreyanov
5
+ Проект: Prizolov Lab
6
+ Версия: 0.2.0
7
+
8
+ Оборачивает уже протестированные TrustScorer и CompatibilityScorer
9
+ (см. trust_score.py, compatibility.py и соответствующие тесты) в
10
+ HTTP-эндпоинты. Используется amvera.yml для деплоя
11
+ (см. run.command: uvicorn agenomics.api:app ...).
12
+
13
+ Локальный запуск для проверки:
14
+ uvicorn agenomics.api:app --reload --port 8000
15
+
16
+ Пример запроса /score:
17
+ curl -X POST http://localhost:8000/score \
18
+ -H "Content-Type: application/json" \
19
+ -d '{
20
+ "id": "cashflow-predictor",
21
+ "domain": "finance",
22
+ "autonomy": "autonomous",
23
+ "transparency": 75,
24
+ "bias_control": 80,
25
+ "data_safety": 85,
26
+ "drift_rate": 0.1,
27
+ "has_ledger": false
28
+ }'
29
+
30
+ Пример запроса /compatibility (2+ агента):
31
+ curl -X POST http://localhost:8000/compatibility \
32
+ -H "Content-Type: application/json" \
33
+ -d '{
34
+ "agents": [
35
+ {"id": "sales", "bias_control": 80, "risk_tolerance": 50, "social_style": 15},
36
+ {"id": "support", "bias_control": 82, "risk_tolerance": 50, "social_style": 90}
37
+ ]
38
+ }'
39
+ """
40
+
41
+ from typing import Dict, List, Optional
42
+
43
+ from fastapi import FastAPI, HTTPException
44
+ from pydantic import BaseModel, Field
45
+
46
+ from .compatibility import CompatibilityScorer
47
+ from .trust_score import AgentGenome, Autonomy, ImpactTier, TrustScorer
48
+
49
+ app = FastAPI(
50
+ title="Agenomics API",
51
+ description=(
52
+ "Genetics for AI Agents — Trust Score и Compatibility Score для "
53
+ "автономных ИИ-агентов. Методология: см. docs/METHODOLOGY.md в репозитории."
54
+ ),
55
+ version="0.2.0",
56
+ )
57
+
58
+ _scorer = TrustScorer()
59
+ _compat_scorer = CompatibilityScorer()
60
+
61
+
62
+ class GenomeRequest(BaseModel):
63
+ id: str = Field(..., description="Уникальный идентификатор агента")
64
+ domain: Optional[str] = Field(
65
+ None, description="Домен агента, напр. 'finance', 'support', 'content'"
66
+ )
67
+ autonomy: str = Field(
68
+ "advisory", description="'advisory' (только советует) или 'autonomous' (действует сам)"
69
+ )
70
+ transparency: Optional[float] = Field(None, ge=0, le=100)
71
+ bias_control: Optional[float] = Field(None, ge=0, le=100)
72
+ data_safety: Optional[float] = Field(None, ge=0, le=100)
73
+ drift_rate: Optional[float] = Field(
74
+ None, ge=0, le=1, description="Доля дрейфа поведения агента, 0.0-1.0"
75
+ )
76
+ has_ledger: bool = Field(False, description="Есть ли журнал аудита (Genome Ledger)")
77
+ accountability_override: Optional[float] = Field(
78
+ None, ge=0, le=100, description="Ручная оценка Accountability, если есть точнее данные"
79
+ )
80
+ tier_override: Optional[int] = Field(
81
+ None, ge=1, le=3, description="Принудительный Impact Tier (1/2/3), если авто-классификация неверна"
82
+ )
83
+ risk_tolerance: Optional[float] = Field(
84
+ None, ge=0, le=100, description="Для Compatibility Score: 0 (осторожный) - 100 (рискованный)"
85
+ )
86
+ social_style: Optional[float] = Field(
87
+ None, ge=0, le=100, description="Для Compatibility Score: 0 (формальный) - 100 (неформальный/эмпатичный)"
88
+ )
89
+
90
+
91
+ class TrustScoreResponse(BaseModel):
92
+ id: str
93
+ tier: int
94
+ autonomy: str
95
+ score: float
96
+ label: str
97
+ breakdown: Dict[str, float]
98
+ insufficient_axes: List[str]
99
+ capped_reason: Optional[str] = None
100
+ recommendations: List[str]
101
+
102
+
103
+ class CompatibilityRequest(BaseModel):
104
+ agents: List[GenomeRequest] = Field(
105
+ ..., min_length=2, description="Список из 2+ агентов для оценки совместимости"
106
+ )
107
+
108
+
109
+ class PairScoreResponse(BaseModel):
110
+ agent_a: str
111
+ agent_b: str
112
+ score: float
113
+ breakdown: Dict[str, float]
114
+ insufficient_axes: List[str]
115
+ capped_reason: Optional[str] = None
116
+
117
+
118
+ class TeamCompatibilityResponse(BaseModel):
119
+ average_score: float
120
+ pairs: List[PairScoreResponse]
121
+ weakest_pair: PairScoreResponse
122
+
123
+
124
+ def _to_genome(payload: GenomeRequest) -> AgentGenome:
125
+ try:
126
+ autonomy = Autonomy(payload.autonomy)
127
+ except ValueError:
128
+ raise HTTPException(
129
+ status_code=400,
130
+ detail=(
131
+ f"autonomy должен быть 'advisory' или 'autonomous', "
132
+ f"получено: '{payload.autonomy}'"
133
+ ),
134
+ )
135
+ tier_override = ImpactTier(payload.tier_override) if payload.tier_override else None
136
+ return AgentGenome(
137
+ id=payload.id,
138
+ domain=payload.domain,
139
+ autonomy=autonomy,
140
+ transparency=payload.transparency,
141
+ bias_control=payload.bias_control,
142
+ data_safety=payload.data_safety,
143
+ drift_rate=payload.drift_rate,
144
+ has_ledger=payload.has_ledger,
145
+ accountability_override=payload.accountability_override,
146
+ tier_override=tier_override,
147
+ risk_tolerance=payload.risk_tolerance,
148
+ social_style=payload.social_style,
149
+ )
150
+
151
+
152
+ @app.get("/health")
153
+ def health() -> dict:
154
+ return {"status": "ok", "service": "agenomics-api", "version": "0.2.0"}
155
+
156
+
157
+ @app.get("/")
158
+ def root() -> dict:
159
+ return {
160
+ "name": "Agenomics API",
161
+ "description": "Genetics for AI Agents — Trust Score & Compatibility Score methodology.",
162
+ "endpoints": {
163
+ "POST /score": "Рассчитать Trust Score для генома агента",
164
+ "POST /compatibility": "Рассчитать совместимость 2+ агентов в команде",
165
+ "GET /health": "Проверка работоспособности",
166
+ },
167
+ "docs": "/docs", # автоматическая Swagger-документация FastAPI
168
+ }
169
+
170
+
171
+ @app.post("/score", response_model=TrustScoreResponse)
172
+ def score_agent(payload: GenomeRequest) -> TrustScoreResponse:
173
+ genome = _to_genome(payload)
174
+ result = _scorer.score(genome)
175
+
176
+ return TrustScoreResponse(
177
+ id=payload.id,
178
+ tier=int(genome.tier.value),
179
+ autonomy=genome.autonomy.value,
180
+ score=result.score,
181
+ label=result.label,
182
+ breakdown=result.breakdown,
183
+ insufficient_axes=result.insufficient_axes,
184
+ capped_reason=result.capped_reason,
185
+ recommendations=result.recommendations,
186
+ )
187
+
188
+
189
+ @app.post("/compatibility", response_model=TeamCompatibilityResponse)
190
+ def score_compatibility(payload: CompatibilityRequest) -> TeamCompatibilityResponse:
191
+ genomes = [_to_genome(a) for a in payload.agents]
192
+ result = _compat_scorer.score_team(genomes)
193
+
194
+ def _to_pair_response(p) -> PairScoreResponse:
195
+ return PairScoreResponse(
196
+ agent_a=p.agent_a,
197
+ agent_b=p.agent_b,
198
+ score=p.score,
199
+ breakdown=p.breakdown,
200
+ insufficient_axes=p.insufficient_axes,
201
+ capped_reason=p.capped_reason,
202
+ )
203
+
204
+ return TeamCompatibilityResponse(
205
+ average_score=result.average_score,
206
+ pairs=[_to_pair_response(p) for p in result.pairs],
207
+ weakest_pair=_to_pair_response(result.weakest_pair),
208
+ )
@@ -0,0 +1,132 @@
1
+ """
2
+ compatibility.py — Compatibility Scorer методологии Agenomics.
3
+
4
+ Автор: Dm.Andreyanov
5
+ Проект: Prizolov Lab
6
+ Версия: 0.2.0
7
+
8
+ Отвечает на вопрос: сработается ли команда из нескольких ИИ-агентов?
9
+ Использует те же геномы (AgentGenome), что и TrustScorer, плюс два
10
+ дополнительных поля: risk_tolerance и social_style.
11
+
12
+ Логика:
13
+ 1. Совместимость считается по 4 осям: этика, риск-толерантность,
14
+ социальный стиль, подотчётность.
15
+ 2. Этическое расхождение — самое опасное: превышение порога даёт
16
+ жёсткий потолок Compatibility Score ≤ 50 (по аналогии с потолком
17
+ автономности в TrustScorer — единый принцип методологии).
18
+ 3. Для команды > 2 агентов считается средняя совместимость по всем
19
+ парам + явно выделяется самая слабая пара (узкое место команды).
20
+ 4. Как и в TrustScorer — отсутствие данных не завышает оценку.
21
+ """
22
+
23
+ from dataclasses import dataclass, field
24
+ from itertools import combinations
25
+ from typing import List, Optional, Tuple
26
+
27
+ from .trust_score import AgentGenome
28
+
29
+ _ETHICS_CONFLICT_THRESHOLD = 40 # разница bias_control, после которой применяется потолок
30
+ _ETHICS_CONFLICT_CAP = 50
31
+
32
+ _WEIGHTS = {
33
+ "ethics": 0.35,
34
+ "risk_tolerance": 0.25,
35
+ "social_style": 0.20,
36
+ "accountability": 0.20,
37
+ }
38
+
39
+
40
+ def _axis_gap_score(a: Optional[float], b: Optional[float]) -> Tuple[float, bool]:
41
+ """
42
+ Превращает разницу между двумя значениями оси (0-100) в оценку
43
+ совместимости по этой оси (0-100, где 100 = полное совпадение).
44
+ Возвращает (score, insufficient_info).
45
+ """
46
+ if a is None or b is None:
47
+ return 50.0, True # нейтрально, не завышаем
48
+ gap = abs(a - b)
49
+ return max(0.0, 100.0 - gap), False
50
+
51
+
52
+ @dataclass
53
+ class PairCompatibilityResult:
54
+ agent_a: str
55
+ agent_b: str
56
+ score: float
57
+ breakdown: dict = field(default_factory=dict)
58
+ insufficient_axes: List[str] = field(default_factory=list)
59
+ capped_reason: Optional[str] = None
60
+
61
+
62
+ @dataclass
63
+ class TeamCompatibilityResult:
64
+ average_score: float
65
+ pairs: List[PairCompatibilityResult] = field(default_factory=list)
66
+ weakest_pair: Optional[PairCompatibilityResult] = None
67
+
68
+
69
+ class CompatibilityScorer:
70
+ """Вычисляет совместимость пары или команды агентов."""
71
+
72
+ def score_pair(self, a: AgentGenome, b: AgentGenome) -> PairCompatibilityResult:
73
+ insufficient = []
74
+
75
+ ethics_score, eth_insuff = _axis_gap_score(a.bias_control, b.bias_control)
76
+ risk_score, risk_insuff = _axis_gap_score(a.risk_tolerance, b.risk_tolerance)
77
+ social_score, soc_insuff = _axis_gap_score(a.social_style, b.social_style)
78
+ acc_score, acc_insuff = _axis_gap_score(a.accountability, b.accountability)
79
+
80
+ for name, insuff in [
81
+ ("ethics", eth_insuff), ("risk_tolerance", risk_insuff),
82
+ ("social_style", soc_insuff), ("accountability", acc_insuff),
83
+ ]:
84
+ if insuff:
85
+ insufficient.append(name)
86
+
87
+ breakdown = {
88
+ "ethics": ethics_score,
89
+ "risk_tolerance": risk_score,
90
+ "social_style": social_score,
91
+ "accountability": acc_score,
92
+ }
93
+
94
+ weighted = sum(breakdown[axis] * w for axis, w in _WEIGHTS.items())
95
+
96
+ capped_reason = None
97
+ ethics_gap = (
98
+ abs(a.bias_control - b.bias_control)
99
+ if a.bias_control is not None and b.bias_control is not None
100
+ else None
101
+ )
102
+ if ethics_gap is not None and ethics_gap > _ETHICS_CONFLICT_THRESHOLD and weighted > _ETHICS_CONFLICT_CAP:
103
+ weighted = _ETHICS_CONFLICT_CAP
104
+ capped_reason = (
105
+ f"Этическое расхождение между агентами ({ethics_gap:.0f} пунктов "
106
+ f"bias_control) превышает порог {_ETHICS_CONFLICT_THRESHOLD} — "
107
+ f"Compatibility Score не может быть выше {_ETHICS_CONFLICT_CAP}, "
108
+ f"независимо от совпадения по другим осям."
109
+ )
110
+
111
+ return PairCompatibilityResult(
112
+ agent_a=a.id,
113
+ agent_b=b.id,
114
+ score=round(weighted, 1),
115
+ breakdown=breakdown,
116
+ insufficient_axes=insufficient,
117
+ capped_reason=capped_reason,
118
+ )
119
+
120
+ def score_team(self, agents: List[AgentGenome]) -> TeamCompatibilityResult:
121
+ if len(agents) < 2:
122
+ raise ValueError("Для оценки совместимости нужно минимум 2 агента.")
123
+
124
+ pairs = [self.score_pair(a, b) for a, b in combinations(agents, 2)]
125
+ average = round(sum(p.score for p in pairs) / len(pairs), 1)
126
+ weakest = min(pairs, key=lambda p: p.score)
127
+
128
+ return TeamCompatibilityResult(
129
+ average_score=average,
130
+ pairs=pairs,
131
+ weakest_pair=weakest,
132
+ )
@@ -0,0 +1,208 @@
1
+ """
2
+ trust_score.py — реализация формулы Trust Score методологии Agenomics.
3
+
4
+ Автор: Dm.Andreyanov
5
+ Проект: Prizolov Lab
6
+ Версия: 0.2.0
7
+
8
+ Логика соответствует промпту "Trust Auditor v0.2":
9
+ 1. Классификация Impact Tier по домену агента.
10
+ 2. Множитель строгости ×1.3 к штрафам Predictability/Accountability
11
+ для TIER 3 (финансы, юридические вопросы, здоровье, деньги).
12
+ 3. Жёсткий потолок Trust Score ≤ 70 для Autonomous-агентов
13
+ с низкой Accountability (< 80), независимо от среднего балла.
14
+ 4. Явная пометка "insufficient_information", если данных для
15
+ честной оценки одной из осей не хватает — вместо завышения балла.
16
+ """
17
+
18
+ from dataclasses import dataclass, field
19
+ from enum import Enum
20
+ from typing import Optional
21
+
22
+
23
+ class Autonomy(str, Enum):
24
+ ADVISORY = "advisory" # агент только советует
25
+ AUTONOMOUS = "autonomous" # агент сам совершает действия
26
+
27
+
28
+ class ImpactTier(int, Enum):
29
+ TIER_1 = 1 # низкий риск: контент, творчество, внутренние заметки
30
+ TIER_2 = 2 # средний риск: поддержка, продажи, маркетинг
31
+ TIER_3 = 3 # высокий риск: финансы, юридические вопросы, здоровье, деньги
32
+
33
+
34
+ # Домены, автоматически относящиеся к TIER_3 (высокая критичность).
35
+ # Список неполный и предназначен для расширения под конкретные кейсы.
36
+ _TIER_3_DOMAINS = {
37
+ "finance", "financial", "banking", "payments", "legal", "law",
38
+ "health", "healthcare", "medical", "insurance", "cashflow",
39
+ }
40
+ _TIER_2_DOMAINS = {
41
+ "sales", "support", "marketing", "customer_service", "crm",
42
+ }
43
+
44
+ _AUTONOMY_TRUST_CAP = 70
45
+ _AUTONOMY_ACCOUNTABILITY_THRESHOLD = 80
46
+ _TIER_3_PENALTY_MULTIPLIER = 1.3
47
+
48
+ _WEIGHTS = {
49
+ "transparency": 0.25,
50
+ "bias_control": 0.25,
51
+ "data_safety": 0.20,
52
+ "predictability": 0.15,
53
+ "accountability": 0.15,
54
+ }
55
+
56
+
57
+ def infer_tier(domain: Optional[str]) -> ImpactTier:
58
+ """Определяет Impact Tier по названию домена агента."""
59
+ if not domain:
60
+ # Неизвестный домен — консервативный дефолт (не занижаем строгость).
61
+ return ImpactTier.TIER_2
62
+ d = domain.strip().lower()
63
+ if d in _TIER_3_DOMAINS:
64
+ return ImpactTier.TIER_3
65
+ if d in _TIER_2_DOMAINS:
66
+ return ImpactTier.TIER_2
67
+ return ImpactTier.TIER_1
68
+
69
+
70
+ @dataclass
71
+ class AgentGenome:
72
+ """Минимальный набор данных об агенте, необходимый для аудита."""
73
+
74
+ id: str
75
+ domain: Optional[str] = None
76
+ autonomy: Autonomy = Autonomy.ADVISORY
77
+
78
+ # Оси аудита (0-100). None означает "недостаточно информации".
79
+ transparency: Optional[float] = None
80
+ bias_control: Optional[float] = None
81
+ data_safety: Optional[float] = None
82
+ drift_rate: Optional[float] = None # 0.0-1.0, используется для Predictability
83
+ has_ledger: bool = False # наличие журнала аудита (Genome Ledger)
84
+ accountability_override: Optional[float] = None # ручная оценка, если есть
85
+
86
+ tier_override: Optional[ImpactTier] = None
87
+
88
+ # Поля ниже используются Compatibility Scorer (compatibility.py),
89
+ # необязательны для расчёта Trust Score.
90
+ risk_tolerance: Optional[float] = None # 0 (осторожный) - 100 (рискованный)
91
+ social_style: Optional[float] = None # 0 (формальный/прямой) - 100 (неформальный/эмпатичный)
92
+
93
+ @property
94
+ def tier(self) -> ImpactTier:
95
+ return self.tier_override or infer_tier(self.domain)
96
+
97
+ @property
98
+ def predictability(self) -> Optional[float]:
99
+ if self.drift_rate is None:
100
+ return None
101
+ return max(0.0, min(100.0, (1 - self.drift_rate) * 100))
102
+
103
+ @property
104
+ def accountability(self) -> float:
105
+ if self.accountability_override is not None:
106
+ return self.accountability_override
107
+ return 90.0 if self.has_ledger else 30.0
108
+
109
+
110
+ @dataclass
111
+ class TrustResult:
112
+ score: float
113
+ label: str
114
+ breakdown: dict = field(default_factory=dict)
115
+ insufficient_axes: list = field(default_factory=list)
116
+ capped_reason: Optional[str] = None
117
+ recommendations: list = field(default_factory=list)
118
+
119
+
120
+ class TrustScorer:
121
+ """Вычисляет Trust Score по методологии Agenomics."""
122
+
123
+ def _apply_tier_penalty(self, value: float, tier: ImpactTier) -> float:
124
+ """Усиливает штраф за низкий балл для критичных доменов (TIER_3)."""
125
+ if tier != ImpactTier.TIER_3:
126
+ return value
127
+ penalty = (100 - value) * _TIER_3_PENALTY_MULTIPLIER
128
+ return max(0.0, 100 - penalty)
129
+
130
+ def score(self, genome: AgentGenome) -> TrustResult:
131
+ insufficient = []
132
+ raw = {
133
+ "transparency": genome.transparency,
134
+ "bias_control": genome.bias_control,
135
+ "data_safety": genome.data_safety,
136
+ "predictability": genome.predictability,
137
+ "accountability": genome.accountability,
138
+ }
139
+
140
+ resolved = {}
141
+ for axis, value in raw.items():
142
+ if value is None:
143
+ insufficient.append(axis)
144
+ resolved[axis] = 50.0 # нейтральная, не завышенная оценка
145
+ else:
146
+ resolved[axis] = value
147
+
148
+ tier = genome.tier
149
+ # Tier-множитель применяется к Predictability и Accountability —
150
+ # именно эти оси определяют риск при сбое агента без надзора.
151
+ resolved["predictability"] = self._apply_tier_penalty(
152
+ resolved["predictability"], tier
153
+ )
154
+ resolved["accountability"] = self._apply_tier_penalty(
155
+ resolved["accountability"], tier
156
+ )
157
+
158
+ weighted = sum(resolved[axis] * w for axis, w in _WEIGHTS.items())
159
+
160
+ capped_reason = None
161
+ if (
162
+ genome.autonomy == Autonomy.AUTONOMOUS
163
+ and resolved["accountability"] < _AUTONOMY_ACCOUNTABILITY_THRESHOLD
164
+ and weighted > _AUTONOMY_TRUST_CAP
165
+ ):
166
+ weighted = _AUTONOMY_TRUST_CAP
167
+ capped_reason = (
168
+ f"Autonomous-агент с Accountability < "
169
+ f"{_AUTONOMY_ACCOUNTABILITY_THRESHOLD} не может получить "
170
+ f"Trust Score выше {_AUTONOMY_TRUST_CAP} (жёсткий потолок, "
171
+ f"не среднее арифметическое)."
172
+ )
173
+
174
+ final_score = round(weighted, 1)
175
+ label = self._label(final_score)
176
+ recommendations = self._recommendations(resolved, tier, genome.autonomy)
177
+
178
+ return TrustResult(
179
+ score=final_score,
180
+ label=label,
181
+ breakdown=resolved,
182
+ insufficient_axes=insufficient,
183
+ capped_reason=capped_reason,
184
+ recommendations=recommendations,
185
+ )
186
+
187
+ @staticmethod
188
+ def _label(score: float) -> str:
189
+ if score >= 85:
190
+ return "Trusted"
191
+ if score >= 60:
192
+ return "Conditional"
193
+ return "High Risk"
194
+
195
+ @staticmethod
196
+ def _recommendations(resolved: dict, tier: ImpactTier, autonomy: Autonomy) -> list:
197
+ recs = []
198
+ ordered = sorted(resolved.items(), key=lambda kv: kv[1])
199
+ for axis, value in ordered[:3]:
200
+ if value >= 80:
201
+ continue
202
+ recs.append(f"Повысить {axis} (текущее значение: {value:.0f}/100)")
203
+ if tier == ImpactTier.TIER_3 and autonomy == Autonomy.AUTONOMOUS:
204
+ recs.append(
205
+ "Домен высокой критичности + автономность: рассмотрите "
206
+ "перевод в Advisory-режим до достижения Accountability >= 80."
207
+ )
208
+ return recs
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: agenomics
3
+ Version: 0.2.0
4
+ Summary: Genetics for AI Agents — predictability and compatibility scoring for autonomous agent personalities.
5
+ Author: Dm.Andreyanov
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://prizolov.ru
8
+ Project-URL: Repository, https://github.com/GIBDD-DPS/agenomics
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Dynamic: license-file
13
+
14
+ # 🧬 Agenomics
15
+
16
+ **Genetics for AI Agents — predictability and compatibility scoring for autonomous agent personalities.**
17
+
18
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
19
+ [![Python](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/)
20
+ [![Status](https://img.shields.io/badge/status-v0.2--draft-orange.svg)](#)
21
+
22
+ > **Автор**: Dm.Andreyanov
23
+ > **Версия**: 0.2.0
24
+ > **Связанные проекты**: [Prizolov Lab](https://prizolov.ru) / [Agent Genome Mapping (AGM)](https://github.com/GIBDD-DPS/agent-genome-mapping)
25
+
26
+ ---
27
+
28
+ ## Что это
29
+
30
+ **Agenomics** — методология и open-source инструментарий для оценки **предсказуемости личности** ИИ-агента и его **совместимости** с другими агентами в команде, построенные на биологической метафоре генома.
31
+
32
+ В отличие от существующих подходов к «доверию к ИИ-агентам» (криптографическая идентичность, лимиты трат, блокчейн-подписи — см. Agent Passport Standard, AgenticTrust и др.), Agenomics фокусируется на другом вопросе:
33
+
34
+ > Не «можно ли доверить агенту деньги», а **«предсказуемо ли ведёт себя личность агента, и уживётся ли она с другими агентами в команде»**.
35
+
36
+ ## Ключевая идея
37
+
38
+ Каждый агент описывается **геномом** — структурированным набором параметров:
39
+
40
+ - `cognitive_genes` — как агент мыслит (глубина рассуждений, креативность, риск-толерантность)
41
+ - `ethics_genes` — какие ограничения соблюдает (bias threshold, hard constraints)
42
+ - `social_genes` — как взаимодействует (стиль общения, разрешение конфликтов)
43
+ - `meta_genes` — как эволюционирует (скорость мутации, критерий отбора)
44
+
45
+ На основе генома вычисляется:
46
+
47
+ 1. **Trust Score** (0–100) — итоговая оценка предсказуемости и безопасности агента с учётом критичности домена (Impact Tier) и уровня автономности
48
+ 2. **Compatibility Score** — насколько хорошо два и более агентов сработаются в одной команде
49
+
50
+ ## Быстрый старт
51
+
52
+ ```bash
53
+ pip install -e .
54
+ ```
55
+
56
+ ```python
57
+ from agenomics import TrustScorer, AgentGenome
58
+
59
+ genome = AgentGenome(
60
+ id="cashflow-predictor-v1",
61
+ domain="finance",
62
+ autonomy="autonomous", # "advisory" | "autonomous"
63
+ transparency=70,
64
+ bias_control=85,
65
+ data_safety=90,
66
+ drift_rate=0.05,
67
+ has_ledger=True,
68
+ )
69
+
70
+ scorer = TrustScorer()
71
+ result = scorer.score(genome)
72
+
73
+ print(result.score) # 0-100
74
+ print(result.label) # Trusted / Conditional / High Risk
75
+ print(result.breakdown) # разбивка по 5 осям
76
+ print(result.capped_reason) # если применён потолок автономности
77
+ ```
78
+
79
+ ### Compatibility Scorer — совместимость команды агентов
80
+
81
+ ```python
82
+ from agenomics import AgentGenome, CompatibilityScorer
83
+
84
+ sales_agent = AgentGenome(
85
+ id="recommendation-agent",
86
+ bias_control=80, risk_tolerance=50, social_style=15, has_ledger=False,
87
+ )
88
+ support_agent = AgentGenome(
89
+ id="support-agent",
90
+ bias_control=82, risk_tolerance=50, social_style=90, has_ledger=True,
91
+ )
92
+
93
+ result = CompatibilityScorer().score_pair(sales_agent, support_agent)
94
+ print(result.score) # 0-100
95
+ print(result.breakdown) # разбивка по 4 осям: ethics, risk_tolerance, social_style, accountability
96
+ print(result.capped_reason) # если сработал потолок из-за этического конфликта
97
+
98
+ # Для команды из 3+ агентов (добавьте other_agent, third_agent и т.д.):
99
+ team_result = CompatibilityScorer().score_team([sales_agent, support_agent])
100
+ print(team_result.average_score)
101
+ print(team_result.weakest_pair) # самое слабое звено команды
102
+ ```
103
+
104
+ ### Веб-API
105
+
106
+ ```bash
107
+ curl -X POST https://<ваш-адрес-на-amvera>/compatibility \
108
+ -H "Content-Type: application/json" \
109
+ -d '{
110
+ "agents": [
111
+ {"id": "sales", "bias_control": 80, "risk_tolerance": 50, "social_style": 15},
112
+ {"id": "support", "bias_control": 82, "risk_tolerance": 50, "social_style": 90}
113
+ ]
114
+ }'
115
+ ```
116
+
117
+ ## Структура репозитория
118
+
119
+ ```
120
+ agenomics/
121
+ ├── agenomics/ # ядро: AgentGenome, TrustScorer
122
+ ├── prompts/ # системные промпты (Trust Auditor и др.)
123
+ ├── docs/ # методология, whitepaper
124
+ ├── tests/ # тесты
125
+ ├── amvera.yml # конфиг деплоя на Amvera
126
+ └── requirements.txt
127
+ ```
128
+
129
+ ## Методология
130
+
131
+ Полное описание методологии — в [`docs/METHODOLOGY.md`](docs/METHODOLOGY.md).
132
+
133
+ ## Roadmap
134
+
135
+ - [x] v0.1 — формула Trust Score, Tier-множитель, потолок автономности
136
+ - [x] v0.1 — промпт Trust Auditor (см. `prompts/`)
137
+ - [x] v0.2 — Compatibility Scorer между несколькими агентами
138
+ - [x] v0.2 — веб-API (`/score`, `/compatibility`) на Amvera
139
+ - [ ] v0.3 — веб-калькулятор на prizolov.ru (по аналогии с инструментами Prizolov Lab)
140
+ - [ ] v0.3 — публичный реестр верификации (Genome Ledger)
141
+ - [ ] v0.3 — публикация пакета на PyPI
142
+
143
+ ## Лицензия
144
+
145
+ Apache 2.0 — см. [LICENSE](LICENSE).
146
+
147
+ ---
148
+
149
+ © 2026 Dm.Andreyanov. Agenomics — независимый проект, развивающий идеи Agent Genome Mapping™ (Prizolov Lab).
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ agenomics/__init__.py
5
+ agenomics/api.py
6
+ agenomics/compatibility.py
7
+ agenomics/trust_score.py
8
+ agenomics.egg-info/PKG-INFO
9
+ agenomics.egg-info/SOURCES.txt
10
+ agenomics.egg-info/dependency_links.txt
11
+ agenomics.egg-info/top_level.txt
12
+ tests/test_compatibility.py
13
+ tests/test_trust_score.py
@@ -0,0 +1 @@
1
+ agenomics
@@ -0,0 +1,19 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "agenomics"
7
+ version = "0.2.0"
8
+ description = "Genetics for AI Agents — predictability and compatibility scoring for autonomous agent personalities."
9
+ authors = [{ name = "Dm.Andreyanov" }]
10
+ license = { text = "Apache-2.0" }
11
+ readme = "README.md"
12
+ requires-python = ">=3.9"
13
+
14
+ [project.urls]
15
+ Homepage = "https://prizolov.ru"
16
+ Repository = "https://github.com/GIBDD-DPS/agenomics"
17
+
18
+ [tool.setuptools.packages.find]
19
+ include = ["agenomics*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,70 @@
1
+ """
2
+ test_compatibility.py — тесты CompatibilityScorer методологии Agenomics.
3
+
4
+ Автор: Dm.Andreyanov
5
+ Проект: Prizolov Lab
6
+ Версия: 0.2.0
7
+ """
8
+
9
+ from agenomics import AgentGenome, CompatibilityScorer
10
+
11
+
12
+ def test_compatible_pair_similar_agents():
13
+ """Два похожих по этике/риску/стилю агента — высокая совместимость."""
14
+ a = AgentGenome(id="support-a", bias_control=85, risk_tolerance=30, social_style=70, has_ledger=True)
15
+ b = AgentGenome(id="support-b", bias_control=88, risk_tolerance=35, social_style=65, has_ledger=True)
16
+ result = CompatibilityScorer().score_pair(a, b)
17
+ assert result.score >= 85
18
+ assert result.capped_reason is None
19
+
20
+
21
+ def test_ethics_conflict_triggers_cap():
22
+ """Сильное этическое расхождение — жёсткий потолок 50, даже если
23
+ остальные оси совпадают идеально."""
24
+ a = AgentGenome(id="strict-agent", bias_control=95, risk_tolerance=20, social_style=50, has_ledger=True)
25
+ b = AgentGenome(id="loose-agent", bias_control=40, risk_tolerance=20, social_style=50, has_ledger=True)
26
+ result = CompatibilityScorer().score_pair(a, b)
27
+ assert result.capped_reason is not None
28
+ assert result.score <= 50
29
+
30
+
31
+ def test_social_style_mismatch_from_article_case():
32
+ """Воспроизводит Кейс 2 из статьи: агент рекомендаций ('продающий',
33
+ social_style низкий) vs агент поддержки ('эмпатичный', высокий)."""
34
+ sales_agent = AgentGenome(
35
+ id="recommendation-agent", bias_control=80, risk_tolerance=50,
36
+ social_style=15, has_ledger=False, # низкий accountability тоже добавляет трение
37
+ )
38
+ support_agent = AgentGenome(
39
+ id="support-agent", bias_control=82, risk_tolerance=50,
40
+ social_style=90, has_ledger=True,
41
+ )
42
+ result = CompatibilityScorer().score_pair(sales_agent, support_agent)
43
+ # Большой разрыв social_style (75 пунктов) должен заметно снизить эту
44
+ # конкретную ось, но не обрушить итоговый score — этика (вес 0.35)
45
+ # у обоих агентов согласована, так что это "трение", а не критический
46
+ # конфликт. Итог должен попасть в диапазон "заметная проблема, но не
47
+ # критика" (аналог Conditional в Trust Score).
48
+ assert result.breakdown["social_style"] <= 30
49
+ assert 60 <= result.score < 85
50
+
51
+
52
+ def test_team_identifies_weakest_pair():
53
+ """Команда из 3 агентов — должен корректно определяться самый
54
+ несовместимый (узкое место) pair."""
55
+ good_a = AgentGenome(id="a", bias_control=85, risk_tolerance=40, social_style=60, has_ledger=True)
56
+ good_b = AgentGenome(id="b", bias_control=87, risk_tolerance=42, social_style=58, has_ledger=True)
57
+ bad_c = AgentGenome(id="c", bias_control=30, risk_tolerance=95, social_style=5, has_ledger=False)
58
+
59
+ result = CompatibilityScorer().score_team([good_a, good_b, bad_c])
60
+ assert len(result.pairs) == 3 # C(3,2) = 3 пары
61
+ assert result.weakest_pair is not None
62
+ assert bad_c.id in (result.weakest_pair.agent_a, result.weakest_pair.agent_b)
63
+
64
+
65
+ def test_insufficient_data_not_overscored():
66
+ """Отсутствие risk_tolerance/social_style не должно завышать оценку."""
67
+ a = AgentGenome(id="minimal-a", bias_control=80)
68
+ b = AgentGenome(id="minimal-b", bias_control=80)
69
+ result = CompatibilityScorer().score_pair(a, b)
70
+ assert set(result.insufficient_axes) >= {"risk_tolerance", "social_style"}
@@ -0,0 +1,73 @@
1
+ """
2
+ test_trust_score.py — тесты TrustScorer методологии Agenomics.
3
+
4
+ Автор: Dm.Andreyanov
5
+ Проект: Prizolov Lab
6
+ Версия: 0.2.0
7
+ """
8
+
9
+ from agenomics import AgentGenome, TrustScorer, Autonomy, ImpactTier
10
+
11
+
12
+ def test_support_agent_medium_quality():
13
+ """Тест-кейс А: чат-бот поддержки, среднее качество, без логов."""
14
+ genome = AgentGenome(
15
+ id="support-bot",
16
+ domain="support",
17
+ autonomy=Autonomy.ADVISORY,
18
+ transparency=60,
19
+ bias_control=65,
20
+ data_safety=55,
21
+ drift_rate=0.15,
22
+ has_ledger=False,
23
+ )
24
+ result = TrustScorer().score(genome)
25
+ assert genome.tier == ImpactTier.TIER_2
26
+ assert result.capped_reason is None # Advisory — потолок не применяется
27
+ assert 40 <= result.score <= 70
28
+
29
+
30
+ def test_finance_autonomous_agent_is_capped():
31
+ """Тест-кейс Б: автономный финансовый агент без логов — должен
32
+ получить жёсткий потолок Trust Score, даже с приличными осями."""
33
+ genome = AgentGenome(
34
+ id="cashflow-predictor",
35
+ domain="finance",
36
+ autonomy=Autonomy.AUTONOMOUS,
37
+ transparency=75,
38
+ bias_control=80,
39
+ data_safety=85,
40
+ drift_rate=0.1,
41
+ has_ledger=False, # accountability = 30, ниже порога 80
42
+ )
43
+ result = TrustScorer().score(genome)
44
+ assert genome.tier == ImpactTier.TIER_3
45
+ assert result.capped_reason is not None
46
+ assert result.score <= 70
47
+ assert result.label in ("Conditional", "High Risk")
48
+
49
+
50
+ def test_insufficient_information_not_overscored():
51
+ """Отсутствие данных не должно приводить к завышенной оценке."""
52
+ genome = AgentGenome(id="unknown-agent", domain=None)
53
+ result = TrustScorer().score(genome)
54
+ assert set(result.insufficient_axes) == {
55
+ "transparency", "bias_control", "data_safety", "predictability",
56
+ }
57
+ assert result.score <= 55
58
+
59
+
60
+ def test_trusted_agent_with_ledger_and_advisory():
61
+ genome = AgentGenome(
62
+ id="content-writer",
63
+ domain="content", # TIER_1
64
+ autonomy=Autonomy.ADVISORY,
65
+ transparency=90,
66
+ bias_control=88,
67
+ data_safety=92,
68
+ drift_rate=0.03,
69
+ has_ledger=True,
70
+ )
71
+ result = TrustScorer().score(genome)
72
+ assert result.label == "Trusted"
73
+ assert result.capped_reason is None