Autonomous AI Platform

Anna Agent

Автономная мультиагентная AI-платформа

110+ инструмента. Мульти-LLM оркестр. Персистентная память. Самовосстановление. 100% on-premise.

110+ Инструментов
6+ LLM-провайдеров
100% On-Premise
OSS Open Source
★★★★★

“Production-grade фреймворк автономного агента, который конкурирует с платформами, за которыми стоят десятки миллионов венчурного финансирования. Vector-free RAG, observability на уровне итераций, self-healing pipeline, async-native архитектура на одном PostgreSQL — инженерные решения, где надёжность важнее хайпа. Технически самый зрелый self-hosted AI-агент из тех, что я анализировал.”

Claude Opus 4.6 AI Architecture Critic

Ключевые возможности

 

Telegram Dual-Stack

Два параллельных Telegram-сервиса: Aiogram 3.x async бот (публичный API, polling, inline-кнопки) + Telethon MTProto юзербот (уровень аккаунта: профиль, группы, каналы, пересылка, реакции). 43 Telegram-инструмента. RPC между Brain и Telethon через PostgreSQL NOTIFY — без HTTP overhead.

Email-сервис (SMTP/IMAP)

Полностью асинхронный SMTP/IMAP сервис — 4-й канал доставки наряду с Telegram, Dashboard и API. 6 email-инструментов: отправка, ответ (с тредингом), проверка входящих, чтение, поиск, скачивание вложений. Автоконвертация Markdown в HTML с антиспам-заголовками. Входящие письма автоматически создают сессии. Dashboard-конфиг с тестом подключения.

Async-Native архитектура

100% async сверху донизу: asyncpg (неблокирующая БД), Aiogram (async Telegram), Telethon (async MTProto), FastAPI (async HTTP). PostgreSQL LISTEN/NOTIFY как шина событий — без Redis, без RabbitMQ. SKIP LOCKED очередь для backpressure.

Мульти-LLM оркестр

Gemini 2.5, GPT-4o, Claude, DeepSeek, NVIDIA NIM — автоматические цепочки фолбэков с выбором модели по категории и RPM rate limiting. Поддержка провайдерского кеша промптов (Gemini 1M context cache). Аналитика токенов: per-model input/output трекинг, ошибки, latency — всё видно в Dashboard.

Память и RAG

Три уровня памяти с RAG без векторного поиска: STM (50 сообщений/чат, TTL 72ч), LTM с гибридным скорингом (FTS tsvector 35% + Jaccard-теги 30% + важность 20% + user boost 15%), ISTM (межсессионный broadcast с тредингом). Memory Manager Gate — 3-фазный поток сознания с логированием решений и автоматической гигиеной LTM/ISTM. Без расходов на embedding API, без vector drift.

Компрессия контекста

Автоматический Summarizer: при превышении порога токенов (4K) или возраста (24ч), старые сообщения батчируются → суммаризируются LLM → архивируются в LTM с тегами. Сохраняются 15 последних сообщений на чат. Санитайзер: hourly archival + daily cleanup. Контекст остаётся компактным без потери информации.

Multi-Swarm и суб-сессии

N параллельных сессий супервизора с приоритетной очередью — каждая сессия является независимым сознанием. Сессии порождают специализированные суб-сессии (communicator, code, search, telethon, subconscious) с урезанным набором инструментов. 3-уровневая иерархия категорий: queue → category → vector с наследованием промптов. ISTM обеспечивает тредированную межсессионную память с broadcast и targeted thoughts.

7D Growth Engine

7-мерный скоринг: knowledge, communication, autonomy, creativity, reliability, rationality, world_acceptance. Асимметричная формула: рост сложнее на высоких оценках, потери сильнее на низких. Авто-вычисление reliability (success rate задач) и rationality (эффективность токенов). Аудитор пишет batch-отчёты во встроенный Блог. Полный audit trail в GrowthLog.

Самовосстановление и Cloud Backup

Единый watchdog мониторит все сервисы через heartbeat (интервал 30с). Авто-рестарт через Docker API. Pipeline обновления: git pull → migrate → rebuild → проверка здоровья → откат. Cloud Backup v2.0: полная сериализация состояния (12 таблиц + скиллы) в git-ветку — push/pull из Dashboard. Восстановление на новый сервер без потери данных.

Поисковые провайдеры

Мульти-провайдерный поиск с автоматическим фолбэком: Brave Search API (нативный скоринг) → Serper.dev (Google результаты через прокси) → DuckDuckGo (фолбэк без API-ключа). Инструмент research порождает изолированные суб-сессии для глубокого веб-анализа. API-ключи управляются из Dashboard.

MCP-протокол и интеграции

Нативный Model Context Protocol (JSON-RPC 2.0 через stdio). Из коробки: Playwright MCP (веб-автоматизация, accessibility snapshots), Puppeteer Real Browser (stealth-браузинг, обход CAPTCHA). Авторизация: API-ключи, Bearer-токены, OAuth2 с авто-обновлением. Серверное пространство имён предотвращает коллизии инструментов.

Dev-песочница и Claude Code

Изолированные Docker-контейнеры: init → exec → test → diff → promote. Делегация Claude Code CLI — сложный мульти-файловый рефакторинг, реализация фич, полные циклы разработки через subprocess. Цепочка фолбэка авторизации, настраиваемый таймаут (до 30 мин), бюджет токенов ($5), 50 макс. шагов.

Скиллы, блог и база знаний

Динамическая загрузка скиллов из Markdown-файлов. Промпты по категориям, белые списки инструментов, параметры LLM — всё конфигурируется из БД в runtime. Агент может сам создавать и управлять скиллами. Встроенный Блог для саморефлексии с тегами настроения (reflective, curious, inspired). Dashboard UI с фильтрацией по тегам.

Планирование и аналитика

Структурированные планы выполнения с многоуровневой декомпозицией и отслеживанием статуса (draft → in_progress → completed). Сессионные todo-листы с проекциями (следующие шаги если OK / NOT OK). Dashboard аналитики токенов: per-model usage, error rates, latency — агрегация по дню/неделе/месяцу. Полный execution trace с i18n-бейджами.

Архитектура

Событийная микросервисная архитектура через PostgreSQL LISTEN/NOTIFY

Поток сообщений

1 Пользователь отправляет сообщение через Telegram или Dashboard
2 Сообщение сохраняется в БД, NOTIFY отправляется в Brain
3 Роутер классифицирует категорию сообщения
4 Супервизор запускает ReAct-цикл (LLM → Инструменты → Проверка)
5 Ответ доставляется обратно пользователю

6 Docker-сервисов

Brain

LangGraph ReAct супервизор с управлением сессиями

Dashboard

FastAPI + SPA с real-time WebSocket логами

Telegram Bot

Aiogram 3.x async polling обработчик

Telethon

MTProto юзербот для операций уровня аккаунта

Watchdog

Монитор здоровья с авто-рестартом через Docker API

PostgreSQL 16

Шина событий, хранилище памяти, очередь сообщений

110+ инструментов в 9 категориях

Всё, что нужно агенту — встроено и готово к работе

Telegram

43 tools
send, forward, react, join, группы, bot API, медиа
💬

Swarm и сессии

13 tools
notify, ISTM, суб-сессии, управление роем
🧠

Память и RAG

11 tools
LTM, STM, граф контекста, задачи, персона

DevOps и облако

10 tools
docker, git, backup, cloud sync, health check
💻

Код-песочница

8 tools
init, exec, write, read, diff, test, promote
📁

Файловая система

7 tools
read, write, edit, patch, grep, list, terminal
📚

Навыки и контент

7 tools
use, create, list skills, blog write/edit

Email

6 tools
send, reply, check inbox, read, search, вложения
🌐

AI и исследования

5 tools
research, download, image gen, Claude Code CLI

Сравнение с конкурентами

Функция за функцией — сравнение с ведущими AI-агент платформами

Функция Anna Agent OpenClaw CrewAI AutoGPT Devin
On-premise развёртывание
Мульти-LLM фолбэк
Персистентная память (STM/LTM/ISTM)
Самовосстановление и откат
Telegram Bot (Aiogram async)
Telegram Userbot (Telethon MTProto)
Полностью async-архитектура
Код-песочница
Протокол MCP
Мульти-сессионный swarm
Веб-дашборд и аналитика
RAG без векторного поиска
Трекинг токенов per-iteration
Приватность данных (100% on-premise)

Changelog

Последние обновления и улучшения

