@dzhechkov/keysarium 1.2.0 → 1.4.0

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.
Files changed (42) hide show
  1. package/README.md +29 -11
  2. package/package.json +2 -2
  3. package/src/utils.js +1 -1
  4. package/templates/.claude/commands/brain-export.md +99 -20
  5. package/templates/.claude/commands/brain-import.md +75 -4
  6. package/templates/.claude/commands/bto-benchmark.md +302 -0
  7. package/templates/.claude/commands/harvest.md +28 -46
  8. package/templates/.claude/rules/trust-tiers.md +1 -0
  9. package/templates/.claude/skills/knowledge-extractor/SKILL.md +254 -0
  10. package/templates/.claude/skills/knowledge-extractor/modules/01-extract.md +188 -0
  11. package/templates/.claude/skills/knowledge-extractor/modules/02-classify.md +99 -0
  12. package/templates/.claude/skills/knowledge-extractor/modules/03-gate.md +150 -0
  13. package/templates/.claude/skills/knowledge-extractor/modules/04-integrate.md +159 -0
  14. package/templates/.claude/skills/knowledge-extractor/references/artifact-categories.md +100 -0
  15. package/templates/.claude/skills/knowledge-extractor/references/maturity-model.md +94 -0
  16. package/templates/.claude/skills/knowledge-extractor/references/quality-gates.md +98 -0
  17. package/templates/.claude/skills/knowledge-extractor/templates/artifact-card.md +63 -0
  18. package/templates/.claude/skills/knowledge-extractor/templates/harvest-report.md +102 -0
  19. package/templates/CLAUDE.md +42 -22
  20. package/templates/docs/continuous-learning-guide.md +622 -0
  21. package/templates/docs/feature-adr/01-architecture.md +750 -0
  22. package/templates/docs/feature-adr/02-functionality.md +712 -0
  23. package/templates/docs/feature-adr/03-deployment-guide.md +614 -0
  24. package/templates/docs/feature-adr/04-admin-guide.md +564 -0
  25. package/templates/docs/feature-adr/05-user-guide.md +508 -0
  26. package/templates/docs/feature-adr/06-user-flows.md +1101 -0
  27. package/templates/docs/improvement-directions.md +8 -4
  28. package/templates/docs/keysarium-core/01-architecture.md +559 -0
  29. package/templates/docs/keysarium-core/02-functionality.md +955 -0
  30. package/templates/docs/keysarium-core/03-deployment-guide.md +625 -0
  31. package/templates/docs/keysarium-core/04-admin-guide.md +529 -0
  32. package/templates/docs/keysarium-core/05-user-guide.md +599 -0
  33. package/templates/docs/keysarium-core/06-user-flows.md +804 -0
  34. package/templates/docs/skills-bto/01-deployment-guide.md +1 -1
  35. package/templates/docs/skills-bto/02-admin-guide.md +4 -1
  36. package/templates/docs/skills-bto/03-user-guide.md +4 -3
  37. package/templates/docs/skills-bto/04-infrastructure-requirements.md +2 -1
  38. package/templates/docs/skills-bto/05-architecture.md +11 -11
  39. package/templates/docs/skills-bto/06-user-flows.md +2 -1
  40. package/templates/lib/dream-engine.md +1 -1
  41. package/templates/lib/memory-protocol.md +131 -22
  42. package/templates/lib/reward-tracker.md +6 -3
