From 3340c126d619345e7bcf2a2ee3213c9f531e57ac Mon Sep 17 00:00:00 2001 From: Mikhail Putilovskij Date: Sun, 3 May 2026 23:42:34 +0300 Subject: [PATCH] docs: remove legacy threads and reports from planning state --- .planning/.continue-here.md | 72 ---------- .planning/reports/20260422-session-report.md | 92 ------------ ...trix-dev-prototype-agent-platform-state.md | 133 ------------------ .../threads/matrix-file-ingestion-context.md | 81 ----------- 4 files changed, 378 deletions(-) delete mode 100644 .planning/.continue-here.md delete mode 100644 .planning/reports/20260422-session-report.md delete mode 100644 .planning/threads/matrix-dev-prototype-agent-platform-state.md delete mode 100644 .planning/threads/matrix-file-ingestion-context.md diff --git a/.planning/.continue-here.md b/.planning/.continue-here.md deleted file mode 100644 index f27ae84..0000000 --- a/.planning/.continue-here.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -context: pre-planning -phase: 05-deployment -task: 0 -total_tasks: 0 -status: ready-to-plan -last_updated: 2026-04-27T18:44:51.832Z ---- - - -Phase 04 полностью завершена и закоммичена на ветке `feat/matrix-direct-agent-prototype` (135 тестов зелёные). Этот сеанс был посвящён архитектуре деплоя — изучили платформенные репозитории и обсудили топологию с командой платформы. Вся информация о деплое зафиксирована в `docs/deploy-architecture.md`. Phase 05 не спланирована, следующий шаг — `/gsd-plan-phase`. - - - - -- Изучены актуальные версии platform-agent, platform-agent_api, platform-master -- Уточнена топология деплоя с платформой (схема с reverse proxy и shared volume) -- Созданы `docs/deploy-architecture.md` — полное summary архитектуры деплоя - - - - -- Смержить `feat/matrix-direct-agent-prototype` → `main` -- Спланировать Phase 05 (деплой) -- Выполнить Phase 05: - - Обновить `config/matrix-agents.yaml` (добавить `base_url`, `workspace_path`, `user_agents`) - - Обновить `sdk/real.py` (AgentApi конструктор, file transfer) - - Обработка `MsgEventSendFile` в Matrix адаптере (скачать файл из volume, отправить пользователю) - - Обработка входящих файлов от Matrix пользователей (сохранить в workspace, передать в attachments) - - Написать `docker-compose.yml` для деплоя - - - - -- **Топология**: один инстанс Matrix-бота, один агент-контейнер на пользователя, reverse proxy на `lambda.coredump.ru:7000` роутит по пути `/agent_N/` -- **Файлы**: через shared volume `/agents/`. Surface пишет файл в `/agents/{N}/`, передаёт относительный путь в `attachments=["file.txt"]`. При `MsgEventSendFile(path)` — читает файл из `/agents/{N}/{path}` и шлёт в Matrix. -- **Agent API**: используем master (`attachments` и `MsgEventSendFile` есть). Ветку `#9-clientside-tool-call` игнорируем — она в разработке и убирает нужные фичи. -- **Конфиг**: два словаря — `user_id → agent_id` и `agent_id → {base_url, workspace_path}` -- **Master**: не используем для MVP. Статический конфиг. При готовности Master — мигрируем. -- **chat_id**: пока `chat_id=0` (один контекст на пользователя) - - - - -- **AGENT_ID + COMPOSIO_API_KEY**: Composio смержен в main platform-agent, теперь обязателен. Значения нужны от Азамата перед деплоем. -- **agent_api #9**: убирает `attachments` и `MsgEventSendFile` — если смержат до деплоя, сломает наш file transfer. Нужно уточнить сроки. - - -## Required Reading (in order) - -1. `docs/deploy-architecture.md` — полная архитектура деплоя, топология, API, файловый обмен, конфиг -2. `adapter/matrix/routed_platform.py` — текущий RoutedPlatformClient -3. `sdk/real.py` — текущий AgentApi wrapper -4. `config/matrix-agents.yaml` и `config/matrix-agents.example.yaml` — текущий формат конфига (нужно расширить) - -## Infrastructure State - -- Ветка: `feat/matrix-direct-agent-prototype` — готова к merge, 135 тестов зелёные -- `config/matrix-agents.yaml` — незакоммичен (live config, добавить в `.gitignore`) -- `docs/deploy-architecture.md` — незакоммичен (новый файл этого сеанса) -- platform-agent main: Composio уже смержен (требует `AGENT_ID`, `COMPOSIO_API_KEY` в env) - - -Архитектура деплоя полностью прояснена. Нет неизвестных блокеров (кроме env-переменных от платформы). Phase 05 — чисто инженерная задача: обновить конфиг, sdk, Matrix адаптер, написать compose. Всё что нужно знать — в docs/deploy-architecture.md. - - - -1. /clear -2. /gsd-resume-work — прочитает этот файл и предложит план Phase 05 -3. Прочитать docs/deploy-architecture.md -4. /gsd-plan-phase 05 - diff --git a/.planning/reports/20260422-session-report.md b/.planning/reports/20260422-session-report.md deleted file mode 100644 index 9044d2b..0000000 --- a/.planning/reports/20260422-session-report.md +++ /dev/null @@ -1,92 +0,0 @@ -# GSD Session Report - -**Generated:** 2026-04-21T22:33:11.666Z -**Project:** surfaces-bot -**Milestone:** v1.0 — Production-ready surfaces - ---- - -## Session Summary - -**Duration:** Single session -**Phase Progress:** Phase 04 implemented; current follow-up work is audit, stabilization, and platform bug localization -**Plans Executed:** 0 formal GSD plans executed in this session; work was focused on post-implementation audit and cleanup -**Commits Made:** 6 - -## Work Performed - -### Phases Touched - -- **Phase 04** — Matrix MVP follow-up after implementation: - - completed audit of platform patches vs surface-owned responsibilities - - removed dependence on local platform modifications for `chat_id` - - switched Matrix integration to numeric `platform_chat_id` mapping on our side - - cleaned transport layer to a thin adapter over upstream `AgentApi` - - updated README and run instructions - - produced final Russian bug report with raw-trace-based diagnosis - -### Key Outcomes - -- Platform repos are clean and synced to pinned upstream commits. -- Matrix real backend works with numeric surrogate `platform_chat_id`. -- `surfaces` transport layer no longer owns custom stream semantics. -- Final diagnosis was narrowed: missing-first-chunk bug is now considered platform-side with direct raw evidence. -- Working state was committed and pushed on `feat/matrix-direct-agent-prototype`. - -### Decisions Made - -- Do not patch vendored platform repos for the working implementation. -- Keep `surfaces` transport layer thin and upstream-aligned. -- Treat the current streaming bug as platform-side unless new evidence disproves it. -- Do not add new local stream workarounds that would blur responsibility. - -## Files Changed - -- `README.md` -- `adapter/matrix/bot.py` -- `sdk/agent_api_wrapper.py` -- `sdk/real.py` -- `tests/platform/test_real.py` -- `tests/adapter/matrix/test_dispatcher.py` -- `tests/core/test_integration.py` -- `docs/reports/2026-04-22-platform-streaming-final-bug-report-ru.md` - -Planning / handoff artifacts updated: - -- `.planning/HANDOFF.json` -- `.planning/phases/04-matrix-mvp-shared-agent-context-and-context-management-comma/.continue-here.md` -- `.planning/reports/20260422-session-report.md` - -## Blockers & Open Items - -- Platform-side streaming bug after tool/file flow. -- Duplicate `END` from platform. -- Image path failure on oversized `data:` URI. -- `tokens_used` remains unavailable from pinned upstream client. - -## Estimated Resource Usage - -| Metric | Estimate | -|--------|----------| -| Commits | 6 | -| Files changed | 8 code/docs files in the main deliverable, plus planning artifacts | -| Plans executed | 0 formal plans in this session | -| Subagents spawned | 0 | - -> **Note:** Token and cost estimates require API-level instrumentation. -> These metrics reflect observable session activity only. - ---- - -### Recent Commits - -- `0c2884c` — `refactor: use thin upstream transport adapter` -- `569824e` — `refactor: shrink agent api wrapper to thin adapter` -- `4d917ac` — `docs: add thin transport adapter plan` -- `3a3fcdc` — `docs: add thin transport adapter design` -- `7a2ad86` — `docs: clarify matrix file sending flow` -- `4524a6a` — `feat: finalize matrix platform audit and docs` - ---- - -*Generated by `$gsd-session-report`* diff --git a/.planning/threads/matrix-dev-prototype-agent-platform-state.md b/.planning/threads/matrix-dev-prototype-agent-platform-state.md deleted file mode 100644 index facd575..0000000 --- a/.planning/threads/matrix-dev-prototype-agent-platform-state.md +++ /dev/null @@ -1,133 +0,0 @@ -# Thread: Matrix dev prototype — состояние агента и платформы - -## Status: IN PROGRESS - -## Goal - -Зафиксировать текущее состояние платформы для последующей разработки Matrix dev прототипа, -в котором команды разработки скиллов смогут быстро добавлять и обкатывать скиллы. - -## Context - -*Исследование проведено 2026-04-14. Репозитории: `external/platform-agent`, `external/platform-agent_api`, `external/platform-master`.* - -### Решение по деплою: локальный контейнер у каждого разработчика - -`platform-master` не готов для общего деплоя: -- lifecycle management контейнеров (TTL, cleanup, переиспользование сессий) — в ветке `feat/storage`, не смержено в main -- без него при общем деплое контейнеры висят вечно, ресурсы не освобождаются - -Локальный вариант: `make up-dev` — полностью рабочий, volume mount `./workspace:/workspace/`, hot reload src. - -### Архитектура изоляции контекстов - -`AgentService` — singleton с `thread_id = "default"` — это **намеренно**. Архитектура Master предполагает один контейнер `platform-agent` на один чат. Изоляция на уровне контейнеров, не thread_id. Фиксить не нужно. - -### Система скиллов (deepagents) - -`SkillsMiddleware` в `deepagents` полностью готов: -- скилл = директория с `SKILL.md` (YAML frontmatter + markdown инструкции) -- progressive disclosure: агент видит имя+описание в system prompt, читает полный файл по требованию -- загружается один раз при старте сессии, кэшируется в LangGraph state - -**НЕ подключено** в `platform-agent/src/agent/base.py` — отсутствует одна строка: -```python -skills=["/workspace/skills/"] -``` -Это задача для команды платформы. - -### Workflow разработчика скилла - -``` -workspace/ - skills/ - my-skill/ - SKILL.md ← редактируешь здесь (live через volume mount) - helper.py ← вспомогательные файлы - config/ - my-skill.json ← токены и настройки (пишет агент при первом запуске) -``` - -1. Редактируешь `SKILL.md` -2. `!new` в Matrix (новая сессия = скиллы перечитываются) -3. Проверяешь поведение -4. Повторяешь - -Агент может **сам установить скилл** из GitHub: -- `execute` → git clone -- `write_file` → положить в `/workspace/skills/` -- после `!new` скилл активен - -### Конфигурация скиллов (токены, API ключи) - -Агент управляет конфигом сам: -- первый запуск: спрашивает пользователя → пишет в `/workspace/config/skill-name.json` -- последующие запуски: читает из файла -- файл персистентен между сессиями (volume mount) - -### Входящий протокол (что принимает агент) - -`ClientMessage` — только `text: str`. Файлы и изображения не поддерживаются. -Задача для платформы — расширить протокол. - -### Исходящий протокол (что шлёт агент) - -Новые события с `origin/main` (апрель 2026): -- `AGENT_EVENT_TOOL_CALL_CHUNK` — агент вызывает инструмент -- `AGENT_EVENT_TOOL_RESULT` — результат инструмента -- `AGENT_EVENT_CUSTOM_UPDATE` — произвольный прогресс - -**Наш `sdk/agent_session.py` падает на этих событиях** (`raise PlatformError("Unexpected agent message")`). -Нужно починить — это наша задача, ~10 строк. - -### AgentApi из lambda_agent_api - -Готовый production-клиент с правильным lifecycle (`connect()`, `close()`, `send_message()` как `AsyncIterator`). -Наш `sdk/agent_session.py` дублирует его функциональность. Стоит заменить. - -### Инструменты агента из коробки - -- `ls`, `read_file`, `write_file`, `edit_file`, `glob`, `grep` — файловые операции в workspace -- `execute` — shell под изолированным OS-пользователем `agent` -- `write_todos` — список задач -- `task` — вызов субагентов - -### Запуск локально - -```bash -# .env минимально необходимый: -PROVIDER_URL=https://openrouter.ai/api/v1 -PROVIDER_API_KEY=<ключ> -PROVIDER_MODEL=anthropic/claude-sonnet-4-6 - -# Dev контейнер: -make up-dev # требует AGENT_API_PATH=../platform-agent_api в env -``` - -Dev Dockerfile монтирует `./workspace:/workspace/` и `./src:/app/src` (hot reload). - -## Что нужно от платформы - -1. Добавить `skills=["/workspace/skills/"]` в `platform-agent/src/agent/base.py` -2. Поддержка файлов/изображений в `ClientMessage` (не срочно для MVP) -3. Lifecycle management контейнеров в Master (для общего деплоя, не срочно) - -## Что делаем мы - -1. Починить `sdk/agent_session.py` — обработка tool-событий вместо исключения -2. (опционально) Заменить `AgentSessionClient` на `AgentApi` из `lambda_agent_api` - -## References - -- `external/platform-agent` — локальный клон, наш патч `1dca2c1` (thread_id) поверх `1e9fa1f` -- `external/platform-agent_api` — локальный клон, актуальный (origin/master = `bb20a84`) -- `external/platform-master` — локальный клон, активная разработка в `feat/storage-s02` -- `docs/superpowers/specs/2026-04-08-matrix-direct-agent-prototype-design.md` -- `docs/superpowers/plans/2026-04-08-matrix-direct-agent-prototype.md` - -## Next Steps - -1. Запросить у команды платформы: подключение `SkillsMiddleware` в `base.py` -2. Починить `sdk/agent_session.py` — обработать tool-события -3. Написать первый тестовый скилл (`workspace/skills/hello/SKILL.md`) и проверить end-to-end -4. Документировать workflow для разработчиков скиллов diff --git a/.planning/threads/matrix-file-ingestion-context.md b/.planning/threads/matrix-file-ingestion-context.md deleted file mode 100644 index 0ccb079..0000000 --- a/.planning/threads/matrix-file-ingestion-context.md +++ /dev/null @@ -1,81 +0,0 @@ -# Thread: Matrix file ingestion and agent-visible storage contract - -## Status: IN PROGRESS - -## Goal - -Сохранить текущий контекст сессии для следующего агента и зафиксировать следующую архитектурную развилку: как принимать вложения из Matrix и делать их доступными агенту. - -## Current State - -Phase 4 Matrix MVP уже собран и проверен на уровне per-room routing: -- обычные сообщения теперь идут в `platform_chat_id`, а не в общий локальный `C1/C2` -- `!context` показывает состояние текущего Matrix-чата -- `!save` и `!load` привязаны к текущему room-context -- `PrototypeStateStore` хранит live state per context -- последние изменения закоммичены в `feat/matrix-direct-agent-prototype` - -Коммиты, которые важно знать: -- `c11c8ec` `feat(task-5): scope matrix context state per room` -- `07c5078` `feat(task-7): verify matrix per-room context routing` - -## What We Learned About Platform Runtime - -Текущий `external/platform-agent` не является отдельным контейнером на чат. -Фактическая модель сейчас такая: -- один FastAPI-процесс -- singleton `AgentService` -- `thread_id` используется как ключ памяти в LangGraph, а не как контейнерная изоляция -- файловой изоляции на чат сейчас нет -- `/workspace` как общий mount для Matrix bot и platform-agent сейчас не настроен -- отдельного upload API для вложений в текущем коде не видно - -Ключевые файлы: -- `external/platform-agent/src/api/external.py` -- `external/platform-agent/src/agent/service.py` -- `external/platform-agent/src/agent/base.py` - -## File Handling Requirement - -Пользовательский запрос на текущем этапе: -- принимать файл или сообщение с файлом из Matrix -- сохранять файл локально -- передавать агенту явный сигнал, что к сообщению есть вложения -- сообщать, где лежит файл - -Но есть техническое ограничение: -- если Matrix bot пишет файл только в своём контейнере, platform-agent его не увидит -- значит нужен либо общий storage, либо upload в платформу, либо контейнеризация platform-agent с общим volume - -## Recommended Design Direction - -Самый прагматичный MVP-вариант: -- хранить вложения в общем каталоге, который виден и Matrix bot, и platform-agent -- формировать для агента структурированный payload с: - - локальным путём - - original filename - - mime type - - attachment type -- если есть текст пользователя, дополнять сообщение краткой summary-подсказкой про вложения -- если прислан только файл, отправлять synthetic message вроде “пользователь прислал файл” - -Если общий каталог невозможен в текущем runtime: -- следующий вариант это upload endpoint в platform-agent -- Matrix surface скачивает файл и загружает его в платформу, а платформа уже кладёт его в своё доступное хранилище - -## Open Questions - -1. Где должен жить shared storage: host path, docker volume или platform-side volume? -2. Нужен ли немедленный upload API в platform-agent, или сначала достаточно shared path? -3. Должны ли файлы быть scoped per room/platform_chat_id, а не per user? - -## Next Step For Another Agent - -1. Подтвердить runtime-модель хранения файлов. -2. Проверить, как сейчас запускаются Matrix bot и platform-agent в реальной dev-схеме. -3. После выбора storage contract начать с изменений в Matrix attachment ingestion. - -## Notes - -- Контекст этой сессии сохранён как отдельный thread, потому что текущий следующий рискованный шаг уже не про context routing, а про файловый transport. -- Не смешивать этот трек с незавершённой историей про `!branch`: upstream branch/snapshot API всё ещё не подтверждён.