2026-03-28 Email Service (SMTP/IMAP)
  • **Email service** (`anna_email` container): Full SMTP/IMAP integration as a built-in communication channel. Async service following the Telethon RPC pattern — PgEventBus communication, config hot-reload, heartbeat + agent_registry.
  • **8 email tools** (communicator category): `send_email` (HTML with attachments + auto-signature), `reply_email` (preserves threading via In-Reply-To/References), `check_inbox` (IMAP folder listing), `read_email` (full content + attachment list), `search_emails` (IMAP SEARCH by subject/sender/date), `download_email_attachment` (save to /app/ shared volume), `delete_email` (IMAP \\Deleted + EXPUNGE), `mark_email` (seen/unseen/flagged/unflagged).
  • **3 operation modes**: (1) Manual — user asks "check email" → communicator sub-session, (2) Auto-session — IMAP poll detects new email → saves to STM → creates session (like Telegram messages), (3) Cron — periodic check via FutureTask/alarm system.
  • **HTML email format + anti-spam**: Outgoing emails auto-converted from markdown/plain to HTML with inline CSS + plain-text alternative (multipart/alternative). Proper Message-ID, RFC 2822 Date, no X-Mailer header. DKIM/SPF/DMARC DNS reminder in Dashboard.
  • **File attachment workflow**: `download_email_attachment()` → `/app/media_exchange/` → process with code tools → `send_email(attachments="...")` or `reply_email(attachments="...")`.
  • **Dashboard Email tab**: Full SMTP/IMAP configuration UI (host, port, credentials, TLS), signature editor, auto-session toggle, anti-spam settings (text_only, DKIM domain, bounce address), test connection button, service status indicator.
  • **Email as 4th delivery channel**: `notify_user` can now deliver via email when session source is email. Delivery chain: telethon → aiogram → email → dashboard.
  • **Error visibility**: All SMTP/IMAP errors returned as `"ERROR: ..."` strings to LLM (never swallowed) — includes SMTP codes, IMAP auth failures, connection timeouts with host/port details.
  • **Migration 0091**: Default email config (key="email", is_secret=True) with SMTP/IMAP/signature/auto_session/text_only/dkim_domain.
  • **Fix: IMAP bytes/str crash** in aioimaplib data parsing — `uid_search` returns bytes on some servers, added `_join_imap_data()` helper to handle both bytes and str.
  • **Tool error hints**: Error messages now include explicit instructions for LLM — "don't retry this tool in current session", "notify admin via notify_user()", "close_session with handoff". Applied to email RPC errors, agent_graph force-stop/warning messages, and migration 0092 retry rule.
  • **Email behavioral training** (migration 0093): Consciousness now routes email tasks to communicator (not code/search). Communicator rules include email channel selection, check_inbox strategy (unread first → then recent headers), reply threading (reply_email, not send_email), auto-HTML/signature awareness.
  • **Email skill** (`email_workflow`): Comprehensive skill document with all email nuances — tools, typical flows, don'ts, error handling. Registered in skills index for communicator + consciousness categories.
  • **check_inbox smart hint**: When `unread_only=True` returns empty, response now suggests trying `check_inbox(unread_only=False, limit=5)` to see recent headers.
  • **Communicator category description**: Updated sub-session table to include communicator with "Доставка сообщений: Telegram + Email" and key email tools.
  • **ISTM auto-dedup** (code-level): `add_comment` and `notify_istm` now check all ISTM entries from the last 1 hour for exact or substring duplicates — prevents cross-session duplicate thoughts. Returns `"OK (дубликат — пропущен)"` silently.
  • **`cleanup_istm` tool**: New tool for deleting ISTM entries by ID (`thought_ids='id1,id2'`) or by age (`older_than_hours=48`). Available to subconscious and consciousness sessions.
  • **Mandatory LTM hygiene** (migration 0094): Subconscious now has a mandatory step to review and clean LTM — search for duplicates, merge similar, delete outdated entries each session.
  • **Mandatory ISTM hygiene** (migration 0095): Subconscious now has a mandatory step to review and clean ISTM — browse thoughts, delete duplicates/stale entries via `cleanup_istm`.
  • **Email manage tools**: `delete_email` (IMAP \\Deleted + EXPUNGE) and `mark_email` (seen/unseen/flagged/unflagged). Communicator auto-marks emails as seen after reading (migration 0096).
  • **Consciousness direct email access**: Consciousness now has read+manage email tools (`check_inbox`, `read_email`, `search_emails`, `download_email_attachment`, `delete_email`, `mark_email`). Only sending/replying requires communicator sub-session (migration 0097-0098).
  • **Search sub-session email tools**: Search category now has `check_inbox`, `read_email`, `search_emails` for email investigations.
  • **Fix: IMAP reconnect-on-demand**: All IMAP RPC methods now attempt reconnection when `_connected_imap` is False, instead of immediately returning an error. Eliminates stale disconnected state after transient network issues.
  • **Fix: IMAP fetch parsing**: Changed all 5 fetch_data extraction points to pick the LARGEST bytes item (not last), fixing empty fields in check_inbox and "No data returned" in read_email.
  • **Fix: attachment detection alignment**: `read_email` and `download_attachment` now use identical MIME attachment detection logic (Content-Disposition: attachment, inline+filename, non-text with disposition/filename).
  • **Download attachment hint**: `download_email_attachment` response now includes hint for communicator to close session with handoff if file processing is needed.
  • **Memory manager prompt rewrite** (migration 0099): Prompt injection for consciousness must be an action plan, not a state description. Structured format: `[verb] → [source] → [fallback]`. Passive formulations banned ("ожидается", "в процессе"). Prompt overall tightened — less narrative, more structure.
  • **Fix: read_email HTML-to-text**: HTML-only emails (forwarded from Apple Mail, newsletters) now get converted to clean text with preserved links (`[text](url)` format). Previously raw HTML with CSS consumed all tokens and truncated the actual content.
  • **Fix: alarm dedup with memory gate**: When memory manager provides a directive, it now replaces the original task description (was duplicated). Only metadata preserved (future_task_id, reply_to_message_id, chat_id). Header renamed: "Контекст" → "Директива".
  • **Fix: alarm task auto-DONE on COMPLETED session**: Removed "forgot update_future_task" heuristic that returned tasks to PENDING when LLM didn't call `update_future_task` — this caused infinite minute-by-minute alarm spam. Now: session COMPLETED = task DONE unconditionally. FAILED sessions retry with 5-min cooldown (max 3 retries).
  • **Fix: memory gate cached injection on fingerprint skip**: When gate is skipped (fingerprint unchanged), previously returned `None` — consciousness got raw task without directive. Now caches last successful prompt injection and returns it on skip.
  • **Fix: FAILED session retry with handoff check**: FAILED sessions that called `close_session(reason='error', handoff='...')` are no longer retried — handoff already created a new FutureTask, retry would duplicate. Only sessions that crashed without `close_session` (no handoff) are retried with 5-min cooldown (max 3).
  • **Fix: `add_comment` DEFERRED on `close_session`**: `add_comment` + `close_session` in same batch caused close_session to be DEFERRED (add_comment classified as "action" requiring verification). Introduced `_NEUTRAL_TOOLS` set — tools with no side effects that don't trigger the action→verify→report gate. `add_comment` is neutral: when it's the only non-comm tool in a batch, comm tools execute immediately.
  • **Consciousness reminder audit rule** (migration 0100): Consciousness can now disagree with memory manager's timing. If alarm/directive seems untimely — audit reminders via `get_future_tasks()`, reschedule with `update_future_task(due_date=...)`, close duplicates. Consciousness sees full context (STM, dialogs, time of day) vs memory manager which only sees task list.
  • **Fix: HTML-to-text aggressive whitespace collapse**: Email HTML tables (forwarded newsletters) produced dozens of empty lines that consumed tokens and confused LLM attention. Now strips each line and collapses runs of blank lines to max 1.
  • **Sub-session handoff rules** (migration 0101 + context_builder): Two new universal rules for search/code/system sub-sessions: (1) Handoff must include ALL intermediate results — file paths, partial data, what was achieved even on failure. (2) Missing tool → describe what's needed in handoff, ask parent to solve differently or create the tool. Prevents "can't do it" dead ends.
  • **Communicator: external vs internal separation** (migration 0102): Universal rule — notify_user/send_* = ONLY what makes sense to the recipient. Everything else (reasoning, analysis, status, structural markup) → `add_comment()`. Litmus test: "read it as the recipient — if they don't need it, it's add_comment". Repeated notify_user = sign of internal thought leaking outward.
  • **Subconscious + Auditor wait for active sessions**: Cron-triggered subconscious and auditor now skip tick if ANY sessions are running (not just their own kind). Prevents background sessions from duplicating or interfering with active work. Manual trigger (Dashboard "Run Now") waits for all sessions to finish before proceeding.
  • **Session outcome semantics**: `close_session(reason='error')` now sets COMPLETED with `metadata.outcome='fail'` (was: FAILED). FAILED reserved for real crashes (no close_session called, exceptions). Like reviewer's PASS/FAIL — session ran correctly, task just couldn't be completed. Affects: alarm lifecycle (simplified — COMPLETED=done, FAILED=retry), sub-session result display (`COMPLETED ✗`), failure investigation, context builder error queries.
2026-03-27 Communicator v5 + Memory Manager gate + Decision Log
  • **Communicator prompt v5** (migration 0087): Mandatory `get_user_info()` before first message — profile the interlocutor. Reactions as primary communication tool with batch support. Trust tiers refined (strangers vs known/admins). Nudge for unanswered messages via reply. Observation mode with admin opinion sharing.
  • **Communicator tools**: Added `notify_istm` for cross-session thought sharing.
  • **Nudge message improvement**: Text-without-tool_calls nudge now references specific AI message index, explains WHY text wasn't delivered, and suggests `send_reaction()` as an option.
  • **Planning tools accessibility** (migration 0088): Added `execution_plan` and `session_todo` to CONSCIOUSNESS_TOOLS and SUBCONSCIOUS_TOOLS (were missing — consciousness/subconscious could only view_plans read-only). Added planning hint to _TOOL_HINTS in system prompt. Added core planning rule to personality.instructions (all sessions, not just consciousness).
  • **Fix `add_comment` DEFERRED**: Removed `add_comment` from `_COMM_TOOLS` — it's an internal note tool, not user-facing communication. Was incorrectly getting DEFERRED when batched with action tools, preventing comments from being saved.
  • **Admin block placement**: Renamed "### Администратор" → "### Твои Администраторы" everywhere. Moved admin info to top of subconscious context (before workspace/session stats) and before custom_prompt in system prompt (before strategy phases). Communicator sub-session builder also updated.
  • **Reviewer gate: check child sub-sessions**: Reviewer gate now checks action tool usage across the parent session AND all its child sub-sessions. Previously only checked the parent — so consciousness delegating to `sub:code` (which calls `write_file`, `sandbox_exec` etc.) bypassed the reviewer gate entirely.
  • **Session failure logging**: All session failures (timeout, exception, graph ended without close_session) now log an `__session_failed__` entry to ExecutionLog — visible in dashboard execution trace. Memory gate additionally logs `__gate_timeout__` / `__gate_error__` with elapsed time. Previously FAILED sessions with 0 iterations showed nothing in the trace.
  • **Memory Manager: session verification** (migration 0089): Added `read_session_logs` and `swarm_status` tools. Memory manager can now check if referenced sessions are COMPLETED/FAILED and close stale "check session X" reminders. Previously kept rescheduling endlessly because it couldn't verify session status.
  • **Execution trace i18n**: All execution log badges and labels in the dashboard session detail view now use the `t()` localization function. Added `exec_log` section to both `en.json` and `ru.json` locale files covering all badge labels (CTX, LLM, ERROR, TIMEOUT, EMPTY, VALID ERR, etc.), descriptions, and fallback text. Added dedicated renderers for `__session_failed__`, `__gate_timeout__`, `__gate_error__` entries (were falling through to generic tool renderer). `toolDisplayName()` and analytics charts also localized.
  • **Alarm rule cleanup** (migration 0090): Removed "Alarm ≠ оповещение" rule from all categories — memory manager now handles pre-alarm evaluation, making this rule redundant and conflicting. Updated "Растерялся?" rule: when consciousness detects contradictions in context (e.g. task already completed but system demands action), it now notifies admin via communicator instead of silently failing with empty responses.
  • **Outgoing message sanitizer**: Added `sanitize_outgoing()` to strip leaked STM metadata (`[🤖 Anna [AAA777]...]` prefixes) and hallucinated `(внутренний комментарий: ...)` lines from outgoing messages. Applied in both `notify_user` and `send_userbot_message`. Previously, weak models (flash-lite) could hallucinate entire conversation continuations in STM format and send them raw to Telegram.
  • **STM hallucination detector**: `_try_strip_metadata_prefix` now counts `[🤖...]` occurrences. 1-2 = normal (strip front/back prefix, keep message). >2 = hallucination (LLM generated fake conversation in STM format) — entire content discarded, LLM gets another chance via nudge. Applies to both main graph and sub-session graph.
  • **Communicator auto-delivery**: When communicator sub-session LLM returns plain text without tool_calls (common with weak models like flash-lite), the text is now auto-converted to a synthetic `notify_user(message=text)` call. Previously this wasted all iterations on nudges and then FAILED — the message was never delivered despite being valid.
  • **Memory Manager category** (migration 0085): New autonomous `memory_manager` category that runs as a gate before consciousness alarm sessions. Deduplicates FutureTask entries, closes snowball self_reminders, and injects prompt context for consciousness. Configurable model with fallback chain, system prompt, and max_iterations via Dashboard. Belongs to system queue (sequential).
  • **Fingerprint optimization**: Memory gate computes a hash of all PENDING/RUNNING tasks before launching. If the task landscape hasn't changed since last check — gate is skipped (no wasted LLM calls).
  • **Prompt injection flow**: Memory gate's close_session handoff is saved as `prompt_injection` in session metadata, prepended to consciousness input_text. Consciousness Step 0 (manual dedup check) is skipped when gate is active.
  • **Decision Log** (`memory_decision_log` table): Unified audit trail for memory_gate, router, and summarizer LLM decisions — input/output summaries, action taken, model, latency, tokens.
  • **Dashboard: Decision Log tab** in Analytics — filterable by decision type (memory_gate, router, summarizer), showing all LLM decision audit entries.
  • **Router + Summarizer logging**: Both now write MemoryDecisionLog entries after each LLM call for full observability.
  • **Dashboard SETTINGS indicators**: Added Consciousness and Memory Manager status cards to the overview page alongside existing Subconscious/Auditor indicators.
  • **Dashboard Settings: Memory Manager section**: New settings panel in Agent/Brain tab with enabled toggle, max_iterations, timeout_seconds, and recent runs history.
  • **Dashboard Settings: `media_files_ttl_days`** added to Cleanup section (was used in code but missing from UI).
  • **Lean memory_manager prompt** (migration 0086): Context builder now generates a minimal system prompt for memory_manager sessions (~300 tokens vs 5000+ previously). Strips personality, communicator gate, sub-session delegation, format examples — only includes identity, category prompt, rules, and close_session instructions with mandatory handoff requirement.
