Этот справочник описывает текущую архитектуру agent-системы CodeGraph. Он намеренно сфокусирован на runtime-границах и точках расширения, а не на полном перечне классов и методов. За деталями уровня исходного кода используйте карту модулей и публичные справочные документы в конце файла.
Текущая модель¶
CodeGraph больше не является системой с единственным “конвейером агентов” как главной архитектурой. Текущая система состоит из нескольких согласованных плоскостей:
- Workflow-агенты маршрутизируют намерение пользователя в scenario handlers, CPG-запросы, domain plugins и форматированные ответы.
- Protocol adapters публикуют одни и те же возможности через REST, MCP, ACP, CLI и headless Codex/OpenCode automation.
- Цифровые сотрудники добавляют управляемое владение ролями, task capsules, handoffs, evidence lanes и release-readiness reporting.
- Context and memory services объединяют project scope, OpenViking resources, session memory, task memory, story capsules и repository sync state.
- Graph intelligence services читают CPG-факты через GoCPG gRPC в runtime. GoCPG является writer для project CPG DuckDB files.
flowchart LR
UI[Frontend / Dashboard] --> API[FastAPI REST]
Codex[Codex / OpenCode] --> MCP[MCP tools]
IDE[IDE / ACP client] --> ACP[ACP JSON-RPC / WS / stdio]
CLI[CLI / headless scripts] --> Services[Application services]
API --> Services
MCP --> Services
ACP --> Services
Services --> Workflow[Workflow scenarios]
Services --> Employees[Digital employees]
Services --> Context[Context and memory]
Services --> CPG[CPGQueryService]
Employees --> Tasks[TaskCapsuleService]
Employees --> Temporal[Temporal coordination]
CPG --> GoCPG[GoCPG gRPC]
GoCPG --> DuckDB[(Project CPG DuckDB)]
Context --> OpenViking[OpenViking]
Tasks --> AppDB[(Application DB)]
Temporal --> AppDB
Карта модулей¶
| Путь | Ответственность | Примечания |
|---|---|---|
src/workflow/ |
LangGraph-style orchestration, scenario routing, handlers, formatters, composition. | Новые scenario handlers должны использовать BaseHandler из src/workflow/scenarios/_base/handler.py, когда это подходит. |
src/agents/ |
Core analysis helpers и compatibility facades: analyzer, retriever, generator, interpreter, enrichment, reranking, reasoning support. | Это helper-компоненты, а не вся agent-архитектура. |
src/digital_employees/ |
Role-governed employee actions, handoffs, capability control, adaptive memory, QA/AppSec/docs/UX/support/product operations. | Task capsules остаются authoritative task state. |
digital_employees/ |
Persona identities, role relationships и runbooks. | Persona files являются governance input; runtime proof приходит из task events и evidence. |
src/context/ |
Project memory, task capsules, story capsules, OpenViking bridge, source freshness, session governance. | Разделяйте bootstrap, task, project, session, repo-sync и graph-evidence layers. |
src/mcp/ |
MCP server и tool adapters для automation. | MCP tools должны вызывать shared services/actions, а не FastAPI routers. |
src/acp/ |
Agent Client Protocol server, transports, session/thread state, approval bridge, diagnostics, hover, workflow/chat adapters. | ACP переводит protocol traffic в существующие services; это не отдельный business-logic stack. |
src/performance/agents/ |
Helpers для performance profiling, resource analysis, bottleneck models и optimization advice. | Используются в diagnostic/advisory flows; reports остаются projections над measured data. |
src/architecture/agents/ |
Helpers для architecture dependencies, layer validation, violation models и reporting. | Используются для structural analysis и remediation advice, но не являются отдельным workflow owner. |
src/security/security_agents.py |
Legacy facade security agents для scanner, data-flow, vulnerability и remediation helper classes. | Для нового runtime behavior предпочитайте shared security services и scenario handlers. |
src/api/ |
FastAPI app, routers, auth, middleware, schemas, repositories, API services. | Routers должны оставаться тонкими и использовать request-scoped ProjectContext. |
src/services/cpg/ |
Python CPG query facade и query mixins. | Runtime reads являются gRPC-first. Local DuckDB access допустим только для tests/compatibility. |
src/services/gocpg/ и gocpg/ |
GoCPG client, gRPC protocol, lifecycle и native CPG writer. | GoCPG владеет записью project CPG DuckDB. |
src/orchestration/temporal/ |
Temporal clients, workers, workflow ids, schedules, handoff/task workflow coordination. | Temporal координирует long-running work; он не является source of business truth. |
src/domains/ |
Domain plugins и domain configuration. | Domain data хранится здесь, а не hardcode-ится в workflows или routers. |
src/exports/ |
Obsidian и traceability exports для capability, PRD delivery, prompt control и evidence surfaces. | Exports являются projections, а не authoritative state. |
Workflow-Агенты¶
Workflow-выполнение открыто через role-bound вызов сценариев цифровых сотрудников.
Runtime-клиенты должны использовать invoke_role_bound_scenario или соответствующий
MCP-инструмент с явными project, namespace и task scope.
Текущий workflow-код смешанный: часть сценариев использует новую handler/formatter registry форму, часть legacy-модулей еще содержит composite workflow logic. При добавлении или существенном изменении scenario behavior:
- разделяйте intent detection, CPG reads, structured data assembly и formatting;
- предпочитайте
BaseHandlerплюс formatter modules для новых handlers; - сохраняйте benchmark-facing поля вроде
answer,retrieved_functions,cpg_results, sources и evidence; - используйте domain plugins из
src/domains/для reusable language/framework semantics; - не обходите GoCPG/gRPC CPG reads в runtime paths.
Старые core helper agents все еще существуют, но теперь это один слой внутри более широкой workflow/governance системы:
| Helper area | Типичные модули | Назначение |
|---|---|---|
| Question analysis | src/agents/core_agents/analyzer_agent.py |
Intent, query mode, keywords, domain hints. |
| Retrieval | src/agents/core_agents/retriever_agent.py, src/retrieval/* |
Semantic, structural и hybrid context lookup. |
| Enrichment | src/agents/enrichment/* |
Tag hints, domain signals, prompt formatting, fallback enrichment. |
| Reasoning support | src/agents/reasoning_support/* |
Call-chain helpers, control-flow query support и non-SQL fallback strategy selection. |
| Interpretation and quality | src/agents/core_agents/interpreter_agent.py, src/agents/result_quality/* |
Result parsing, answer generation, confidence, reranking. |
Цифровые сотрудники¶
Цифровые сотрудники - это accountable role lanes, а не просто prompt personas. Текущий реестр содержит 13 ролевых дорожек. Вместе они задают управляемый SDLC contract для development work.
| Роль | Ответственность |
|---|---|
| Анна | Планирование PRD и задач, оркестрация и отчет о готовности поставки. |
| Кира | Владение продуктом, discovery, требования и готовность входа в SDLC. |
| Сергей | Системный анализ, промышленные требования, ограничения и трассировка требований. |
| Дмитрий | Написание кода и доказательства реализации. |
| Рита | Структурное ревью. |
| Вера | AppSec-ревью. |
| Лена | Приемка качества. |
| Борис | Документация и синхронизация памяти. |
| Иван | Трассировка, пользовательские и инженерные поверхности. |
| Олег | Ответы по коду и поддержке, привязанные к источникам, и операционные заметки. |
| Ева | AI FinOps, учет токенов/стоимости и доказательства финансового контроля. |
| Марина | Жизненный цикл цифровых сотрудников, управление capability, prompt, skill и topology. |
| Глеб | Готовность runtime, DevOps/SRE и инженерия выпуска. |
Runtime pattern:
Anna-owned task plan
-> named employee task capsules and handoff chain
-> lane-specific action or tool
-> evidence refs, artifacts, checks, and events
-> Anna release-readiness status
Важные границы:
TaskCapsuleServiceявляется authoritative task state boundary.- Handoff lifecycle state хранится через task capsules и events, а не в параллельном handoff truth store.
- Codex/general AI является operator, который может вызывать governed tools; он не является accountable owner для implementation, review, QA, AppSec, docs, traceability, support, product discovery или runtime readiness.
- Финальный отчет о complete delivery требует explicit lane evidence или explicit not-applicable waiver для обязательных lanes.
- Suggested handoffs не являются executed handoffs, пока offer/accept/complete lifecycle не записан.
Ключевые implementation areas:
| Surface | Модули |
|---|---|
| Handoff contracts and governance | src/digital_employees/governance/handoffs/* |
| Shared employee actions | src/digital_employees/actions/* |
| PRD delivery planning/execution | src/digital_employees/planning/delivery/* |
| Capability and skill control | src/digital_employees/governance/capabilities/* |
| Employee memory | src/digital_employees/memory/* |
| MCP employee tools | src/mcp/tools/digital_employee_core/*, src/mcp/tools/digital_employee_runtime/* |
| REST employee surfaces | src/api/routers/digital_employees*.py |
Protocol Surfaces¶
REST, MCP и ACP должны публиковать capabilities через shared service/action boundaries.
REST router / MCP tool / ACP handler
-> shared action or service
-> context, workflow, digital employee, CPG, or repository service
-> App DB, OpenViking, GoCPG, Temporal, or external runtime
Правила:
- REST routers валидируют HTTP shape, auth, rate limits и project context.
- MCP tools разбирают tool arguments и вызывают те же actions/services, что и REST.
- ACP transports и handlers адаптируют JSON-RPC, WebSocket, stdio, sessions, approvals, hover, diagnostics и workflow/chat traffic в существующие services.
- Frontend должен показывать backend-authored readiness, reviewability, approval и chain state, а не выводить governance локально.
Project Scope и Memory¶
В runtime-архитектуре нет глобального “current project”. Project scope должен быть explicit, route-bound, workspace-derived, session-bound или actor-scoped для user, digital employee или service account.
Используйте ProjectContext и ctx.db_path в project-sensitive API, MCP, workflow,
automation и multi-tenant paths. Не доверяйте DB paths, переданным пользователем.
Memory layers:
| Layer | Назначение |
|---|---|
bootstrap_memory |
Stable repo orientation: AGENTS.md, architecture, canonical maps. |
task_memory |
Active PRDs, implementation plans, acceptance docs, task capsules. |
project_memory |
Durable governed facts and policies. |
session_memory |
Temporary session evidence and used-context traces. |
repo_sync |
OpenViking projection of repository files and comments. |
graph_evidence |
GoCPG structural facts used as evidence, not memory storage. |
OpenViking является primary context backend для repository resources, explicit sessions, memory resources и native MCP resource access. Project memory и CPG - разные системы: они могут объединяться для agent context, но ни одна из них не становится скрытым source of truth для другой.
CPG и Documentation Facts¶
GoCPG владеет CPG generation и project CPG DuckDB writes. Runtime reads должны идти
через GoCPG gRPC via CPGQueryService.
Documentation extraction является CPG-first:
- canonical documentation facts приходят из
method_documentation_facts; - production consumers используют
CPGQueryService.get_method_documentation_by_identity(...); - same-name methods в разных файлах должны оставаться distinct;
- legacy name-only comment и description APIs являются compatibility/debug surfaces.
Configuration и Limits¶
Используйте get_unified_config() и attribute access на config objects. Не hardcode-ьте
domains, DB paths, limits, thresholds, batch sizes или timeouts в feature code.
Domain-specific data должна находиться в src/domains/{domain}/config/ или reusable
domain plugin. Runtime routing и access decisions должны использовать project scope,
policy и backend-authored context.
Расширение системы¶
Добавить или изменить workflow scenario¶
- Используйте карту модулей из этого справочника и релевантный scenario code.
- Добавьте или обновите handler в
src/workflow/scenarios/.... - Используйте
BaseHandlerи formatter, если локальный scenario поддерживает этот pattern. - Используйте
CPGQueryServiceи domain plugins вместо direct DB reads или hardcoded domain knowledge. - Добавьте focused tests для scenario или затронутого helper.
Добавить protocol capability¶
- Поместите business logic в service или shared action.
- Добавьте thin REST, MCP или ACP adapters по необходимости.
- Сохраняйте REST/MCP/ACP parity, когда одна capability опубликована на нескольких surfaces.
- Сохраняйте auth, project context, task evidence, rate limiting и approval gates.
Добавить или изменить digital employee behavior¶
- Начните с Anna-owned plan/task capsule и required lane evidence.
- Держите role accountability явной.
- Пишите handoff и lifecycle state через task capsules.
- Используйте shared employee action modules для REST/MCP/Temporal parity.
- Не сообщайте full closure, пока required lane evidence не существует.
Валидация¶
Запускайте validation, соответствующую измененной поверхности. Не запускайте pytest ..
| Изменение | Focused validation |
|---|---|
| Docs/catalog | python scripts/generate_development_doc_index.py --write и python scripts/check_development_doc_catalog.py --json |
| SDLC/operator contract | python scripts/check_sdlc_operator_contract.py --json |
| Task capsules | pytest tests/unit/context/test_task_capsule_service.py -v |
| Digital employee handoffs | pytest tests/unit/digital_employees/test_handoff_contracts.py tests/unit/digital_employees/test_handoff_orchestrator.py -v |
| Digital employee MCP | pytest tests/unit/mcp/test_digital_employee_tools.py -v |
| Digital employee REST | pytest tests/unit/api/test_digital_employees_router.py -v |
| Surface hardening | pytest tests/unit/security/test_surface_authz_audit.py -q плюс affected API/MCP/ACP tests |
| CPG/gRPC runtime | pytest tests/unit/services/test_gocpg_grpc_transport.py -v плюс affected CPG query tests |
| Workflow scenarios | Scenario-specific tests under tests/workflow/ или focused tests/unit/... targets |
| Frontend surfaces | cd frontend, затем focused checks вроде npm run test:e2e и npm run check:i18n:ru, если менялись UI text/routes |