@@ -0,0 +1,955 @@
1
+ # Функциональность @dzhechkov/keysarium-core
2
+
3
+ > Полный справочник по всем протоколам, алгоритмам и JSON-схемам фреймворка.
4
+
5
+ ## Содержание
6
+
7
+ 1. [Governance — Управление](#1-governance--управление)
8
+ 2. [Memory — Обучение](#2-memory--обучение)
9
+ 3. [Orchestration — Оркестрация](#3-orchestration--оркестрация)
10
+ 4. [Verification — Верификация](#4-verification--верификация)
11
+ 5. [Trust Tiers — Классификация доверия](#5-trust-tiers--классификация-доверия)
12
+ 6. [Platform — Мультиплатформенность](#6-platform--мультиплатформенность)
13
+
14
+ ---
15
+
16
+ ## 1. Governance — Управление
17
+
18
+ ### 1.1. Constitution (constitution.md)
19
+
20
+ Набор **нерушимых инвариантов**, которые проверяются на каждом stage gate.
21
+
22
+ #### Формат инварианта
23
+
24
+ ```markdown
25
+ ### INV-{NNN}: {Short Name}
26
+
27
+ **Rule:** {Что всегда должно быть истинным}
28
+ **Enforcement:** {Как проверить — deterministic check, file existence, hash}
29
+ **On violation:** {HALT | WARN | RETRY(N)}
30
+ **Rationale:** {Зачем этот инвариант нужен}
31
+ ```
32
+
33
+ #### 7 базовых инвариантов
34
+
35
+ | ID | Название | Rule | Enforcement | On Violation |
36
+ |----|---------|------|-------------|-------------|
37
+ | INV-001 | Artifact Integrity | Артефакт верифицируем по witness chain hash | SHA-256 check после каждого этапа | HALT |
38
+ | INV-002 | Stage Completion Signal | Этап не завершён без promise tag | Проверка `<promise>` в checkpoint output | HALT |
39
+ | INV-003 | Human Checkpoint Required | Нет авто-перехода без подтверждения человека | Orchestrator ждёт explicit user input | HALT |
40
+ | INV-004 | Evaluator Independence | Судьи в panel работают изолированно | Judge attestation protocol | HALT |
41
+ | INV-005 | Loop Detection | Агент не повторяет действие 3+ раз подряд | Track last 3 actions per agent | WARN + escalate |
42
+ | INV-006 | Memory Consistency | Нет противоречивых паттернов в памяти | Check pattern_id conflicts при store | WARN |
43
+ | INV-007 | No Unverified Claims | Research не содержит непроверенных фактов | Scan для claims без source citation | HALT |
44
+
45
+ #### Доменные расширения
46
+
47
+ Нумерация с INV-100. Примеры:
48
+
49
+ - **Banking:** INV-100 Data Perimeter — все LLM-вызовы только к on-premise моделям
50
+ - **BTO:** INV-100 Judge-Generator Separation — модель генерации ≠ модель оценки
51
+
52
+ #### Интеграция
53
+
54
+ На каждом stage gate:
55
+ 1. Загрузить constitution + доменные расширения
56
+ 2. Запустить enforcement check для каждого инварианта
57
+ 3. HALT → остановить pipeline
58
+ 4. WARN → логировать и продолжить
59
+ 5. RETRY(N) → повторить до N раз, затем HALT
60
+
61
+ ---
62
+
63
+ ### 1.2. Shard Protocol (shard-protocol.md)
64
+
65
+ Решает проблему **context drift**: после ~40 минут правила «выпадают» из контекста агента.
66
+
67
+ #### Формат shard
68
+
69
+ ```markdown
70
+ # {Stage Name} Governance Shard
71
+
72
+ ## Time Budget
73
+ - Allocated: {percentage}% of total pipeline time
74
+ - Hard limit: {minutes} minutes
75
+
76
+ ## Prerequisites
77
+ - Required upstream promises: [{PROMISE_TAG_1}, {PROMISE_TAG_2}]
78
+ - Required input files: [{file_list}]
79
+
80
+ ## Skill to Load
81
+ - Primary: {skill_name} (read SKILL.md at: {path})
82
+
83
+ ## Rules for This Stage
84
+ 1. {Rule 1}
85
+ 2. {Rule 2}
86
+
87
+ ## Quality Gates
88
+ - [ ] {Gate 1}
89
+ - [ ] {Gate 2}
90
+
91
+ ## Promise Tag
92
+ On successful completion, emit: `<promise>{PROMISE_TAG}</promise>`
93
+
94
+ ## Anti-Patterns for This Stage
95
+ | Pattern | Fix |
96
+ |---------|-----|
97
+ | {Anti-pattern 1} | {Fix} |
98
+ ```
99
+
100
+ #### Протокол загрузки (7 шагов)
101
+
102
+ 1. **Determine shard path** — construct filename from stage ID
103
+ 2. **Read shard** — load into agent context
104
+ 3. **Validate prerequisites** — check upstream promises
105
+ 4. **Validate inputs** — check required files exist
106
+ 5. **Load skill** — read SKILL.md if specified
107
+ 6. **Start timer** — track against budget
108
+ 7. **Execute stage** — follow rules and quality gates
109
+
110
+ #### Naming Convention
111
+
112
+ ```
113
+ {stage-id}.shard.md
114
+ ```
115
+
116
+ Примеры: `stage-0-init.shard.md`, `bto-evaluation.shard.md`
117
+
118
+ #### Best Practice
119
+
120
+ - Держите shard под **100 строк** для оптимального context usage
121
+ - Включайте только правила релевантные текущему этапу
122
+ - Всегда включайте promise tag и time budget
123
+
124
+ ---
125
+
126
+ ### 1.3. Checkpoint Protocol (checkpoint-protocol.md)
127
+
128
+ Обязательные точки синхронизации «человек ↔ система».
129
+
130
+ #### Формат checkpoint
131
+
132
+ ```
133
+ =====================================================
134
+ CHECKPOINT {N}: {Stage Name} Complete
135
+ <promise>{PROMISE_TAG}</promise>
136
+
137
+ {2-3 line summary}
138
+ Artifacts created: {list}
139
+
140
+ Options:
141
+ - "ok" / "proceed" — advance to next stage
142
+ - "deepen {section}" — elaborate
143
+ - "{specific feedback}" — adjust
144
+ =====================================================
145
+ ```
146
+
147
+ #### Promise Tags
148
+
149
+ | Правило | Описание |
150
+ |---------|---------|
151
+ | Emit only when conditions met | Promise = подтверждение что quality gates пройдены |
152
+ | `_INCOMPLETE` suffix | Если условия НЕ выполнены: `<promise>TAG_INCOMPLETE</promise>` |
153
+ | Downstream check | Следующий этап проверяет upstream promises перед стартом |
154
+
155
+ #### Классификация reward по ответу пользователя
156
+
157
+ | Ответ | Reward | Label | Детекция |
158
+ |-------|--------|-------|----------|
159
+ | "ок", "proceed", одно слово | 1.0 | excellent | Single-word approval |
160
+ | "углуби X", feedback на 1 область | 0.7 | good | Scoped to one area |
161
+ | Переработка 3+ областей | 0.3 | needs_work | Multiple areas affected |
162
+ | "заново", "это неправильно" | 0.0 | failed | Full restart |
163
+
164
+ #### Интеграция
165
+
166
+ - **С governance:** на checkpoint запускаются все invariant checks
167
+ - **С memory:** после ответа пользователя → memory_store() с reward
168
+ - **С witness chain:** на "ok" → compute SHA-256 hash → append to chain
169
+
170
+ ---
171
+
172
+ ## 2. Memory — Обучение
173
+
174
+ ### 2.1. memory_query(context)
175
+
176
+ Вызывается в **начале** каждого этапа для загрузки исторических паттернов.
177
+
178
+ #### Input
179
+
180
+ ```json
181
+ {
182
+ "stage": "stage-2",
183
+ "domain": "banking",
184
+ "slug": "bank-kc-automation",
185
+ "skill": "goap-research-ed25519"
186
+ }
187
+ ```
188
+
189
+ #### Алгоритм (7 шагов)
190
+
191
+ 1. **Check enabled** — читаем `{memory-root}/config.json`, если `enabled: false` → пустой результат
192
+ 2. **Resolve path** — `{memory-root}/{domain}/` (сканируем все slug, не только текущий)
193
+ 3. **Scan records** — читаем все `{stage}_*.json` файлы по matching stage
194
+ 4. **Filter expired** — исключаем records где `expires_at < current_date`
195
+ 5. **Sort** — по `reward` DESC, затем `usage_count` DESC, затем `timestamp` DESC
196
+ 6. **Limit** — top `max_results_per_query` записей (default 10)
197
+ 7. **Enrich** — загружаем `_patterns/domain-patterns.json` для matching domain
198
+
199
+ #### Output
200
+
201
+ ```json
202
+ {
203
+ "records": [
204
+ {
205
+ "project_slug": "bank-kc-automation",
206
+ "stage": "stage-2",
207
+ "reward": 1.0,
208
+ "reward_label": "excellent",
209
+ "skill_used": "goap-research-ed25519",
210
+ "outcome_summary": "Research completed with verified sources",
211
+ "timestamp": "2026-02-15T14:30:00Z"
212
+ }
213
+ ],
214
+ "patterns": [
215
+ {
216
+ "pattern_id": "banking-stage-2-bottleneck",
217
+ "description": "Banking projects struggle in research phase",
218
+ "confidence": 0.85,
219
+ "actionable_advice": "Allocate extra time for regulatory research"
220
+ }
221
+ ],
222
+ "count": 3,
223
+ "domain": "banking"
224
+ }
225
+ ```
226
+
227
+ #### Использование после query
228
+
229
+ 1. Log: `"Loaded {count} historical patterns for {stage} in {domain} domain"`
230
+ 2. Если `records` не пустые — review top 3 для relevant approaches
231
+ 3. Если `patterns` не пустые — apply actionable advice
232
+ 4. Если всё пустое (первый запуск) — продолжить нормально
233
+ 5. **Increment usage_count** — для каждого применённого record (top 3) инкрементировать `usage_count` в файле и индексе
234
+
235
+ ---
236
+
237
+ ### 2.2. memory_store(result, reward)
238
+
239
+ Вызывается на каждом **checkpoint** после ответа пользователя.
240
+
241
+ #### Input
242
+
243
+ ```json
244
+ {
245
+ "project_slug": "bank-kc-automation",
246
+ "domain": "banking",
247
+ "stage": "stage-2",
248
+ "stage_name": "Research",
249
+ "skill_used": "goap-research-ed25519",
250
+ "reward": 0.7,
251
+ "reward_label": "good",
252
+ "reward_reason": "User requested additional regulatory depth",
253
+ "context": {
254
+ "stage_number": 2,
255
+ "domain_detected": "banking",
256
+ "upstream_promises": ["DISCOVERY_COMPLETE", "CASE_EXPLORED"],
257
+ "patterns_loaded": 3,
258
+ "time_budget_pct": 15.0,
259
+ "agent_count": 3
260
+ },
261
+ "outcome": {
262
+ "artifacts_created": ["02_research_findings.md"],
263
+ "checkpoint_response": "углуби регуляторику",
264
+ "iterations": 2,
265
+ "promise_emitted": "RESEARCH_PARANOID_PASSED"
266
+ }
267
+ }
268
+ ```
269
+
270
+ #### Алгоритм (6 шагов)
271
+
272
+ 1. **Ensure directory** — создать `{memory-root}/{domain}/{slug}/` если не существует
273
+ 2. **Build record** — полный RewardRecord JSON
274
+ 3. **Compute expires_at** — `current_date + retention_days` (default 90)
275
+ 4. **Generate filename** — `{stage}_{ISO-timestamp}.json`
276
+ 5. **Write file** — JSON в `{memory-root}/{domain}/{slug}/{filename}`
277
+ 6. **Log** — `"Stored reward {reward} ({label}) for {stage} of {slug}"`
278
+
279
+ #### RewardRecord Schema
280
+
281
+ ```json
282
+ {
283
+ "id": "bank-kc_stage-2_2026-02-15T14:30:00Z",
284
+ "version": "1.0",
285
+ "timestamp": "ISO-8601",
286
+ "project_slug": "bank-kc-automation",
287
+ "domain": "banking",
288
+ "stage": "stage-2",
289
+ "stage_name": "Research",
290
+ "skill_used": "goap-research-ed25519",
291
+ "reward": 0.7,
292
+ "reward_label": "good",
293
+ "reward_reason": "...",
294
+ "context": { "..." },
295
+ "outcome": { "..." },
296
+ "promise_tag": "RESEARCH_PARANOID_PASSED",
297
+ "usage_count": 0,
298
+ "expires_at": "2026-05-15T14:30:00Z"
299
+ }
300
+ ```
301
+
302
+ #### Namespace structure
303
+
304
+ ```
305
+ {memory-root}/
306
+ ├── config.json
307
+ ├── _patterns/
308
+ │ └── domain-patterns.json
309
+ ├── _stats/
310
+ │ └── reward-summary.json
311
+ ├── banking/
312
+ │ └── bank-kc-automation/
313
+ │ ├── stage-0_2026-02-15T10:00:00Z.json
314
+ │ ├── stage-1_2026-02-15T10:30:00Z.json
315
+ │ └── stage-2_2026-02-15T14:30:00Z.json
316
+ └── retail/
317
+ └── ecommerce-recommendations/
318
+ └── ...
319
+ ```
320
+
321
+ ---
322
+
323
+ ### 2.3. Reward Tracker (reward-tracker.md)
324
+
325
+ Аналитический движок, вычисляющий агрегаты и обнаруживающий паттерны.
326
+
327
+ #### 6-шаговый процесс
328
+
329
+ **Step 1: Load All Records** — рекурсивный scan `{memory-root}/`, исключая config/patterns/summary. Parse каждый JSON как RewardRecord. Exclude expired.
330
+
331
+ **Step 2: Per-Stage Averages**
332
+
333
+ ```json
334
+ {
335
+ "stage-2": {
336
+ "avg_reward": 0.85,
337
+ "total_runs": 12,
338
+ "distribution": { "excellent": 8, "good": 3, "needs_work": 1, "failed": 0 },
339
+ "trend": "stable",
340
+ "best_project": "bank-kc",
341
+ "worst_project": "healthcare-ai"
342
+ }
343
+ }
344
+ ```
345
+
346
+ **Trend Detection:** Делим records на 2 половины по timestamp. Newer_avg - Older_avg > 0.15 → "improving", < -0.15 → "degrading", иначе → "stable". Минимум 4 записи.
347
+
348
+ **Step 3: Per-Domain Averages**
349
+
350
+ ```json
351
+ {
352
+ "banking": {
353
+ "avg_reward": 0.72,
354
+ "total_runs": 18,
355
+ "stage_breakdown": { "stage-0": 0.85, "stage-1": 0.90, "stage-2": 0.55 },
356
+ "bottleneck_stage": "stage-2",
357
+ "strongest_stage": "stage-1"
358
+ }
359
+ }
360
+ ```
361
+
362
+ **Bottleneck Detection:** Этап с минимальным средним reward в домене. Только если 3+ записей.
363
+
364
+ **Step 4: Per-Skill Effectiveness**
365
+
366
+ ```json
367
+ {
368
+ "goap-research-ed25519": {
369
+ "overall_avg": 0.74,
370
+ "total_runs": 15,
371
+ "by_domain": {
372
+ "banking": { "avg": 0.65, "runs": 8 },
373
+ "retail": { "avg": 0.85, "runs": 7 }
374
+ },
375
+ "best_domain": "retail",
376
+ "worst_domain": "banking"
377
+ }
378
+ }
379
+ ```
380
+
381
+ **Step 5: Pattern Detection** — 6 правил:
382
+
383
+ | Правило | Условие | Шаблон паттерна |
384
+ |---------|---------|----------------|
385
+ | Stage Bottleneck | avg < 0.5 в домене, 3+ записей | "{domain} struggles in {stage}" |
386
+ | Stage Excellence | avg > 0.9 в домене, 3+ записей | "{domain} excels in {stage}" |
387
+ | Skill-Domain Mismatch | avg < 0.5 в одном домене, > 0.7 в другом | "{skill} underperforms in {domain}" |
388
+ | Improving Trend | trend = "improving" | "{stage} quality improving in {domain}" |
389
+ | Degrading Trend | trend = "degrading" | "{stage} quality degrading — investigate" |
390
+ | Time Overhead | avg iterations > 2.0 | "{domain} requires more iterations in {stage}" |
391
+
392
+ **Confidence:** `min(1.0, evidence_count / 10)`
393
+
394
+ **Step 6: Write Outputs** — `reward-summary.json` и `domain-patterns.json`
395
+
396
+ ---
397
+
398
+ ### 2.4. DreamEngine (dream-engine.md)
399
+
400
+ Фоновый процесс, строящий concept graphs и генерирующий cross-domain insights.
401
+
402
+ #### Trigger Evaluation
403
+
404
+ ```json
405
+ {
406
+ "version": "1.0",
407
+ "last_dream_completed_at": null,
408
+ "records_since_last_dream": 0,
409
+ "pending_events": [],
410
+ "config": {
411
+ "time_threshold_minutes": 60,
412
+ "volume_threshold": 20,
413
+ "event_triggers_enabled": true
414
+ }
415
+ }
416
+ ```
417
+
418
+ **3 типа триггеров:**
419
+
420
+ | Триггер | Условие | Default |
421
+ |---------|---------|---------|
422
+ | Time | Прошло > threshold минут с последнего dream | 60 min |
423
+ | Volume | records_since_last_dream ≥ threshold | 20 records |
424
+ | Event | pending_events непустой и enabled | true |
425
+
426
+ #### Dream Execution Protocol (5 шагов)
427
+
428
+ **Step 1: Load Data** — check memory root, read summary + patterns, scan records, exclude expired, sort by reward DESC, take top 200. Exit if < 5 records.
429
+
430
+ **Step 2: Build Concept Graph** — nodes (domain, stage, skill, outcome) + edges (domain→stage, stage→skill, skill→outcome) weighted by reward. Per-node aggregates: avg_reward, count, trend.
431
+
432
+ **Step 3: Detect Cross-Domain Associations (4 метода):**
433
+ - 3a: Cross-domain stage comparison (gap > 0.15)
434
+ - 3b: Skill-domain mismatch (gap > 0.15)
435
+ - 3c: Stage correlation (co-occurrence of low rewards ≥ 3)
436
+ - 3d: Temporal trends (systematic reward changes)
437
+
438
+ **Step 4: Generate Insights** — for each association → Insight JSON (type, description, confidence, impact, rank_score). Sort by rank_score DESC, take top 20.
439
+
440
+ **Step 5: Store and Clean** — write `dream-{timestamp}.json`, enforce max 10 files, reset triggers.
441
+
442
+ #### Dream Result Schema
443
+
444
+ ```json
445
+ {
446
+ "version": "1.0",
447
+ "dream_id": "dream-20260301-143022",
448
+ "status": "completed",
449
+ "trigger_reason": "volume",
450
+ "started_at": "ISO-8601",
451
+ "completed_at": "ISO-8601",
452
+ "records_analyzed": 200,
453
+ "concept_graph_nodes": 24,
454
+ "concept_graph_edges": 36,
455
+ "associations_found": 8,
456
+ "insights": [ "..." ],
457
+ "metadata": {
458
+ "domains_covered": ["banking", "retail"],
459
+ "stages_covered": ["stage-0", "stage-1", "stage-2"],
460
+ "total_reward_records_in_memory": 42
461
+ }
462
+ }
463
+ ```
464
+
465
+ ---
466
+
467
+ ## 3. Orchestration — Оркестрация
468
+
469
+ ### 3.1. Queen Protocol (queen-protocol.md)
470
+
471
+ 10-шаговый lifecycle координатора верхнего уровня.
472
+
473
+ | Step | Name | Purpose | Failure Mode |
474
+ |------|------|---------|-------------|
475
+ | 1 | INIT | Создать project directory | Abort on error |
476
+ | 2 | HEALTH | Проверить ресурсы (skills, shards, constitution) | Abort on missing |
477
+ | 3 | LOAD | Загрузить memory + dream insights + brain | Graceful (proceed without) |
478
+ | 4 | DETECT | Классифицировать domain + set variables | Default "general" |
479
+ | 5 | SHARD | Загрузить governance shard для текущего этапа | Fallback to master config |
480
+ | 6 | ORCHESTRATE | Выбрать topology + assign model + spawn agents | Halt at checkpoint |
481
+ | 7 | MONITOR | Track execution + display checkpoints | HALT if skipped (INV-003) |
482
+ | 8 | COLLECT | Собрать артефакты + verify quality gates | Halt if mandatory missing |
483
+ | 9 | STORE | memory_store() + update dream triggers | Graceful (log and continue) |
484
+ | 10 | REPORT | Summary + list artifacts + time report | Always succeeds |
485
+
486
+ ```
487
+ INIT → HEALTH → LOAD → DETECT → SHARD
488
+ ↓
489
+ ORCHESTRATE
490
+ ↓
491
+ MONITOR ←→ (repeat per stage)
492
+ ↓
493
+ COLLECT → STORE → REPORT
494
+ ```
495
+
496
+ #### Customization
497
+
498
+ - Steps 1-3 (INIT, HEALTH, LOAD) — **универсальные**, оставить как есть
499
+ - Step 4 (DETECT) — кастомизировать detection logic
500
+ - Step 5 (SHARD) — указать на ваш shard directory
501
+ - Step 6 (ORCHESTRATE) — определить ваши stages и topologies
502
+ - Steps 7-10 (MONITOR, COLLECT, STORE, REPORT) — **универсальные**
503
+
504
+ ---
505
+
506
+ ### 3.2. Topology Selection (topology-selection.md)
507
+
508
+ 6 типов топологий для организации агентов внутри этапа.
509
+
510
+ #### Star
511
+
512
+ ```
513
+ Coordinator
514
+ / | \
515
+ Agent1 Agent2 Agent3
516
+ ```
517
+
518
+ - **Координация:** централизованная
519
+ - **Communication:** hub-and-spoke
520
+ - **Fault tolerance:** medium
521
+ - **Scalability:** good
522
+ - **Best for:** простые параллельные задачи, multi-evaluator panels (изолированные)
523
+
524
+ #### Mesh
525
+
526
+ ```
527
+ Agent1 ←→ Agent2
528
+ ↕ ↕
529
+ Agent3 ←→ Agent4
530
+ ```
531
+
532
+ - **Координация:** децентрализованная
533
+ - **Communication:** all-to-all
534
+ - **Fault tolerance:** high
535
+ - **Scalability:** limited (O(n²) communication)
536
+ - **Best for:** fault-tolerant research
537
+
538
+ #### Hierarchical
539
+
540
+ ```
541
+ Queen
542
+ / \
543
+ Manager1 Manager2
544
+ / \ / \
545
+ W1 W2 W3 W4
546
+ ```
547
+
548
+ - **Координация:** иерархическая
549
+ - **Communication:** parent-child
550
+ - **Fault tolerance:** medium
551
+ - **Scalability:** excellent
552
+ - **Best for:** 10+ агентов, multi-level tasks
553
+
554
+ #### Ring
555
+
556
+ ```
557
+ Agent1 → Agent2 → Agent3 → Agent4
558
+ ↑ |
559
+ └──────────────────────────┘
560
+ ```
561
+
562
+ - **Координация:** последовательная
563
+ - **Communication:** unidirectional
564
+ - **Fault tolerance:** low
565
+ - **Scalability:** limited (linear latency)
566
+ - **Best for:** iterative refinement (draft → review → polish)
567
+
568
+ #### Hybrid
569
+
570
+ Комбинация двух+ топологий. Разные части stage используют разные arrangements.
571
+
572
+ #### Adaptive
573
+
574
+ Начинает как Star, эволюционирует:
575
+ - Если disagreement > 3 points → switch to Mesh
576
+ - Если простая задача → stay Star
577
+ - Если complexity выше threshold → elevate to Hierarchical
578
+
579
+ #### Selection Guide
580
+
581
+ | Характеристика | Рекомендация |
582
+ |---------------|-------------|
583
+ | Независимые параллельные задачи | **Star** |
584
+ | Fault-tolerant research | **Mesh** |
585
+ | Multi-evaluator panel | **Star** (isolated) |
586
+ | Итеративное улучшение | **Ring** |
587
+ | Complex multi-level | **Hierarchical** |
588
+ | Heterogeneous sub-tasks | **Hybrid** |
589
+ | Uncertain complexity | **Adaptive** |
590
+
591
+ ---
592
+
593
+ ### 3.3. Background Workers (background-workers.md)
594
+
595
+ Non-blocking агенты для долгих операций.
596
+
597
+ #### Directory Structure
598
+
599
+ ```
600
+ {workers-root}/
601
+ ├── registry.json ← Managed by orchestrator ONLY
602
+ ├── wkr-{YYYYMMDD}-{HHmmss}-{type}/
603
+ │ ├── status.json ← Written by worker
604
+ │ ├── stop-requested ← Flag file (orchestrator creates)
605
+ │ ├── output/ ← Worker output
606
+ │ └── error.log ← On failure
607
+ ```
608
+
609
+ #### Registry Schema
610
+
611
+ ```json
612
+ {
613
+ "version": "1.0",
614
+ "max_concurrent": 3,
615
+ "workers": [
616
+ {
617
+ "worker_id": "wkr-20260301-143022-consolidate",
618
+ "type": "consolidate",
619
+ "status": "running",
620
+ "model": "sonnet",
621
+ "started_at": "ISO-8601",
622
+ "completed_at": null,
623
+ "output_dir": "...",
624
+ "retry_count": 0
625
+ }
626
+ ]
627
+ }
628
+ ```
629
+
630
+ #### 6 правил изоляции
631
+
632
+ 1. Workers MUST only write to their own directory
633
+ 2. Workers MUST NOT modify project files directly
634
+ 3. Workers MUST NOT modify pipeline configuration
635
+ 4. Workers MUST NOT spawn sub-agents
636
+ 5. Workers MAY read project files (read-only)
637
+ 6. Workers write deltas/reports that user decides whether to apply
638
+
639
+ #### Протоколы
640
+
641
+ | Операция | Шаги |
642
+ |---------|------|
643
+ | **Launch** | Validate type → check concurrency (max 3) → create dir → update registry → spawn agent → confirm |
644
+ | **Status** | Read registry → read each status.json → update registry → prune 24h old entries → display |
645
+ | **Stop** | Verify running → write stop-requested flag → update registry → worker exits gracefully |
646
+
647
+ #### Error Handling
648
+
649
+ - Max 2 retries per original request
650
+ - Each retry = NEW worker (new ID, incremented retry_count)
651
+ - retry_count ≥ 2 → permanently failed
652
+
653
+ ---
654
+
655
+ ### 3.4. Model Routing (model-routing.md)
656
+
657
+ 3-tier система назначения моделей по сложности задачи.
658
+
659
+ | Tier | Model | Latency | Cost | Задачи |
660
+ |------|-------|---------|------|--------|
661
+ | 1 | haiku | ~500ms | 1x | Formatting, validation, structural checks, quick ranking |
662
+ | 2 | sonnet | ~2s | 15x | Research synthesis, analysis, judge panels, mutation workers |
663
+ | 3 | opus | ~5s | 75x | Creative design, complex solving, storytelling, architecture |
664
+
665
+ #### Enforcement Rules
666
+
667
+ 1. **NEVER** Tier 3 для structural checks — wasteful
668
+ 2. **NEVER** Tier 1 для judge panels — insufficient quality
669
+ 3. **NEVER** Tier 1 для creative work — shallow output
670
+ 4. **ALWAYS** specify model при spawn агента
671
+ 5. Без спецификации → наследуется от parent (обычно Tier 3)
672
+
673
+ #### Cost Impact
674
+
675
+ ```
676
+ Without routing: 20 tasks × Tier 3 = 20 × 75x = 1500x
677
+ With routing: 8×Tier1 + 8×Tier2 + 4×Tier3 = 8 + 120 + 300 = 428x
678
+ Savings: ~71%
679
+ ```
680
+
681
+ ---
682
+
683
+ ## 4. Verification — Верификация
684
+
685
+ ### 4.1. Witness Chain (witness-chain.md)
686
+
687
+ SHA-256 hash-chain для tamper-evident целостности артефактов.
688
+
689
+ #### Constants
690
+
691
+ ```
692
+ NULL_HASH = "0000000000000000000000000000000000000000000000000000000000000000"
693
+ CHAIN_FILE = ".witness-chain.json"
694
+ HASH_PREFIX = "sha256:"
695
+ ```
696
+
697
+ #### Hash Computation
698
+
699
+ ```bash
700
+ # Platform detection
701
+ if command -v sha256sum &>/dev/null; then SHA_CMD="sha256sum"
702
+ elif command -v shasum &>/dev/null; then SHA_CMD="shasum -a 256"
703
+ fi
704
+
705
+ # File hash
706
+ HASH=$(${SHA_CMD} "path/to/file.md" | awk '{print $1}')
707
+
708
+ # Chained hash
709
+ CHAINED_HASH=$(printf '%s%s' "${FILE_CONTENT}" "${PREV_HASH}" | ${SHA_CMD} | awk '{print $1}')
710
+ ```
711
+
712
+ #### Chain Operations
713
+
714
+ | Операция | Preconditions | Procedure |
715
+ |---------|--------------|-----------|
716
+ | **Genesis** | First artifact created, no chain file | Compute hash with NULL_HASH → create chain file |
717
+ | **Append** | Chain exists, new artifact created | Read last hash → compute chained hash → append record |
718
+ | **Verify** | Chain file exists | Walk chain, recompute each hash, compare |
719
+ | **Repair** | Artifact legitimately modified | Rehash modified → cascade rehash ALL downstream |
720
+
721
+ #### Chain File Schema
722
+
723
+ ```json
724
+ {
725
+ "project_slug": "bank-kc-automation",
726
+ "created_at": "ISO-8601",
727
+ "last_updated": "ISO-8601",
728
+ "chain": [
729
+ {
730
+ "sequence": 0,
731
+ "stage": "stage-0",
732
+ "artifact": "00_discovery.md",
733
+ "hash": "sha256:<64 hex>",
734
+ "previous_hash": "sha256:0000...0000",
735
+ "timestamp": "ISO-8601",
736
+ "promise_tag": "DISCOVERY_COMPLETE"
737
+ }
738
+ ]
739
+ }
740
+ ```
741
+
742
+ ---
743
+
744
+ ### 4.2. Judge Attestation (judge-attestation.md)
745
+
746
+ Криптографическое доказательство независимости оценщиков.
747
+
748
+ #### Hash Construction
749
+
750
+ ```
751
+ evaluation_hash = SHA-256(judge_id | artifact_hash | score | rationale_summary)
752
+ ```
753
+
754
+ - `judge_id` — уникальный ID роли судьи
755
+ - `artifact_hash` — SHA-256 оцениваемого артефакта
756
+ - `score` — числовой score с 1 decimal ("8.2")
757
+ - `rationale_summary` — первые 500 символов rationale
758
+
759
+ #### Chain Linking
760
+
761
+ ```
762
+ Judge 1: previous = NULL_HASH
763
+ Judge 2: previous = Judge 1's evaluation_hash
764
+ Judge 3: previous = Judge 2's evaluation_hash
765
+ ```
766
+
767
+ #### Isolation Proof Logic
768
+
769
+ 1. **Hash Independence** — each evaluation_hash computed from judge's own data only
770
+ 2. **Chain Integrity** — previous_attestation_hash links order, NOT scores
771
+ 3. **Timestamp Monotonicity** — timestamps strictly increasing
772
+
773
+ #### Attestation Schema
774
+
775
+ ```json
776
+ {
777
+ "evaluations": [
778
+ {
779
+ "evaluation_id": "bto-eval-001",
780
+ "artifact_path": "path/to/artifact.md",
781
+ "artifact_hash": "sha256:<hex>",
782
+ "panel_size": 3,
783
+ "attestations": [
784
+ {
785
+ "judge_id": "domain-expert",
786
+ "score": 8.2,
787
+ "rationale_summary": "...",
788
+ "evaluation_hash": "sha256:<hex>",
789
+ "timestamp": "ISO-8601",
790
+ "previous_attestation_hash": "sha256:0000...0000"
791
+ }
792
+ ],
793
+ "final_score": 7.94,
794
+ "weights": { "domain-expert": 0.4, "critic": 0.3, "auditor": 0.3 }
795
+ }
796
+ ]
797
+ }
798
+ ```
799
+
800
+ #### Meta-Judge
801
+
802
+ При disagreement > 3 points → meta-judge MAY reference other judges' scores (это synthesizer, не independent evaluator). Appended to attestation chain.
803
+
804
+ ---
805
+
806
+ ### 4.3. Audit Trail (audit-trail.md)
807
+
808
+ Единая история всех решений и оценок.
809
+
810
+ #### Directory Structure
811
+
812
+ ```
813
+ {audit-root}/
814
+ ├── audit-log.json ← Master event log
815
+ ├── witness-chains/
816
+ │ └── {project-slug}.json ← Per-project witness chain
817
+ ├── attestations/
818
+ │ └── {evaluation-id}.json ← Per-evaluation attestations
819
+ └── decisions/
820
+ └── {decision-id}.json ← Decision records
821
+ ```
822
+
823
+ #### 10 типов событий
824
+
825
+ | Event Type | Source Protocol |
826
+ |-----------|---------------|
827
+ | `artifact_created` | witness-chain.md |
828
+ | `artifact_verified` | witness-chain.md |
829
+ | `artifact_modified` | witness-chain.md (repair) |
830
+ | `evaluation_started` | judge-attestation.md |
831
+ | `evaluation_completed` | judge-attestation.md |
832
+ | `checkpoint_reached` | checkpoint-protocol.md |
833
+ | `checkpoint_approved` | checkpoint-protocol.md |
834
+ | `checkpoint_revised` | checkpoint-protocol.md |
835
+ | `reward_stored` | memory-protocol.md |
836
+ | `decision_made` | (this protocol) |
837
+
838
+ #### Retention
839
+
840
+ - Audit logs retained for **lifetime of project** (no auto-expiry)
841
+ - NOT subject to memory protocol's expiration rules
842
+ - On brain export: audit trail included as metadata (event counts, not full events)
843
+
844
+ ---
845
+
846
+ ## 5. Trust Tiers — Классификация доверия
847
+
848
+ ### 5.1. Tier System (tier-system.md)
849
+
850
+ | Tier | Label | Requirements | Confidence |
851
+ |------|-------|-------------|-----------|
852
+ | 3 | Verified | Eval tests + panel score ≥ 8.5 | Highest — production-ready |
853
+ | 2 | Validated | Panel score ≥ 7.0 | High — tested |
854
+ | 1 | Structured | SKILL.md + references/ or modules/ | Medium — organized |
855
+ | 0 | Advisory | Basic SKILL.md | Low — use with caution |
856
+
857
+ #### Classification Checklist
858
+
859
+ ```
860
+ [ ] SKILL.md exists → Tier 0 minimum
861
+ [ ] SKILL.md has complete protocol → Tier 0
862
+ [ ] references/ OR modules/ OR structured output → Tier 1
863
+ [ ] Multi-evaluator panel score ≥ 7.0 → Tier 2
864
+ [ ] Deterministic eval tests exist and pass → Tier 3
865
+ [ ] Panel score ≥ 8.5 → Tier 3
866
+ ```
867
+
868
+ #### Enforcement
869
+
870
+ | Context | Rule |
871
+ |---------|------|
872
+ | Production pipeline | Warn on Tier 0 skills |
873
+ | Critical decisions | Require Tier 2+ |
874
+ | Evaluation panels | Judges should be Tier 1+ |
875
+ | Knowledge export | Include tier metadata |
876
+
877
+ ---
878
+
879
+ ### 5.2. Promotion Protocol (promotion-protocol.md)
880
+
881
+ #### Tier 0 → Tier 1
882
+
883
+ **Requirements:** Complete SKILL.md + references/ OR modules/ OR structured output
884
+ **Process:** Structural check (no formal evaluation)
885
+
886
+ #### Tier 1 → Tier 2
887
+
888
+ **Requirements:** Pass 3-judge panel with avg score ≥ 7.0, no judge < 5.0
889
+ **Panel:** Domain Expert (0.4) + Critic (0.3) + Completeness Auditor (0.3)
890
+ **Process:** Submit for evaluation → judges score independently → compute weighted average → if ≥ 7.0 → promote
891
+
892
+ #### Tier 2 → Tier 3
893
+
894
+ **Requirements:** Score ≥ 8.5 + deterministic eval test suite (5+ tests) passing
895
+ **Process:** Create test cases → verify all pass → re-evaluate or use existing score ≥ 8.5 → promote
896
+
897
+ #### Demotion
898
+
899
+ | Trigger | Demotion |
900
+ |---------|---------|
901
+ | Eval tests start failing | Tier 3 → Tier 2 |
902
+ | Re-evaluation score drops | Tier 2 → Tier 1 |
903
+ | Materials removed | Tier 1 → Tier 0 |
904
+
905
+ #### Cross-Project Transfer
906
+
907
+ При импорте скилла из другого проекта, tier = **recommendation**:
908
+ 1. Accept as-is (trust source)
909
+ 2. Require re-evaluation (verify locally)
910
+ 3. Demote by one tier (conservative)
911
+
912
+ ---
913
+
914
+ ## 6. Platform — Мультиплатформенность
915
+
916
+ ### 6.1. Adapter Registry (adapter-registry.md)
917
+
918
+ | Platform | Config Format | Max Size |
919
+ |----------|--------------|---------|
920
+ | Claude Code | `.claude/` directory | Native (no limit) |
921
+ | Cursor | `.cursorrules` flat file | < 10K tokens |
922
+ | OpenCode | `.opencode/` directory | No hard limit |
923
+ | GitHub Copilot | `.github/copilot-instructions.md` | < 8K tokens |
924
+
925
+ #### Translation Rules
926
+
927
+ | Source Element | Cursor | OpenCode | Copilot |
928
+ |---------------|--------|----------|---------|
929
+ | Skill loading | Inline summary | Separate .md | Inline summary |
930
+ | Agent tool refs | "Break into sub-tasks" | "Break into sub-tasks" | "Break into sub-tasks" |
931
+ | Model routing | Omit | Omit | Omit |
932
+ | Promise tags | Keep as markers | Keep as markers | Keep as markers |
933
+ | Governance shards | Omit (single-file) | Include | Omit (single-file) |
934
+
935
+ #### Adding New Platform
936
+
937
+ 1. Create template: `platform/templates/{name}.md`
938
+ 2. Add to registry table
939
+ 3. Define: Target Format, Generation Protocol, Content Adaptation, Size Constraints, Example Output
940
+
941
+ ---
942
+
943
+ ## Error Handling — Сводная таблица
944
+
945
+ | Ситуация | Поведение |
946
+ |---------|----------|
947
+ | Memory root не существует | query → empty; store → create |
948
+ | config.json missing | Use defaults (90 days, 10 results) |
949
+ | Corrupted JSON | Skip file, log warning, continue |
950
+ | Write failure | Log error, continue (non-blocking) |
951
+ | sha256sum not available | Log WARNING, skip witness chain |
952
+ | Worker exceeds concurrency | Reject (not queue) |
953
+ | Invariant HALT violation | Stop pipeline, report to human |
954
+ | Invariant WARN violation | Log and continue |
955
+ | Dream insufficient data | Exit with status, zero insights |