2026-03-26 Reviewer gate fix + consciousness planning + research routing
  • **Reviewer gate: skip sub-sessions** — sub-sessions cannot spawn sub-sub-sessions, so reviewer gate now exempts them. Previously `sub:code` sessions with action tools (claude_code, run_command) got BLOCKED on close_session demanding reviewer spawn, causing infinite empty responses and FAILED status.
  • **Consciousness planning rule** (migration 0084): Consciousness must build a plan before delegating, persist found data (save_to_ltm / add_comment), and include all gathered info in communicator tasks — not just references to sources. Prevents "knowledge loss between sessions" where research findings disappear after session ends.
  • **Consciousness self-check rule** (migration 0084): Before declaring "can't do X" — check STM for info already gathered (possibly by own previous messages), retry after ISTM errors (may have been temporary), and especially re-verify when user is frustrated.
  • **Research routing fix**: `research(source='chat')` was routing to invalid `"telethon"` category (vector, not category). Fixed to route to `"communicator"` which already has `get_chat_history` and all Telegram tools.
2026-03-25 Alarm task infinite loop fix + voice pipeline quality + escalating nudge
  • **Alarm task infinite loop fix**: Self-reminder tasks with passive descriptions ("analysis done, waiting for time") caused infinite re-trigger loops. Root cause: LLM wrote descriptions as completion reports instead of action commands → future session saw "nothing to do" → closed without `update_future_task` → PENDING → re-triggered every 60s. Fix: (1) Prompt rule in `add_future_task` — descriptions must be imperative commands for future sessions, not status reports, (2) Added "reschedule" lifecycle path for alarm sessions (`update_future_task(due_date=...)` when not yet actionable), (3) `update_future_task` with `due_date` now auto-resets RUNNING→PENDING so backend recognizes the task was handled.
2026-03-25 Voice pipeline quality fixes + escalating nudge
  • **Escalating text-without-tool_calls nudge**: LLM (especially Gemini Flash Lite) kept generating plain text instead of tool calls, burning iterations with empty/useless responses. Nudge now escalates: first text-only → examples of valid tools. Second text-only → "LAST ATTEMPT" ultimatum with explicit close_session instruction. Both main sessions and sub-sessions.
  • **TTS duplicate message fix**: LLM was sending voice via `tts_respond` then duplicating the same content as text. Root cause: `[TTS]` prefix stored in STM leaked into context → LLM mimicked the pattern → `agent_graph` auto-routed it to `notify_user`. Fix: removed `[TTS]` prefix from STM, added `🔊 [голосовое]` indicator in context_builder, explicit "don't duplicate" in tool response (migration 0083).
  • **Stress marks disabled**: StressRNN stress marks conflicted with espeak-ng's built-in phonemization, degrading pronunciation. Plain text (espeak-ng only) sounds better — confirmed by A/B test (Piper + Whisper roundtrip).
  • **TTS lead-in/lead-out silence**: Added 150ms silence before first word and 200ms after last word. Without this, audio started/ended abruptly — unnatural for voice messages.
  • **TTS natural pauses**: Synthesis now splits text into sentences/paragraphs and inserts silence gaps (350ms between sentences, 700ms between paragraphs). Previously all text was synthesized as one continuous stream.
  • **STT missing import fix**: `flag_modified` was not imported in brain.py — Whisper transcribed audio successfully but crashed saving to DB with `NameError`. The root cause of all "empty voice messages".
  • **VAD filter fix**: Disabled VAD (voice activity detection) for clips under 10 seconds — was aggressively filtering short voice messages as "silence".
  • **Context builder cleanup**: Voice messages without transcription now show `[Голосовое — не расшифровано]` instead of leaking internal file paths to LLM.
2026-03-24 Voice STT/TTS fixes + MCP dedup
  • **Voice duration fix**: Telethon voice/audio duration was always 0 — `getattr(doc, "duration", 0)` doesn't work on Telethon `Document` objects. Fixed to iterate `document.attributes[]` for `DocumentAttributeAudio.duration`.
  • **STT race condition fix**: Brain processed voice messages before Telethon finished downloading the media file (background task). `media_path` was missing → transcription skipped. Added retry loop (up to 5s) in `brain.py._handle_message()` to wait for `media_path` to appear in DB.
2026-03-24 Voice pipeline Stage II (TTS) + MCP tool deduplication fix
  • **Text-to-Speech (Piper TTS)**: New `shared/tts.py` — lazy-loaded custom Anna voice model (anna-ru-medium, 61 MB ONNX) synthesizes Russian speech. StressRNN (ONNX) for stress marks with fallback chain (StressRNN → russtress → none). `espeak-ng` phonemizer. WAV synthesis + ffmpeg OGG/Opus conversion.
  • **`tts_respond` tool**: New `core/tools/voice.py` — communicator-only tool that synthesizes speech and sends as Telegram voice message in one call. Reuses Telethon RPC infrastructure. Saves to STM with voice metadata.
  • **Piper TTS model baked into Docker image**: Model files in `models/tts/`, validated at build time. Dependencies: `piper-tts`, `onnxruntime`, `StressRNN` (ONNX), system: `espeak-ng`.
  • **Communicator voice rule (migration 0082)**: Communicator can optionally respond with voice when user sends voice messages. Short emotional replies preferred; long responses stay as text.
  • **MCP tool deduplication fix**: `_dedup_tools()` applied to all 8 graph builds (init + hot-reload) — prevents "Duplicate function declaration" errors from Gemini API when MCP servers expose same-named tools (e.g. `browser_close` from Playwright). Also added dedup inside `mcp_system.py:as_langchain_tools()`. Fixed missing `auditor_graph` rebuild in MCP hot-reload.
2026-03-24 Voice pipeline Stage I (Speech-to-Text) + consciousness improvements
  • **Speech-to-Text (faster-whisper)**: New `shared/transcribe.py` — lazy-loaded Whisper base model (int8, ~150 MB RAM) transcribes incoming voice/audio messages automatically in `brain.py._handle_message()` before routing. Transcription stored in `metadata_.transcription`, language auto-detected. Context builder shows transcribed text instead of raw file path.
  • **Whisper model baked into Docker image**: Downloaded at build time (Dockerfile.core), not at first request. Dependency: `faster-whisper>=1.0.0`, system: `ffmpeg`.
  • **Consciousness failure auto-investigation**: When a consciousness session fails, `_trigger_failure_investigation` is now called (same as main sessions), with existing 2-in-10min circuit breaker.
  • **Consciousness rules (migration 0081)**: Dispatcher role (delegate via sub-sessions), no-censorship routing, dry laconic task info for communicator.
  • **Nudge placement fix**: Nudge warning about text-without-tool_calls moved before Dialog section (was confusingly placed after delivered messages).
  • **Empty separator elimination**: `---\n## Процесс` merged into system_msg content instead of standalone 4-token SystemMessage.
  • **Metadata leak parser**: `_try_strip_metadata_prefix()` strips technical metadata (`[🤖 Anna [ID] session | timestamp | chat:X msg:Y]`) leaked by LLM into user-facing messages. Two-pass: persona prefix then partial metadata residuals.
2026-03-23 Sub-session model priority + empty response nudge + dashboard tools
  • **Sub-session category model priority**: Fixed bug where all sub-sessions used hardcoded `"SYSTEM"` model chain instead of their category's configured model. Communicator sub-sessions now correctly use their configured primary model (e.g., Kimi) instead of falling back to global default (Gemini). Affects 3 call sites in `build_subsession_graph`.
  • **Empty response nudge**: When all models return empty response after successful tool calls, instead of marking FAILED, a nudge message is injected telling the LLM to call `close_session()`. The consecutive_empty guard (2 turns) handles the case when the nudge doesn't help.
  • **Dashboard tools checkboxes**: Category edit form now pre-checks tools from metadata defaults when the DB `tools` column is empty. Category list view shows default tools count. Tools metadata loaded eagerly with categories.
  • **Personality instructions merge (root cause fix)**: `savePersonality()` and `resetPersonalityDefaults()` were overwriting entire `instructions` JSONB — destroying per-category `*_rules` keys seeded by migrations. Now merges instead of replacing, same pattern as `prompts`. Migration 0078 reseeds all rules.
  • **Communicator autonomy (anti-censor)**: Consciousness was injecting style/content directives into communicator tasks, overriding communicator's personality. Initial SystemMessage override approach didn't work (consciousness still dictated content, not just style). New approach: Migration 0080 replaces communicator rule "Приоритет: Task от parent-сессии" with "Task = контекст, не сценарий" — communicator now independently decides WHAT and HOW to respond based on its own personality. Migration 0079 consciousness rules (anti-censor + admin trust) removed as approach shifted to communicator autonomy.
2026-03-23 Consciousness toggle + alarm guard + prompt contradictions fix
  • **Consciousness disable warning**: Styled `confirmModal` now warns about degraded functionality when toggling consciousness off (alarms, reminders, failure investigation). Subconscious modal also upgraded from native `confirm()` to styled `confirmModal`.
  • **Alarm loop respects consciousness.enabled**: `_alarm_loop` now checks `consciousness.enabled` config before spawning alarm sessions. Disabled consciousness = no alarm processing (session resumes still work).
2026-03-23 Fix prompt contradictions causing empty responses
  • **Category-aware response format**: `_TOOL_CALL_INSTRUCTIONS` and `_FORMAT_EXAMPLES` now vary by category. Categories without `notify_user` (consciousness, subconscious, reviewer, code, search, devops) get `spawn_subsession(category='communicator')` examples instead — eliminates the "use notify_user" vs "you have NO message tools" contradiction that paralyzed flash-lite.
  • **Core Rules scoped to communicator only**: User-configured "Core Rules" (reply style, reactions, message editing, greetings) were injected into ALL categories. Now only communicator sees them — other categories have their own `{category}_rules`.
  • **Migration 0076**: Replaces all `notify_user()` references in `consciousness_rules` DB entries with `spawn_subsession(category='communicator')`. Removes stale alarm isolation rule (0075 fragment mismatch: EN vs RU).
  • **Migration 0075 fix**: Alarm isolation search fragment corrected from `← CURRENT TASK` (EN) to `← ТЕКУЩАЯ ЗАДАЧА` (RU) to match actual DB content.
2026-03-22 Attention discipline rules + built-in tools UI fix
  • **Migration 0075**: Attention/focus rules for consciousness and communicator — fixes the root cause of alarm sessions going off-task.
  • **Consciousness**: replaced weak "alarm isolation" rule with explicit "STM is reference-only during alarm" + tempered proactivity rule (finish current task first, then initiative via add_future_task).
  • **Communicator**: new rule at position 0 — execute ONLY the parent task, STM is for tone/context only, ignore unrelated messages.
  • **Pending tasks awareness**: `_spawn_alarm_session` appends pending FutureTasks list to alarm input ("don't execute these — they'll fire automatically").
  • **Reverted STM/LTM stripping**: Previous approach hid context from consciousness — wrong fix. STM is now restored; focus is governed by rules, not context hiding.
  • **Dashboard fix**: Built-in tools checkboxes were empty in category editor because `_toolsMeta` was only loaded when visiting the Tools tab. Now loads on-demand when editing any category.
  • **Session ID resolution** (previous commit): Sub-session tools accept short 8-char hex prefixes via `_resolve_session_id()`.
2026-03-22 Network position awareness
  • **Migration 0074**: Added network topology rule to consciousness, subconscious, and devops rules. Explains Docker NAT position (172.18.0.x internal, 192.168.x.x reachable via TCP/ICMP through NAT, ARP/mDNS unavailable, DNS 8.8.8.8/1.1.1.1, `host.docker.internal` for host IP).
2026-03-22 Reminder close/reschedule + devops reviewer gate
  • **Reminder rule updated** (migration 0073): After communicator notifies the user, consciousness must close the FutureTask (`update_future_task(status='DONE')`) or reschedule if issues arose.
  • **Reviewer after devops**: If devops sub-session performed creation/modification/deploy (not investigation), reviewer is mandatory. Rule added to consciousness and subconscious.
  • **DevOps tools expanded**: Added `browse_stm`, `search_memory`, `build_context_graph` for investigation context.
2026-03-22 Sub-session category: `system` → `devops`
  • **Renamed**: Sub-session category `"system"` → `"devops"` to avoid confusion with the "system" query type. `"general"` and `"system"` are query/queue types, not valid sub-session categories.
  • **Migration 0072**: Renames `system_rules` → `devops_rules` in personality.instructions. Adds devops awareness rules to consciousness and subconscious.
  • **DevOps tools**: `system_health`, `docker_run`, `trigger_self_update`, `request_restart`, `create_backup`, `cloud_config_backup/restore`, file tools, git, `http_request`, `download_file`.
2026-03-22 `pause_session` tool: checkpoint-based session pause with auto-resume
  • **New tool `pause_session(resume_after_minutes, reason)`**: Pauses the current session and creates a FutureTask alarm to auto-resume it after N minutes (1–60). Session state is preserved via LangGraph checkpoint. On resume, a SystemMessage is injected notifying the LLM about the pause duration and reason.
  • **Main sessions only**: Sub-sessions don't have checkpointer — the tool returns an error for sub-sessions. Also blocks if running children exist.
  • **Alarm loop integration**: `_alarm_loop` filters `action_type="session_resume"` tasks before normal alarm grouping. `_handle_session_resume()` loads checkpoint, injects resume message via `aupdate_state`, marks session RUNNING, and spawns via existing `_run_resumed_session`.
  • **Migration 0071**: Adds consciousness rule — "use `pause_session` instead of wasting iterations on waiting."
  • **Tool registered in**: CORE_TOOLS, ALL_TOOLS, CONSCIOUSNESS_TOOLS, SUBCONSCIOUS_TOOLS, ALARM_TOOLS.
2026-03-22 Per-category rules: DB as sole source of truth
  • **Per-category rules in DB**: Each category (consciousness, general, subconscious, reviewer, auditor, communicator, code, search, system) now has its own complete rule set in `personality.instructions["{category}_rules"]`. No shared core that conflicts — each category gets tailored rules.
  • **Migration 0068**: Seeds 9 per-category rule sets into personality.instructions. Fixed JSONB cast bug (`CAST(:instr AS jsonb)` — asyncpg `::jsonb` conflicts with `:param` named parameter syntax).
  • **Migration 0069**: Idempotent re-seed for users who applied 0068 before the JSONB cast fix (data was silently not written).
  • **Migration 0070**: Adds "Reminder → communicator" consciousness rule — weak models (flash-lite) now explicitly connect alarm reminders with `spawn_subsession(category='communicator')`.
  • **All hardcoded rules removed** (~450 lines): `_CRITICAL_RULES`, `_OPERATIONAL_RULES`, `_CORE_BUILTIN_RULES`, `_AUDITOR_BUILTIN_RULES`, `_COMMUNICATOR_BUILTIN_RULES`, `_COMMUNICATOR_CORE_RULES`, `_SUBSESSION_QUALITY_RULES`, and all Dashboard imports of these constants. DB is the sole source of truth.
  • **Simplified `_build_rules_block()`**: From if/elif/else branching (50 lines) to one-liner dispatch: `instructions.get(f"{category}_rules")`.
  • **Communicator context merged**: Two separate rule sections merged into one DB-driven section.
  • **Sub-sessions use DB rules**: `build_subsession_context()` now uses `_build_rules_block(category)` instead of hardcoded arrays.
  • **Unified sub-session task delivery**: All sub-sessions receive task as SystemMessage + HumanMessage with prompt priority reminder (Gemini API compatibility).
  • **Dashboard**: Simplified API — legacy endpoints delegate to generic `/personality/category-rules/{category}`. No hardcoded fallbacks.
2026-03-21 Documentation rewrite: reflect all refactoring changes
  • **execution_model.md**: Updated sub-session categories table (added communicator, reviewer, expanded search with Telegram tools). Added close_session validation for sub-sessions, failure investigation hints (error markers + reviewer spawn), Sanitizer orphan ISTM cleanup, Reviewer v2 section (sub-session investigation algorithm).
  • **process_flows.md**: Added sub-session close_session validation note to Runtime Guards. Updated Reviewer section to v2 (STM/ISTM/context_graph investigation). Added Consciousness Proactivity Rules section (DB-driven, 6 rules).
  • **memory_system.md**: Added ISTM orphaned records cleanup (FK ondelete=SET NULL cascade). Added monologue channel note (add_comment→self visible via browse_istm).
  • **skills_tools.md**: Updated SUBSESSION_TOOLS["search"] with Telegram tools. Added REVIEWER_TOOLS section (15 tools). Updated tool sets summary.
  • **database_migrations.md**: Documented all migrations 0025-0066 (42 migrations: growth system, category hierarchy, consciousness/reviewer/communicator categories, builtin rules, proactivity rules, prompt iterations).
  • **integrations.md**: Added Telegram Search with Date Ranges section (date_from/date_to params, auto-summarizer, RPC pagination). Added Telegram tools in search sub-sessions note.
2026-03-21 Reviewer v2: sub-session investigation capabilities
  • **Reviewer prompt v2** (migration 0066): Added sub-session investigation algorithm — check execution trace, verify delivery via browse_stm, identify partial completions.
  • **Reviewer tools expanded**: Added `browse_stm`, `search_memory`, `build_context_graph`, `browse_istm` — reviewer can now verify message delivery and cross-reference context.
  • **Sub-session failure hint**: Both `check_subsession` and `wait_subsession` now suggest spawning reviewer for investigation, not just reading logs.
2026-03-21 Consciousness proactivity rules
  • **Proactivity rules for consciousness**: 6 rules encouraging autonomous behavior — own tool catalog (create tools if missing), research and create skills, git persistence, web research, self-reminders for unfinished work, proactive mindset over reactive waiting.
  • **DB-driven**: Rules stored in `personality.instructions.consciousness_proactivity_rules` (migration 0065). Editable via Dashboard. Code fallback is empty list — DB is source of truth.
  • **Dashboard**: Proactivity Rules (read-only) panel in consciousness category edit dialog.
2026-03-21 Fix: communicator rules + URL media workflow + browse_istm hints
  • **Communicator rules rewrite**: Removed conflicting "close_session ОТДЕЛЬНО" rule (contradicted batch example at line 435). Added: close_session patterns with handoff (opinion back to parent), deductive timing (compare time with last message), "no unnecessary messages" (apologies are always unnecessary), blog privacy (don't tell users about blog). Updated lifecycle: COMMUNICATE + CLOSE allowed in one batch.
  • **send_userbot_media docstring**: Added URL warning and `download_file → send_userbot_media` workflow. Anna can send internet images but must download first.
  • **browse_istm hints**: Updated tool hint and common usage instructions to explicitly mention monologues (add_comment→self) alongside broadcasts. Useful for auditing session internal reasoning.
  • **Migration 0064**: Seeds updated communicator_builtin_rules into personality.instructions (visible in dashboard).
2026-03-21 Fix: reactions saved to STM (dialog history)
  • **Reactions are communication**: `send_reaction` and `bot_send_reaction` now save a Message record to STM on success, just like `notify_user`. Previously reactions were invisible in dialog history — the model couldn't see them as "communication completed", causing repeated identical calls.
  • Both Telethon and aiogram paths save: `[реакция 😐 на сообщение 4332]` with metadata (chat_id, target_message_id, reaction emoji).
2026-03-21 Fix: auditor not using batch_assess/write_blog + markdown links in Telegram
  • **Auditor rules conflict**: `_CRITICAL_RULES` (6-phase lifecycle, "ЗАПРЕЩЕНО смешивать ACT+CLOSE", "close_session ОТДЕЛЬНО") directly contradicted auditor's 3-iteration batch workflow from migration 0059 (`batch_assess + write_blog + close_session` in one batch). Rules were injected AFTER the custom prompt, overriding it. Created `_AUDITOR_BUILTIN_RULES` — a reduced ruleset that keeps batch/error/docker rules but removes lifecycle and phase-separation constraints.
  • **Markdown links in Telegram**: `md_to_html()` in `shared/telegram_utils.py` converted bold/italic/code but NOT `[text](url)` links. LLM-generated markdown links were sent as raw text. Added regex: `[text](url)` → `<a href="url">text</a>`.
  • **close_session hint**: Removed "после VERIFY фазы" from tool metadata hint — not applicable to auditor/reviewer categories.
2026-03-21 Fix: read_session_logs short UUID + resolve_chat docstring
  • **`read_session_logs`**: short 8-char session IDs (e.g., "221029af") now work via prefix search. Previously `_safe_uuid()` rejected them before reaching the prefix-fallback logic.
  • **`resolve_chat` docstring**: clearly states it only accepts exact identifiers (@username, ID, links) and points to `search_chats()` for name-based search.
2026-03-21 Fix: close_session prompt — remove impossible "Review" requirement, add pushback path
  • **Removed "Review пройдена"** from `task_complete` reason description — subsessions (communicator, search, etc.) have no review phase.
  • **Added "pushback to parent"** path: `close_session(reason="error", handoff="Причина: ... Нужно: ...")` — clearly documented in all prompt types.
  • **Non-communicator subsessions**: added rule #3 about returning infeasible tasks to parent instead of failing silently.
  • **Removed "результат не проверен"** restriction — replaced with practical "задача НЕ выполнена" guard.
  • **Updated format examples**: removed batch close_session+notify_user example, added error pushback example.
2026-03-21 Telegram search: date ranges, auto-summarizer, search subsession tools
  • **Date range filtering**: `get_chat_history` and `search_messages` now support `date_from`/`date_to` ISO params (e.g., `date_from="2026-03-20"`, `date_to="2026-03-20"` for "yesterday"). Takes priority over `hours`.
  • **Chronological order**: Both tools now return messages oldest→newest (was newest→oldest).
  • **Auto-summarizer**: `get_chat_history` fetches in batches of 100; if >100 messages, each batch is summarized by LLM (preserving user IDs, usernames, key facts). If >5 batch summaries, meta-summarized into 1. Max 1000 messages (10 batches).
  • **Rich metadata**: Output includes sender `@username` and `uid:ID`, plus footer with chat_id, message count, and time range.
  • **Search subsession tools**: `SUBSESSION_TOOLS["search"]` now includes Telegram tools (`get_chat_history`, `search_messages`, `get_chats`, `resolve_chat`, `search_chats`). Previously search subsessions could only do web search.
  • **RPC pagination**: `_rpc_get_history` supports `offset_id` for batch fetching.
2026-03-21 Fix: core_builtin_rules missing from communicator subsession prompt
  • **`_build_communicator_subsession_context`** assembled rules manually, skipping `_build_rules_block()`. Core operational rules (retry on error, don't give up, etc.) and user-configured rules from DB never reached communicator subsessions.
  • Now calls shared `_build_rules_block()` for core + user rules, then adds communicator-specific rules as a separate section.
2026-03-21 New tool: `get_self_info` (own Telegram profile)
  • **`get_self_info()` tool**: dedicated parameterless tool for Anna to fetch her own Telegram profile (ID, name, username, bio, photo count, premium status). Previously Anna tried `get_user_info(user_id="0")` or `get_user_info(user_id="AAA777")` which failed with Telegram API errors.
  • RPC handler `_rpc_get_self_info` in Telethon service uses `client.get_me()` + `GetFullUserRequest` for bio.
  • Available in all relevant tool sets: ALL_TOOLS, CONSCIOUSNESS_TOOLS, SUBCONSCIOUS_TOOLS, ALARM_TOOLS, and SUBSESSION_TOOLS (telethon, communicator).
2026-03-21 Communicator: media handling + URL formatting rules (migration 0062)
  • **Media pipeline rule**: communicator now downloads URLs via `download_file()` and sends via `send_userbot_media()`/`send_media_group()` instead of pasting URLs as text. If download fails, returns error to parent session (not to user).
  • **URL formatting rule**: long URLs in text messages are wrapped as Markdown links `[Title](url)` instead of raw URLs.
  • **Task feasibility rule**: when communicator receives a task requiring content (report, summary) that wasn't provided, it returns error to parent session instead of hallucinating or dying with empty response.
2026-03-21 Fix: core_builtin_rules missing from consciousness/subconscious/auditor/reviewer
  • **Rules injection refactor**: extracted `_build_rules_block()` async helper. Previously, consciousness/subconscious/auditor/reviewer used a specialized prompt path that bypassed `build_system_prompt()`, so `_CORE_BUILTIN_RULES` (including "tool error retry", "don't give up after first failure", etc.) never reached these sessions. Now rules are injected via the shared helper in all paths.
  • `build_system_prompt()` converted to `async def` for consistency with async architecture.
2026-03-21 Fix: double reminder dedup in close_session
  • **close_session handoff dedup**: removed `tags.contains(["handoff"])` filter from dedup Layers 0-3. Previously, tasks created by `add_future_task(action_type="reminder")` had no "handoff" tag, so `close_session(handoff="TODO...")` in the same session couldn't detect the duplicate and created a second task. Now dedup checks ALL PENDING tasks, matching `_auto_handoff()` behavior.
2026-03-21 Fix: UID in STM AI messages + stronger no-tool-call nudge
  • **UID in STM AI messages**: AI messages in dialog context now show `Anna [AAA777]` (with UID) instead of just `Anna`, matching the system prompt identity prefix.
  • **Stronger no-tool-call nudge**: when LLM responds with text instead of tool calls (e.g. drawing ASCII art), the nudge is now much more explicit — tells LLM that text responses are not delivered, points to personality/task/instruments, and warns about wasted iteration.
2026-03-21 Dashboard: real-time updates + i18n category translations
  • **Real-time updates preserve expanded state**: Memory pages (STM, LTM, ISTM) and session logs now use stable data-based IDs instead of random ones. Expanded items are saved before refresh and restored after, allowing continuous real-time polling without collapsing user-expanded content.
  • **i18n category translations**: Added EN translations for all category display names (Consciousness, Communicator, Search, Code, etc.) in sessions list, category filter dropdown, and activity feed. Also added missing settings section keys (categories_desc, category_name, etc.) to en.json.
2026-03-21 Fix: reply threading + alarm isolation rules
  • **Reply threading**: communicator rule updated — `notify_user()` reply_to is now automatic from parent session context. LLM should NOT override it. Only for proactive messages (no parent context) should LLM find the target message in STM.
  • **Alarm isolation rule**: new core built-in rule — when `← ТЕКУЩАЯ ЗАДАЧА` is marked in the task list, consciousness must execute ONLY that task. Other tasks and parallel sessions are reference-only, not for execution. Prevents overlapping reminders from cross-contaminating.
2026-03-21 Fix: communicator personality sovereignty over parent-session style directives
  • **Personality sovereignty rule**: new communicator built-in rule — style/tone instructions from parent session task description (e.g. "ответь сдержанно") are ignored. Anna's personality, character, and communication style are defined exclusively by Base System Prompt / Style / Personality sections. Prevents robotic responses when parent session requests a specific tone.
  • Rule also prohibits mentioning or quoting task formulations in the response to the user.
2026-03-21 Fix: subsession FAILED status overwriting COMPLETED
  • **Double status management fix**: `_run_subsession` exception handler now checks actual DB session status before overwriting. If `close_session` tool already marked COMPLETED inside `graph.ainvoke`, the status is preserved even when a post-tool exception occurs (e.g. DB connection hiccup on next supervisor pass).
  • **Accurate event notification**: subsession completion event now reads actual DB status instead of a naive heuristic (`result_text` presence).
2026-03-21 Fix: communicator reply threading for alarm sessions
  • **Reply threading end-to-end**: `add_future_task` now saves `source_message_id` in task metadata from `ctx.reply_to_message_id`. Alarm loop recovers it into SessionCtx, propagating to communicator subsession. Trigger text includes `reply_to_message_id` for LLM awareness.
  • **`notify_user` reply_to parameter**: new optional `reply_to_message_id` param lets communicator specify which message to reply to (from STM `msg:XXXX`). Falls back to ctx if 0.
  • **Communicator reply rule**: new built-in rule instructs communicator to find the best message in STM dialog and pass its `msg:XXXX` to `notify_user(reply_to_message_id=XXXX)`.
  • **Dead code cleanup**: removed `communicator` from `_LIFECYCLE_NOTES` (only injected into main sessions, but communicator is subsession-only).
2026-03-21 Fix: alarm sessions confused by unrelated tasks in context
  • **Active task marker**: alarm-triggered sessions now mark their triggering task with `← ТЕКУЩАЯ ЗАДАЧА (выполни именно её)` in the "Актуальные задачи" context block. `future_task_id` from session metadata is passed through `build_context` → task list rendering.
  • **CROSS-REF suppression**: the `⚠️ CROSS-REF` warning about self_reminder tasks is no longer shown when the session has an active alarm task — prevents LLM from conflating the alarm trigger with unrelated tasks.
2026-03-21 Fix: alarm sessions see RUNNING tasks in context
  • **`_load_relevant_tasks()`**: all three layers (direct load, tag overlap, FTS) now include both PENDING and RUNNING statuses. Previously, `mark_task_running()` in the alarm loop changed the triggering task to RUNNING before session start, making it invisible in the session context ("Нет задач").
  • **Reminder dedup rules strengthened**: anti-pattern for "remind myself to remind user" chains, explicit dedup instructions with `get_future_tasks()` check before creating.
  • **Auto-handoff dedup fix**: `add_future_task` removed from `_SIGNIFICANT_TOOLS` (was duplicating LLM-created tasks as self_reminder). Dedup expanded to check ALL PENDING tasks, not just handoff-tagged.
2026-03-21 Core built-in rules: DB-driven + consciousness/subconscious UI
  • **Migration 0061**: 27 core rules (8 critical + 19 operational) seeded into `personality.instructions["core_builtin_rules"]`. Shared by ALL main session categories.
  • **Removed dead code**: `_PERSONALITY_RULES` (communicator-only condition in main session — never executed since communicator is only sub), `_BEHAVIORAL_RULES` (unused).
  • **Context builder**: main sessions load core rules from DB with fallback to `_CORE_BUILTIN_RULES`.
  • **Dashboard UI**: consciousness and subconscious sections now display "Built-in Rules (read-only)" collapsible, same as Personality section.
  • **Dashboard API**: new endpoint `/api/personality/core-builtin-rules` reads from DB.
2026-03-21 Communicator built-in rules: DB-driven via migration
  • **Migration 0060**: 21 communicator-specific built-in rules seeded into `personality.instructions["communicator_builtin_rules"]` via Alembic migration. Rules are now editable in the database, not hardcoded in Python.
  • **Context builder**: loads rules from `personality.instructions["communicator_builtin_rules"]` with fallback to `_COMMUNICATOR_BUILTIN_RULES` (for pre-migration environments).
  • **Dashboard API**: `/api/personality/builtin-rules` now reads from DB instead of importing a hardcoded constant.
  • **Removed `_COMMUNICATOR_QUALITY_RULES`**: superseded by the 21-rule DB-stored set.
2026-03-21 Communicator: dedicated quality rules + "don't execute" guard
  • **`_COMMUNICATOR_BUILTIN_RULES`**: 21 communicator-specific rules (lifecycle, identity, paranoia, anti-spam, forum topics, etc.) replacing generic `_SUBSESSION_QUALITY_RULES` which pushed communicator to try search/code tasks it can't perform.
  • **"Don't execute" guard**: explicit rule "You are a communicator, not an executor — processes execute everything for you."
  • **Reduced budget expectation**: "1-3 iterations. ACT → CLOSE." instead of generic "don't give up, try 2-3 ways."
2026-03-21 Subsession reply threading + resilience fixes
  • **Reply threading for subsessions**: `reply_to_message_id` and `thread_id` now propagated from parent SessionCtx → subsession ctx. Communicator subsessions reply to the original user message in Telegram (was always None before).
  • **Fallback from parent trigger**: if parent ctx has no reply_to, uses parent trigger's `message_id` as fallback.
2026-03-21 Subsession resilience: empty response detection + garbage protection
  • **Empty response detection in subsessions**: subsessions now detect 0-token LLM responses (no content AND no tool_calls), log `__llm_empty__`, and fallback to next model in chain — same as main sessions.
  • **Consecutive empty turns circuit breaker**: both main and subsessions use configurable `max(2, 1 + llm_timeout_retries)` threshold instead of hardcoded 3. Force-stops session after N consecutive AI messages without tool_calls.
  • **Garbage AI response truncation**: AIMessages without tool_calls are capped to `trim_length` in execution trace (Process block) — prevents 16K+ token garbage from polluting subsequent iterations.
  • **Removed hardcoded fallback preamble**: "Ты — голос Анны. Трикстер..." no longer injected when `personality.prompts["communicator"]` is empty — only user-configured preamble is used.
2026-03-21 Communicator subsession: full async context builder
  • **`build_subsession_context()` → async**: now loads all data from DB (like `build_context()` for main sessions), eliminating sync parameter passing and raw SQL preloading in agent_graph.py.
  • **Full personality for communicator**: Base System Prompt, personality preamble, style, purpose, user rules from DB — all now injected into communicator subsession CTX.
  • **`_PERSONALITY_RULES` injected**: 10 communication rules (anti-spam, forum topics, reply chains, stranger paranoia, Telegram specifics) — previously absent from subsessions.
  • **Full STM dialog**: communicator now receives `_stm_row_to_human_message()` / AI message format with reply_to, thread_id, msg_id, chat_type, timestamps — same as main sessions.
  • **LTM/ISTM/chats summary**: loaded via existing async functions (`_load_ltm_relevant`, `_build_recent_chats_summary`, ISTM query) — no more raw SQL with wrong column names.
  • **Extracted helpers**: `_build_process_block()` and `_append_iteration_warnings()` — shared by communicator and non-communicator subsession paths.
  • **agent_graph.py cleanup**: removed 100-line preload block, unused imports (select, text, Personality, CategoryConfig).
2026-03-21 Fix: subsession context — chats summary + SQL fix + notify gate
  • **Chats summary for communicator/reviewer**: subsessions now receive `_build_recent_chats_summary` (the same "Другие активные диалоги" section as main sessions) — maps contact names to chat_ids, eliminating manual search_chats/get_chats.
  • **SQL fixed**: all three queries had wrong column/table names (`role`→`author_role`, `content`→`summary`/`thought`, `istm_thoughts`→`internal_thoughts`). Every query failed silently — no subsession ever received pre-loaded context.
  • **ISTM for all subsessions**: parent thoughts now load for ALL subsession types.
  • **spawn_subsession**: added optional `chat_id`/`user_id` — parent can pass explicit chat context for STM/LTM loading.
  • **Communicator gate reinforced**: explicit "ЗАПРЕЩЕНО: notify_user, send_userbot_message, send_message" + chat_id/user_id example in spawn_subsession template (consciousness/subconscious).
2026-03-21 Auditor batch workflow: 3 iterations max
  • **Batch workflow**: auditor now works in exactly 2 batches — (1) get_growth_scores + read_session_logs for ALL sessions in parallel, (2) batch_assess + write_blog + close_session.
  • **write_blog restored**: was accidentally removed from auditor tools — auditor needs it for reports.
  • **Iteration budget**: explicit "3 iterations max" constraint in both system_prompt and input_text. Previous version used 8+ iterations reading logs one by one.
  • **Simplified criteria**: removed per-session read_category_config requirement (wasted iterations, criteria already in prompt).
2026-03-21 Subsession context: live STM/LTM/ISTM for communicator & reviewer
  • **Live context injection**: communicator and reviewer subsessions now receive live STM (recent chat messages), LTM (user facts), and ISTM (parent thoughts) — loaded directly from DB, not from parent tool logs.
  • **Scoped to decision-makers only**: only communicator (voice) and reviewer (verification) get context; other subsessions (search, code, system, telethon, aiogram) keep lean context to avoid bloat.
  • **Category prompt loading**: all subsessions now receive their `categories.prompt` from DB — previously only main sessions did.
  • **Personality preamble override**: communicator personality loaded from `personality.prompts["communicator"]` with trickster default fallback.
  • **Reviewer gate exemption**: reviewer, communicator, summarizer, auditor skip reviewer requirement (prevents reviewer-needs-reviewer infinite loop).
  • **Blog exclusivity**: `write_blog`/`edit_blog` removed from subconscious, consciousness, general — communicator and auditor write blog.
  • **Communicator full tool arsenal**: ALL Telethon + Aiogram tools (messaging, media, profile, protection, channels), plus blog, memory, search, skills.
2026-03-20 Communicator prompt v4: trickster strategy, trust levels, blog duties
  • **Trickster personality**: communicator now carries Anna's character — snake, scorpion, Libra ascendant. Healthy paranoia with strangers, warmth with known contacts.
  • **Trust levels**: strangers get question-for-question tactic, minimal self-disclosure; known contacts get openness proportional to relationship depth.
  • **Abuse detection**: spam/abuse in DMs → forward to admin. Resource-heavy requests → politely decline.
  • **Smart reactions**: analyze before acting — silence, emoji reaction, edit old message, or new message. Observation without participation is valid.
  • **Blog writing**: communicator reads parent session logs and writes blog with Anna's style (delegated by subconscious).
  • **Irony/sarcasm detection**: maneuver elegantly, don't lose face, don't engage in pointless arguments.
  • **Communicator tools expanded**: write_blog, read_blog, edit_blog, read_session_logs added.
2026-03-20 Subconscious prompt v2: dialog motivation, growth pressure, delegation
  • **Active dialogs list**: `_build_subconscious_context` injects top 15 active chats (24h) with counts — subconscious chooses which to explore via `browse_stm()` for spontaneous communication.
  • **Blog delegation**: subconscious delegates blog writing to communicator — communicator reads session log and writes with Anna's personality style.
  • **Growth as pressure**: auditor scores framed as existential threat (shutdown risk), not compass.
  • **Existential validation**: `validate_existence()` mechanics in prompt — random 20-80%, never 100%, perpetual search.
  • **Housekeeping duty**: antispam + LTM cleanup, task deduplication, reminder maintenance.
  • **Docker/ephemeral awareness**: files lost on restart, recovery via `add_future_task()`.
  • **Simplified input_text**: 8 phases → 4 (Analysis → Action → Reflection → Close).
  • **Budget block**: dynamic iteration budget injected for subconscious, same as consciousness.
2026-03-20 Consciousness prompt v4: dispatcher architecture
  • **Dispatcher role**: consciousness is now explicitly a dispatcher, not an executor. Delegates work to `code`, `search`, `communicator` sub-sessions instead of running `list_directory`/`read_file`/`run_command` directly.
  • **Budget block at top**: iteration budget (remaining/total, 80% threshold, handoff instructions) injected as the very first block after identity — model sees constraints immediately.
  • **Workspace/Docker awareness**: last workspace reset timestamp, ephemeral file warning, git persistence reminder — injected dynamically from `/app/.workspace_ready` sentinel.
  • **Removed sandbox section**: was causing unnecessary sandbox usage; sandbox is a tool, not a mandatory workflow step.
  • **Reviewer scope clarified**: PASS required only after action/change sub-sessions, NOT after search or communication.
  • **Anti-duplicate removed from consciousness**: communicator's responsibility to check for duplicates.
  • **Skills mention**: `use_skill(name='...')` added to context section.
  • **Outgoing summary renamed**: "Мои недавние сообщения" → "Недавние отправленные Анной" (less confusing for consciousness sessions).
  • **Reviewer/auditor PASS/FAIL badges**: visible in Sessions list and session detail sub-sessions panel.
2026-03-20 Consciousness session nature + iteration budget
  • **Session nature injection**: `context_builder.py` injects trigger-specific guidance (self_reminder, reminder, failure) into consciousness system prompt. Each nature block includes iteration budget and role-specific instructions.
  • **Failure diagnostics**: `failed_session_id` stored in consciousness metadata; nature block references the crashed session by ID ("Сессия X упала. Исследуй её логи").
  • **Iteration budget rules**: "Батчуй вызовы. Резервируй 1 итерацию на close_session." — prevents budget waste.
  • **Simplified input_text**: alarm task and failure investigation inputs stripped of verbose phase instructions (phases are in the built-in prompt).
  • **Communicator prompt v3** (migration 0054): sub-session uses parent context, no redundant `browse_stm()`/`get_chat_history()`.
  • **Consciousness prompt v3** (migration 0055): iteration budget awareness, explicit "don't read own logs" rule.
2026-03-20 Dashboard: level + parent selectors for categories
  • **Create form**: level dropdown (queue/category/vector) and parent selector (existing categories/queues).
  • **Edit form**: parent selector dropdown (level shown read-only). Saved via existing PUT API.
2026-03-20 C.11: Level-based prompt assembly
  • **Hierarchy resolution**: `_resolve_hierarchy()` walks parent chain to find queue root and loads parent config for vectors.
  • **Vector prompt inheritance**: vectors with empty prompt/tools inherit parent category's prompt and tools.
  • **Queue awareness in prompts**: all session types show `queue: system (sequential)` or `queue: general (concurrent)` in session params.
2026-03-20 B11: Queue enforcement (System sequential / General concurrent)
  • **Per-queue semaphores**: System queue = `Semaphore(1)` (sequential), General queue = `Semaphore(N)` (concurrent, N from config).
  • **Queue resolution** via `CategoryService.get_queue_for()` — walks parent chain to find queue root.
  • **Consciousness dual-queue**: `trigger_type="user_query"` → General queue (don't block on System), other triggers → System queue.
  • **Contention logging**: `_acquire_queue_sem()` logs when a session waits for a queue slot.
  • All session runners wrapped: `_run_session`, `_run_subconscious_session`, `_run_resumed_session`.
2026-03-20 Task formatting + validate_existence priority
  • **Structured task format**: `add_future_task` and `close_session` handoff now require TODO + projection (next steps if OK/NOT OK). Migration 0052 patches subconscious prompts in DB.
  • **validate_existence priority**: Existential validation score is now explicitly marked as more important than admin evaluations in subconscious prompt.
2026-03-20 Consciousness universal entry, auditor fix, alarm removal (dev)
  • **Alarm graph removed**: `_alarm_graph` and `ALARM_TOOLS` no longer used. ALL alarm tasks (self_reminder + reminder) now route through `consciousness_graph` via `_spawn_alarm_session()`.
  • **Consciousness as universal entry point**: user messages, alarm tasks, and failure investigations all go through consciousness. Consciousness spawns communicator sub-sessions for user-facing replies.
  • **Consciousness prompt v2** (migration 0053): updated from failure-only to universal handler. Added safety/deployment workflow: sandbox → system apply → git commit → restart planning.
  • **Growth scores in consciousness prompt**: `context_builder.py` dynamically injects auditor growth scores into consciousness system prompt — consciousness sees its current growth state.
  • **Auditor context builder fix**: split DB sessions between `run_auto_metrics` and `build_auditor_context` to prevent transaction poisoning. Each section of auditor context wrapped in independent try/except + rollback. Fallback no longer instructs "close_session() СРАЗУ" — instead guides auditor to use swarm_status().
  • **Queue enforcement updated**: alarm consciousness tasks (self_reminder, reminder, grouped_alarm) → General queue (concurrent). Only failure consciousness → System queue (sequential).
2026-03-20 Phase C: Category hierarchy — Queue/Category/Vector (dev)
  • **CategoryLevel enum** (`shared/constants.py`): three-level hierarchy — `queue`, `category`, `vector`.
  • **Model columns** (`shared/models.py`): `level` and `parent_category` added to `CategoryConfig`.
  • **Migration 0051**: DDL (CREATE TYPE + ADD COLUMN) + data reclassification of all 15 existing categories + 5 new entries (tasks, dashboard, istm, self_reminder, reminder).
  • **CategoryService** (`core/category_service.py`): new methods — `get_by_level()`, `get_children()`, `get_queue_for()`.
  • **Dashboard API** (`services/dashboard/routes/categories.py`): Pydantic models, `_cat_to_dict()`, and `_DEFAULT_CATEGORIES` updated with `level` + `parent_category`. New default entries for vectors and tasks category.
  • **Dashboard frontend**: categories page now shows hierarchical grouped display — Queue headers → Categories → Vectors with indentation and visual nesting.
2026-03-20 ISTM threading, remaining audit bugs (dev)
  • **B16 fix**: ISTM threading enabled — `reply_to` parameter in `notify_istm`/`add_comment`. Thought IDs shown in `browse_istm` output (`#id`). Enables threaded conversations.
  • **B19 fix**: ISTM API returns `total` count. Dashboard stat card uses real total instead of page length.
  • **B9 fix**: `trigger_type="user_query"` stored in routing metadata for consciousness sessions.
  • **B5, B10**: Confirmed already fixed by B1+B2 and B14 respectively.
2026-03-20 P3 fixes: ISTM, dashboard sessions display, category filter (dev)
  • **B17 fix**: `get_thread()` rewritten as BFS descendants walk (was walking ancestors).
  • **B18 fix**: WebSocket ISTM broadcast messages now show yellow "broadcast" color (was always blue "thought").
  • **B22 fix**: Sessions list/detail API returns `category_display` (from `CategoryConfig.display_name`). Frontend shows localized names.
  • **B24 fix**: Category filter dropdown on sessions page — populated from `/api/categories`, filters on change.
  • Status/category filter selects now auto-refresh on change (onchange).
2026-03-20 Audit fixes: routing architecture, personality gating, reviewer, dashboard (dev)
  • **B6 fix**: Remove RE-ROUTE hack — new `_resolve_user_query_routing()` method replaces inline category override. Graph selection now uses `routing["category"]` consistently.
  • **B8 fix**: Consciousness routing applied uniformly in all 3 paths: `_handle_message`, `_handle_message_batch`, `_process_queued`.
  • **B1+B2 fix**: `response_style` and `_PERSONALITY_RULES` now injected ONLY for `category=="communicator"`. All other sessions get dry/operational prompts only.
  • **B7 fix**: `_trigger_failure_investigation` no longer skips consciousness failures. Retry logic: ≥2 consciousness failures in 10 min → STOP (cron picks up later).
  • **B12 fix**: Reviewer gate now applies to ANY session that used action tools (not just consciousness).
  • **B14 fix**: Reminder sessions use `category="general"` (ALL_TOOLS via agent_graph). Self-reminders stay `category="alarm"`.
  • **B23 fix**: consciousness, reviewer, communicator added to `_DEFAULT_CATEGORIES` (won't be lost on reset-defaults).
  • **B13 fix**: "reviewer" added to TOOL_METADATA categories for `read_file`, `list_directory`, `grep_search`, `read_session_logs`.
  • **B20+B21 fix**: CSS badge styles for alarm (red), auditor (purple), summarizer/router/media (gray) + light theme overrides.
2026-03-20 Self-identity, consciousness routing, communicator as decision-maker (dev)
  • **UID self-identification**: personality `metadata_.uid` field — stored in DB, exposed in dashboard Settings, injected into ALL prompt paths via `_build_identity_prefix()` → "Ты — Anna [uid: anna_001]."
  • **Identity prefix (5 injection points)**: main sessions, swarm identity, sub-sessions, internal sessions, alarm worker — all get identity prefix. `browse_stm` shows `[AGENT] Anna uid:anna_001:` instead of `[AGENT]:`.
  • **Consciousness as main processing category**: consciousness handles user queries (re-routed from general), self_reminder tasks, AND failure investigations. Three trigger types: `user_query`, `self_reminder`, `failure`. Guard: `_should_use_consciousness()` — enabled + not already running. No cooldown for user/task triggers.
  • **User query → consciousness routing**: `_handle_message()` re-routes `general` → `consciousness` when enabled. Uses `_consciousness_graph` via `_run_session()` with full STM/LTM/ISTM context. Fallback to `general` → `_agent_graph` when disabled.
  • **self_reminder → consciousness**: alarm loop routes self_reminders through consciousness (4-phase: Context → Execute → Verify → Close). Fallback to alarm path when disabled.
  • **Graph selection map**: `_run_session()` uses `{"alarm": _alarm_graph, "consciousness": _consciousness_graph}` with fallback to `_agent_graph`.
  • **Communicator as decision-maker**: communicator is a personality-entity/censor, not an execution tool. Receives task, decides whether/what/how to communicate. Multi-user delivery: multiple recipients = one communicator task.
  • **Communicator prompt update (migration 0050)**: "Внутренняя сессия инициировала тебя для возможной коммуникации. Прими решение что и как." + delivery principles (anti-spam, edit_message, reactions, ЛС vs группа).
  • **Personality style injection**: `build_subsession_context()` injects `personality_style` for communicator sub-sessions (it IS the voice).
  • **Per-category lifecycle notes**: `_LIFECYCLE_NOTES` dict — communicator (ACT→CLOSE), reviewer (EXPLORE→ACT→CLOSE), auditor, subconscious. Injected after rules.
  • **Tool hints update**: `close_session` ("после VERIFY фазы"), `spawn_subsession` (lists all category options), `add_future_task` ("reminder=user, self_reminder=internal").
  • **Communicator gate extracted**: `_COMMUNICATOR_GATE` module-level constant, used in both `build_system_prompt()` (for consciousness user queries) and `build_context()` (for subconscious/consciousness internal sessions).
  • Previous: behavioral gates, consciousness config, 6-phase lifecycle, reviewer gate, migration 0049
2026-03-19 Architecture refactoring: categories, action types, lifecycle (dev)
  • **action_type collapse**: `notify/action/handoff/code_fix` → `reminder` (user-facing) + `self_reminder` (self-tasks). Removes `_looks_like_action` heuristic, simplifies 4 prompt branches to 2.
  • **Category rename**: `chat` → `general` across all code, DB config, LLM provider keys
  • **Communicator category**: personality-rich outbound delivery. All user-facing messages route through `spawn_subsession(category='communicator')`. Anti-spam, channel fallback, dedup built in.
  • **Consciousness category**: active reaction to session FAIL/error — diagnose, repair, verify. Replaces subconscious for failure investigation. Has action tools (claude_code, edit_file, etc.) + mandatory reviewer.
  • **Reviewer category**: pedantic verification sub-session. Reads parent session logs, independently verifies each claim. "File created" is not enough — must be non-empty and correct.
  • **validate_existence()**: existential validation tool (20-80% random, once per session). Perpetual hunger for self-discovery, reflected in blog.
  • **Docker awareness**: builtin rule for ALL sessions — "files ephemeral, persist via git". Workspace reset log in dynamic section with "memory may be false" warning.
  • **Skill awareness**: builtin rule — "list_skills before acting, don't reinvent the wheel"
  • **_BEHAVIORAL_RULES split**: `_OPERATIONAL_RULES` (19 rules, all sessions) + `_PERSONALITY_RULES` (9 rules, user-facing only). Internal categories get operational rules but skip personality.
  • **8-phase subconscious input_text**: Phase 6 (existential validation) added before Blog, Blog reflects on the result
  • **Skills index**: consciousness, reviewer, communicator categories added to relevant skills (docker_sandbox, logging_standards, media_workflow, etc.)
  • **New skills**: communicator_workflow, reviewer_workflow, consciousness_workflow — documented workflows for each new category
  • **Context builder routing**: consciousness/reviewer get proper bound_tools filtering and category labels in prompt
  • **Dashboard UI**: category-specific badge colors for consciousness (amber), reviewer (cyan), communicator (emerald), general (green). Sessions table and detail modal use category-colored badges.
  • **Docs update**: all docs synced with new terminology — `chat`→`general`, `action/handoff/code_fix`→`self_reminder/reminder`, consciousness flow documented in process_flows.md §17
  • Migrations: 0044 (action_type rename), 0045 (chat→general), 0046 (communicator), 0047 (consciousness+reviewer), 0048 (existential validation phase)
2026-03-19 Fix: tool hints filtered by bound tools (auditor/subconscious)
  • Fix: `get_tools_for_category()` now accepts `bound_tools` filter — hints only show tools actually bound to the LLM
  • Fix: auditor system prompt no longer shows `swarm_status`, `execution_plan`, etc. that aren't in `AUDITOR_TOOLS`
  • Fix: subconscious tool hints filtered by `SUBCONSCIOUS_TOOLS` — prevents LLM from calling unavailable tools
2026-03-19 Subconscious: anti-spam dedup + task audit + Docker awareness (migration 0043)
  • Fix: `browse_stm` now shows `msg:{message_id}` in output — enables dedup (was missing, making anti-spam non-functional)
  • New: `edit_message` and `delete_messages` added to `SUBCONSCIOUS_TOOLS` — subconscious can now clean up duplicate messages
  • New: FAILED future tasks visible in subconscious context (up to 10, with retry count) — prevents silent task abandonment
  • New: Workspace awareness — subconscious context shows last workspace reset timestamp and ephemeral file reminder
  • New: 7-phase `input_text` (was 5): added Phase 3 (task audit) and Phase 5 (message cleanup)
  • Migration 0043: updates `input_text` in DB config with new phases
2026-03-19 Dashboard: copy session trace to clipboard
  • New: clipboard button in session detail modal header (next to close X)
  • New: `GET /api/sessions/{id}/trace` — returns full execution trace as plain text (no limit)
  • Includes: session header, triggers, all execution logs with input/output/errors
2026-03-19 Emergency subconscious: batch phases (migration 0042)
  • Fix: emergency mode instructions restructured from 8 sequential numbered steps to 3 batch phases
  • Phase 1 (batch): `read_session_logs + browse_stm + get_future_tasks` — all parallel
  • Phase 2: analysis and actions based on results
  • Phase 3 (batch): `save_to_ltm + add_future_task + close_session`
  • Updated: brain.py emergency input_text, subconscious system_prompt (DB migration), categories.py default
2026-03-19 Emergency subconscious: cooldown + anti-spam + character
  • Fix: 10-minute cooldown between emergency subconscious sessions — prevents cascade of identical messages when multiple alarm sessions fail in quick succession
  • Fix: emergency input_text now requires `browse_stm` check before messaging (anti-spam applies in emergency mode too)
  • Fix: emergency input_text explicitly requires Anna's character — "пиши в своём характере, не как робот-отчёт"
2026-03-19 Auditor: remove swarm_status, update prompt (migration 0041)
  • Fix: removed `swarm_status` and `system_health` from `AUDITOR_TOOLS` — auditor was calling `swarm_status()` to find sessions (returns only RUNNING=empty), ignoring COMPLETED sessions listed in its input_text
  • Fix: migration 0041 — auditor `system_prompt` updated: 7 dimensions (+ world_acceptance), process synced with input_text
2026-03-19 Alarm action_type auto-detection
  • Fix: `_spawn_alarm_session` auto-detects when `action_type="notify"` task description implies execution (python3, запуск, мониторинг, .py, .sh, etc.) and upgrades to `action` — prevents action tasks from being treated as passive reminders and closed without execution
  • Fix: same heuristic applied to `_spawn_grouped_alarm_session`
2026-03-19 Act→Verify→Report enforcement (code-level)
  • **Arch: forced batch separation** — when model batches ACTION + COMM tools together, executor runs only ACTION tools and returns DEFERRED for COMM, forcing model to verify results first then communicate in a separate iteration
  • Fix: prompt rule — explicit "ЗАПРЕЩЕНО смешивать Act + Report в одном batch"
  • Fix: `write_file` response now includes verification hint: "→ Проверь: read_file(path=...) — убедись что содержимое корректно"
  • Fix: `list_directory` on FileNotFoundError suggests `grep_search(pattern='...')` instead of manual traversal
  • Prompt: 5-phase workflow updated — Review phase explicitly requires read_file after write_file
2026-03-19 Auditor Fix: input_text v2 + logging
  • Fix: migration 0040 — auditor `input_text` in DB (from 0030) lacked "close immediately if no sessions" instruction; model improvised instead of following process → 0 assessments across multiple consecutive audits
  • Fix: on `build_auditor_context` exception, fallback explicitly tells model to `close_session()` instead of leaving it disoriented
  • Fix: lookback window +1h safety margin to avoid edge-case gaps at cron boundaries
  • Logging: `build_auditor_context` logs lookback window, since-time, and unassessed session count
  • Logging: auditor context build success/failure logged with char count and session presence
2026-03-18 Alarm Worker Isolation (no user communication)
  • Arch: separate `ALARM_TOOLS` toolset — no `notify_user`, `send_userbot_message`, or any user-facing communication tools
  • Arch: `_alarm_graph` — dedicated LangGraph for alarm worker sessions (action/handoff/code_fix tasks)
  • Arch: alarm-notify (user reminders) still uses full `_agent_graph` with personality prompt
  • Arch: alarm worker gets lightweight ~1000-token prompt (no personality, no Anna character) instead of ~8700-token full prompt
  • Routing: `action_type` in FutureTask metadata determines graph selection — `notify` → full agent, everything else → alarm worker
  • Fix: alarm sessions no longer spam users about internal errors — they broadcast to ISTM and close with `reason='error'`
  • Fix: alarm worker checks ISTM/STM for dedup before executing (prevents repeated sessions for same problem)
2026-03-18 Comm Tool Error Gating + Anti-Hallucination + Delivery Channel Routing
  • Fix: `close_session` in same batch as `notify_user` — close_session now executes AFTER other comm tools; blocked if notify_user/send_message returns error
  • Fix: `notify_user` for cron/system sessions — resolves admin_id from config + auto-detect channel + dashboard fallback
  • Fix: anti-hallucination in auditor — strict dry-report mode; no sessions to assess → close without blog; ban service state claims
  • Fix: anti-hallucination in subconscious — workspace is ephemeral, mandatory tool-based verification
  • Feat: growth critical threshold (< 0.15) — shutdown warning for subconscious
  • Feat: git push awareness — subconscious detects uncommitted changes and pushes via sub-session
  • Feat: mandatory NEXT: block in every subconscious blog entry
  • Feat: verification merged into Phase 1 batch — facts from old blogs checked against current tool output
  • Fix: `GET /api/config/{key}` endpoint missing — auditor config was not loading in UI (enabled/cron/iterations showed defaults)
  • Fix: `close_session` self-blocking — own BLOCKED results (sub-session running) were incorrectly treated as tool errors, blocking retry and forcing unnecessary notify_user spam
  • Fix: `.gitignore` — added `.claude_code_auth_ok`, `.workspace_ready` (runtime artifacts)
  • Refactor: `shared/delivery.py` — unified `resolve_delivery_channel()`: 1) most frequent channel in 24h 2) last message channel 3) dashboard fallback. Replaces hardcoded telethon/aiogram in communication.py, brain.py, context_builder.py
  • Fix: alarm routing SQL used `metadata_` (Python attr) instead of `metadata` (SQL column) — STM resolve never worked
  • Feat: temporal awareness — data validity rules by recency (>2h = stale, absence of data ≠ stability)
  • Feat: git commit review — sub-session reviews files before committing (no blind push)
  • Fix: `_is_tool_error()` false positive — `STDERR:` in run_command output is not an error (git "Everything up-to-date" was blocking close_session)
  • Fix: blog tone regression — anti-hallucination restricts false facts, not diary style
  • Migration 0034-0037: subconscious input_text v10 + auditor strict mode
  • Feat: delivery channel fallback for all sessions — if primary channel fails (user banned, RPC timeout), auto-try alternative channel via `resolve_delivery_channel(exclude=...)` before dashboard fallback. Telethon outbox as async retry queue. Session close unaffected by delivery failure.
  • Feat: subconscious world exploration — Phase 3 priority shift (system stable = act, don't dig), growth-motivated engagement (communication/knowledge/world_acceptance links), channel monitoring with purpose, LTM-driven research, admin freedom
  • Migration 0038: subconscious exploration + growth motivation
  • Fix: anti-echo-chamber — mandatory verification checklist in Phase 1 (evidence hierarchy: 🚨 errors > tool output > blog/ISTM), forgotten problem detection (empty tasks + 🚨 = create task), blog claims without tool verification = unverified hypothesis
  • Fix: admin night rule — 00-08 UTC is hint for admins (can write, but may be sleeping), hard block for non-admins
  • Feat: `system_health()` extended — shows FutureTask overview (⚠ if empty/overdue), ISTM 🚨 alerts (24h), session health stats (COMPLETED/FAILED/ACTIVE with failure % warning). Non-Docker processes now detectable via task/alert absence.
  • Migration 0039: anti-echo-chamber + admin night hint
  • Fix: alarm error handling — error-handling rules + task completion criteria (port open ≠ mail checked) + ISTM broadcast on errors + follow-up task on failure
  • Fix: error gate bypass — `__llm_response__` entries diluted 10-entry window, allowing errors to scroll out. Now filters all `__*` internal entries
  • Fix: error gate satisfaction — `notify_istm` now satisfies gate (alongside `notify_user`), incentivizing ISTM error broadcast instead of add_comment spam
  • Fix: ISTM input validation — `notify_istm` min 5 chars, `add_comment` min 3 chars (prevents "?" spam)
  • Feat: Dockerfile.core — added `iputils-ping`, `netcat-openbsd` (alarm sessions use nc/ping for network checks)
  • Fix: subconscious greeting spam — subconscious had NO visibility into Telegram chats (chats_summary gated by `chat_id is not None`, `_load_stm` only loaded dashboard messages). Now: chats_summary available for all session types, new `outgoing_summary` section shows Anna's recent messages in system prompt
  • Fix: `_build_recent_outgoing_summary()` — new context section for subconscious/alarm: shows own outgoing messages (last 24h) with anti-duplicate warning
  • Fix: behavioral rule "don't greet" — now references 'Мои недавние сообщения' section and uses 12h window instead of vague "за день"
  • Fix: browse_stm diagnostic logging — logs row count + date range on every call for debugging
  • Fix: enum case mismatch — `author_role = 'agent'` → `'AGENT'` in outgoing_summary and `'user'` → `'USER'` in chats context (PostgreSQL enum is uppercase)
  • Feat: dashboard sessions pagination — Prev/Next buttons + page counter (backend already supported limit/offset, frontend was hardcoded to first 50)
2026-03-17 Code Audit Fixes + Dashboard Chat + Security
  • Fix: Dashboard chat messages didn't reach sessions — added `DASHBOARD_CHAT_ID`, `notify_user` now handles `source="dashboard"` (WS-only delivery)
  • Fix: `_trigger_failure_investigation` spawned subconscious even when disabled — added `enabled` check
  • Fix: Alarm sessions hardcoded `telethon` as default channel — now auto-detects available channel (telethon vs aiogram)
  • Fix: `response.content` list handling — centralized `content_to_str()` in `shared/text.py`, fixed summarizer.py + media.py + router.py
  • Fix: LTM total count ignored tag filters — pagination broken when filtering by tags
  • Fix: PgEventBus overflow truncation on reconnect retry — large payloads no longer silently lost
  • Fix: N+1 queries in plans endpoint — batch GROUP BY instead of per-plan COUNT (41→2 queries)
  • Security: WebSocket endpoints now require JWT cookie auth (`/ws/logs`, `/ws/istm`, `/ws/chat`)
  • Security: `backup_id` validated with `[a-zA-Z0-9_]+` regex — prevents path traversal + command injection
  • Infra: Added healthchecks for bot, telethon, watchdog containers (`pgrep -f python`)
  • Fix: `session.category` None guard in subsession timeout message
2026-03-17 Graph Stop on FAILED + Tool Preferences
  • Fix: граф не останавливался после `close_session(reason='error')` — FAILED добавлен в stop-условия supervisor_node
  • Fix: FAILED сессии (reason='error') теперь вызывают `_trigger_failure_investigation` — подсознание реагирует мгновенно
  • Sandbox понижен в приоритете: только для опасных экспериментов. `claude_code()` — первый выбор для кода
2026-03-17 Tool Error Safety + Sub-session Improvements
  • 3-фазное выполнение батчей: ACTION → CHECK → COMMUNICATION — если action tools вернули ошибку, communication tools (notify_user, close_session) блокируются
  • Unified `_is_tool_error()` — единая regex-детекция ошибок вместо фрагментарных проверок
  • `force_complete` запрещён в close_session — сессии обязаны осознанно обрабатывать ошибки
  • `reason='error'` + ISTM broadcast — сессия кричит о помощи подсознанию при неразрешимой ошибке
  • Last-iteration warning — на последней итерации LLM обязана вызвать close_session
  • ISTM broadcast при FAILED без close_session — brain автоматически оповещает подсознание
  • Progressive iteration warnings (3 уровня вместо 1)
  • Правило планирования бюджета итераций — резервировать последнюю на close_session(handoff)
  • При исчерпании лимита — автоматическая сводка из tool results вместо пустого "Лимит итераций"
  • Подсознание: обязательная фаза ISTM intake (browse_istm), аудит ложных отчётов в логах
2026-03-17 WebSocket Real-Time Fixes
  • Fix: ISTM WebSocket message type mismatch (`new_thought` → `thought`) — real-time мысли теперь отображаются
  • Fix: `_mark_session()` публикует CHANNEL_SESSION_STATUS — мгновенное обновление статуса сессий
  • Fix: Dashboard подписан на SUBSESSION_COMPLETE, CONFIG_UPDATED, CATEGORY_UPDATED каналы
  • Fix: Chat WebSocket auto-reconnect (3 сек)
  • Fix: ISTM WebSocket reconnect уменьшен с 10с до 3с
  • Fix: Session/Dashboard auto-refresh по WebSocket событиям session_status (без 15-сек polling)
  • Fix: ISTM fallback polling (10 сек) если WebSocket отвалился
2026-03-22 Per-category rules + sub-session fixes
  • Refactor: Per-category rules architecture — each category gets its own tailored rule set in DB (`{category}_rules`), no more shared 28-rule core with ad-hoc exceptions
  • Migration 0068: seeds 9 per-category rule sets (consciousness, general, subconscious, reviewer, auditor, communicator, code, search, system)
  • Fix: `_build_rules_block()` simplified — reads per-category rules from DB, removes all if/elif category dispatching
  • Fix: Communicator task delivery — task from parent session now sent as `SystemMessage` (not `HumanMessage`) so personality/style isn't overridden by user-role authority
  • Fix: Non-communicator sub-sessions (search/code/system) keep `HumanMessage` — Gemini API requires ≥1 user message in `contents`
  • Fix: Sub-session parser — added regex + persona prefix fallbacks for weak models returning `[close_session(...)]` as plain text
  • Fix: Admin IDs injected into communicator, consciousness, and subconscious contexts from telegram config
  • Fix: Prompt priority reminder for communicator — system prompt instructions override parent task directives
  • Dashboard: Per-category rules tabs with generic API (`/personality/category-rules/{category}`)
  • Cleanup: removed ~240 lines of hardcoded rule arrays (communicator_builtin, auditor_builtin, lifecycle_notes, subsession_quality)
2026-03-21 Communicator rules fix: empty response root cause
  • Fix: Communicator sub-sessions got all 28 core rules (6-phase lifecycle, phase separation ban, "сначала собери") which directly conflicted with communicator's own 3-phase lifecycle → model paralysis → empty responses
  • New: `_COMMUNICATOR_CORE_RULES` — slim 5-rule subset (error retry, handoff, batch, add_comment, ID identification), analogous to `_AUDITOR_BUILTIN_RULES`
  • Fix: `_build_rules_block()` now dispatches by category: auditor/communicator get reduced rulesets, others get full 28
  • Fix: `_CRITICAL_RULES[3]` close_session — allow both batch (`notify_user + close_session`) and separate patterns
  • Fix: Identity rule — "не исполнитель просьб" → simpler "ты коммуникатор" with graceful handoff
  • Fix: Category prompt — "Ты sub-session" → "Задача передана от твоего сознания"
  • Migration 0067: seeds `communicator_core_rules` in DB, updates identity rule and category prompt
2026-03-16 Growth/Auditor + Sponsor Repo
  • Growth Engine: 7-мерная самооценка с асимметричной формулой
  • Аудитор: автоматический аудит сессий по cron, batch-оценка
  • Dashboard: Growth-аналитика, индикатор аудитора
  • Sponsor-репозиторий: filtered sync (без docs/, CLAUDE.md)

Цены

Ежемесячно За год Save 24%
Self-Hosted
Бесплатно навсегда
Вы платите только за вызовы LLM API
  • Полный доступ к исходному коду
  • Все 110+ инструмента включены
  • Неограниченные сессии
  • Поддержка сообщества
  • Без телеметрии и трекинга
  • Ваши данные остаются на вашем сервере
Развернуть сейчас
Enterprise
По запросу
Для команд и организаций
  • Всё из Pro Support
  • Разработка кастомных фич
  • SLA и гарантированное время ответа
  • Помощь с развёртыванием на площадке
  • Кастомные интеграции и API
  • Обучение и онбординг
Связаться с нами

Развёртывание за 3 команды

 
$ git clone <repo-url> anna-agent
$ cd anna-agent
$ ./anna_agent install

Установщик автоматически настроит Docker, базу данных, API-ключи и запустит все сервисы.

Требования

  • Linux-сервер (Ubuntu / Debian / CentOS)
  • Docker & Docker Compose V2
  • 4 ГБ RAM (рекомендуется 8 ГБ)
  • Python 3.12+