From 7d270d3d3178f1535289cdc85a31275ded857f70 Mon Sep 17 00:00:00 2001 From: Mikhail Putilovskij Date: Wed, 22 Apr 2026 01:34:47 +0300 Subject: [PATCH] chore: save handoff context for next agents --- .planning/HANDOFF.json | 109 ++++++++++++++---- .../.continue-here.md | 99 +++++++++------- .planning/reports/20260422-session-report.md | 92 +++++++++++++++ 3 files changed, 238 insertions(+), 62 deletions(-) create mode 100644 .planning/reports/20260422-session-report.md diff --git a/.planning/HANDOFF.json b/.planning/HANDOFF.json index 630bd40..25f1d19 100644 --- a/.planning/HANDOFF.json +++ b/.planning/HANDOFF.json @@ -1,38 +1,107 @@ { "version": "1.0", - "timestamp": "2026-04-19T18:21:44.189Z", + "timestamp": "2026-04-21T22:33:11.666Z", "phase": "04", "phase_name": "Matrix MVP: shared agent context and context management commands", "phase_dir": ".planning/phases/04-matrix-mvp-shared-agent-context-and-context-management-comma", - "plan": null, - "task": null, - "total_tasks": null, + "plan": 3, + "task": 3, + "total_tasks": 3, "status": "paused", "completed_tasks": [ - {"id": 1, "name": "fix(sdk): correct WebSocket URL — /agent_ws/?thread_id= instead of /v1/agent_ws/{id}/", "status": "done", "commit": "fbcf449"}, - {"id": 2, "name": "docs: README runbook for Matrix + platform-agent setup, feature status table", "status": "done", "commit": "b333146"}, - {"id": 3, "name": "feat(matrix): !reset via new platform_chat_id — no platform endpoint needed", "status": "done", "commit": "73c472e"} + { + "id": 1, + "name": "Стабилизировать Matrix MVP runtime: numeric platform_chat_id mapping, staged attachments, clean vendored platform repos", + "status": "done", + "commit": "4524a6a" + }, + { + "id": 2, + "name": "Перевести transport layer на thin adapter над pinned upstream AgentApi и обновить тесты/документацию", + "status": "done", + "commit": "0c2884c" + }, + { + "id": 3, + "name": "Провести финальную локализацию streaming bug и зафиксировать platform-side diagnosis в подробном отчёте", + "status": "done", + "commit": "0c2884c" + } ], "remaining_tasks": [ - {"id": 4, "name": "File ingestion MVP — inline text content for text/code/PDF files", "status": "not_started"}, - {"id": 5, "name": "Execute original Phase 4 plans (04-01, 04-02, 04-03) if still relevant", "status": "not_started"} + { + "id": 4, + "name": "Передать платформенной команде финальный bug report и дождаться triage/fix proposal", + "status": "not_started" + }, + { + "id": 5, + "name": "После ответа платформы решить follow-up phase для surfaces hardening: tokens_used optional, bounded session cache, import/config cleanup, protocol contract tests", + "status": "not_started" + }, + { + "id": 6, + "name": "После platform fix повторно прогнать Matrix live smoke на text/tool/file/image сценариях", + "status": "not_started" + } ], "blockers": [ - {"description": "!save/!load cross-chat broken — StateBackend files are per thread_id, not shared", "type": "external", "workaround": "inform user; full fix requires FilesystemBackend in platform-agent"}, - {"description": "tokens_used always 0 — platform-agent hardcodes MsgEventEnd(tokens_used=0)", "type": "external", "workaround": "none until platform fixes it"}, - {"description": "File attachments — no upload API, StateBackend has no upload_files support", "type": "external", "workaround": "inline text content for text/code/PDF (MVP)"} + { + "description": "После tool/file flow начало ответа может пропадать; raw logs показывают, что первый повреждённый MsgEventTextChunk уже рождается внутри platform-agent до websocket-клиента", + "type": "external", + "workaround": "Только документирование и platform bug report; локально больше не лечить transport hacks" + }, + { + "description": "platform-agent отправляет duplicate END", + "type": "external", + "workaround": "Не чинить в surfaces; держать как известный platform-side дефект до upstream исправления" + }, + { + "description": "Image path падает на больших data URI (>10 MB) и сопровождается WS 1009", + "type": "external", + "workaround": "Удалять oversized staged attachments и предупреждать пользователя; root fix только на платформе" + }, + { + "description": "tokens_used остаётся 0, потому что pinned platform-agent_api.AgentApi не публикует MsgEventEnd наружу", + "type": "external", + "workaround": "Считать текущее значение неизвестным; не городить локальные костыли" + } ], "human_actions_pending": [ - {"action": "Send platform team the file upload ТЗ (POST /upload endpoint, python-multipart, aiofiles)", "context": "Documented in session — 3 files, ~20 lines total change on their side", "blocking": false}, - {"action": "Ask platform team to fix tokens_used in MsgEventEnd (hardcoded 0)", "context": "One line fix in external/platform-agent/src/api/external.py", "blocking": false} + { + "action": "Отправить платформенной команде финальный отчёт docs/reports/2026-04-22-platform-streaming-final-bug-report-ru.md", + "context": "Это основной артефакт с итоговым аудиторским выводом и raw evidence", + "blocking": true + }, + { + "action": "Решить, оформлять ли отдельную follow-up phase в roadmap под production cleanup surfaces после platform triage", + "context": "Сейчас реализация признана рабочей, но проблемной; часть hardening-задач осознанно отложена", + "blocking": false + } ], "decisions": [ - {"decision": "!reset assigns new platform_chat_id (matrix:!roomId#timestamp) instead of calling /reset endpoint", "rationale": "thread_id in LangGraph is just a string key — new ID = fresh context, no platform changes needed", "phase": "04"}, - {"decision": "AgentApiWrapper._build_ws_url uses /agent_ws/?thread_id={chat_id}", "rationale": "platform-agent only exposes /agent_ws/ with thread_id query param, not path segments", "phase": "04"}, - {"decision": "StateBackend is platform-agent default — no real /workspace filesystem exists", "rationale": "create_deep_agent() called without backend param defaults to StateBackend (in-memory)", "phase": "04"}, - {"decision": "platform-agent is a 6-commit prototype — no Docker, no isolation, MemorySaver in-memory", "rationale": "Intentional placeholder while Master + LXC infra is built by platform team", "phase": "04"} + { + "decision": "Не патчить vendored platform repos для рабочей реализации; все platform-side изменения использовались только как временная локальная диагностика и были откатаны", + "rationale": "Нужна чистая граница ответственности между surfaces и платформой", + "phase": "04" + }, + { + "decision": "Оставить transport layer максимально thin: AgentApiWrapper только строит клиента на chat_id, а stream semantics принадлежат upstream AgentApi", + "rationale": "Так проще локализовать баги и не смешивать platform bugs с локальными workaround’ами", + "phase": "04" + }, + { + "decision": "Считать текущую Matrix real integration рабочей, но проблемной из-за upstream streaming/image bugs", + "rationale": "Live flow в целом работает, однако после tool/file path есть подтверждённые platform-side дефекты", + "phase": "04" + }, + { + "decision": "Не лечить missing-first-chunk локальными transport hacks повторно", + "rationale": "После cleanup и raw tracing корень локализован на стороне platform-agent; дальнейшие локальные обходы только размоют диагностику", + "phase": "04" + } ], "uncommitted_files": [], - "next_action": "File ingestion MVP: handle Matrix m.file/m.image events, inline text content for text/code/PDF, honest decline for binary/images", - "context_notes": "Session was architectural investigation + 3 hotfixes. Key finding: platform-agent is much more primitive than assumed (StateBackend not FilesystemBackend, no Docker, singleton process). All 3 fixes are committed and pushed to feat/matrix-direct-agent-prototype (now 29 commits ahead of main). 163 tests green." + "next_action": "Начать с отправки финального bug report платформенной команде; до их triage не менять transport semantics в surfaces повторно", + "context_notes": "Сессия завершилась полной очисткой transport layer до thin adapter, обновлением README, финальным bug report и подтверждением через raw logs, что повреждённый первый chunk рождается внутри platform-agent до websocket-клиента. Рабочая ветка clean, последние meaningful commits: 0c2884c и 4524a6a. Если продолжать работу в surfaces без ответа платформы, единственный разумный фронт — инфраструктурный hardening вокруг known limitations, а не ещё одна попытка локально чинить поток." } diff --git a/.planning/phases/04-matrix-mvp-shared-agent-context-and-context-management-comma/.continue-here.md b/.planning/phases/04-matrix-mvp-shared-agent-context-and-context-management-comma/.continue-here.md index 9911053..576296b 100644 --- a/.planning/phases/04-matrix-mvp-shared-agent-context-and-context-management-comma/.continue-here.md +++ b/.planning/phases/04-matrix-mvp-shared-agent-context-and-context-management-comma/.continue-here.md @@ -1,70 +1,85 @@ --- -context: phase phase: 04-matrix-mvp-shared-agent-context-and-context-management-comma -task: null -total_tasks: null -status: ready_to_execute -last_updated: 2026-04-17T12:34:43.144Z +task: 3 +total_tasks: 3 +status: paused +last_updated: 2026-04-21T22:33:11.666Z --- -Phase 4 planning is COMPLETE. 3 plans written, verified by checker, revised once. -Ready to execute — no blockers. +Phase 04 как MVP-фаза по сути закрыта: Matrix real backend работает, transport layer очищен до thin adapter над pinned upstream `platform-agent_api.AgentApi`, ветка чистая и запушенная. Текущее состояние зафиксировано как "working but problematic": после tool/file flow остаётся подтверждённый upstream bug платформы, из-за которого начало ответа может пропадать. -Before executing: pull platform-agent origin/main: - git -C external/platform-agent pull +Ключевой результат последней сессии: raw tracing показал, что первый повреждённый `MsgEventTextChunk` появляется уже внутри `platform-agent` до websocket-клиента. Это сняло основное подозрение с `surfaces`. -- CONTEXT.md — all design decisions from 2026-04-16 session -- RESEARCH.md — AgentApi lifecycle, platform-agent origin/main state, store patterns -- 04-01-PLAN.md — Replace AgentSessionClient with AgentApiWrapper (Wave 1) -- 04-02-PLAN.md — !save/!load/!reset/!context commands (Wave 2) -- 04-03-PLAN.md — Dockerfile + docker-compose (Wave 2, parallel with 04-02) -- Checker passed after 1 revision (3 blockers fixed: tag rename, missing return, external/ modification) +- Переведён `sdk/agent_api_wrapper.py` в тонкий factory/shim без собственной stream-semantics. +- Переведён `sdk/real.py` на pinned upstream contract: без post-END drain, без custom listener, без локальной реконструкции стрима. +- Обновлены тесты под новый transport layer: + - `tests/platform/test_real.py` + - `tests/adapter/matrix/test_dispatcher.py` + - `tests/core/test_integration.py` +- README обновлён под новое состояние интеграции и known limitations. +- Создан финальный отчёт: `docs/reports/2026-04-22-platform-streaming-final-bug-report-ru.md`. +- Временная диагностика в vendored `platform-agent` и `platform-agent_api` была использована только для расследования и полностью удалена; nested repos снова clean. +- Последний кодовый commit с рабочим состоянием: `0c2884c` (`refactor: use thin upstream transport adapter`). -- Execute Wave 1: 04-01 (AgentApi migration) -- Execute Wave 2: 04-02 + 04-03 in parallel +- Передать платформенной команде финальный отчёт и дождаться triage/fix proposal. +- После ответа платформы решить, открываем ли отдельную follow-up phase для production hardening в `surfaces`. +- После platform fix повторить live smoke: + - text-only + - staged attachments + - tool/file flow + - large image failure path -- AgentApi wrapped in AgentApiWrapper (sdk/agent_api_wrapper.py) — subclasses AgentApi, overrides _listen() to capture MsgEventEnd.tokens_used. Do NOT modify external/platform-agent_api/ -- build_thread_key and thread_id in WS URL removed entirely — architecture is one container = one chat -- !reset → POST {AGENT_BASE_URL}/reset; returns "unavailable" if 404 (endpoint not yet in platform-agent) -- !save/!load are agent-mediated: bot sends text message to agent, agent uses write_file/read_file in /workspace/contexts/ -- !load numeric selection intercepted in on_room_message before dispatcher.dispatch() -- lambda_agent_api install needs --ignore-requires-python (pyproject.toml says >=3.14, runs fine on 3.11) +- Больше не трогать vendored platform repos ради рабочей реализации. +- Больше не добавлять локальные transport hacks, маскирующие streaming bug. +- Считать текущий missing-first-chunk баг platform-side дефектом до опровержения raw evidence. +- Оставить `tokens_used=0` как честное ограничение current upstream contract, не симулировать это значение локально. -None blocking execution. - -Pending (non-blocking): -- POST /reset endpoint needs to be requested from platform team -- Credentials rotation (Matrix password, OpenRouter key sk-or-v1-d27c07...) +- Platform-side streaming bug: после tool/file flow начало ответа может пропадать. +- Duplicate `END` на стороне платформы. +- Image path на больших вложениях падает с `data-uri > 10 MB` и `WS 1009`. +- Без ответа платформенной команды дальнейший transport-layer surgery в `surfaces` не имеет инженерного смысла. -## Required Reading (in order) -1. `04-CONTEXT.md` — locked decisions -2. `04-RESEARCH.md` — AgentApi interface details, platform-agent findings -3. `external/platform-agent_api/lambda_agent_api/agent_api.py` — AgentApi source (read before implementing wrapper) - -## Infrastructure State -- platform-agent local clone: 11 commits BEHIND origin/main — pull before executing -- surfaces-bot branch: feat/matrix-direct-agent-prototype -- platform-agent branch: main (local has our old thread_id patch on top) - -Phase 4 is the main MVP delivery phase. The core insight: platform-agent uses thread_id="default" as a singleton by design — one container per chat, isolation at container level. We stop fighting this and embrace it. AgentSessionClient (our custom WS client) gets replaced by the platform team's AgentApi, wrapped to capture tokens_used. Four context management commands added: !save (agent writes summary to file), !load (agent reads file, user picks by number), !reset (POST /reset endpoint), !context (show session info). +Важная ментальная модель: + +- `surfaces` сейчас максимально близок к upstream transport semantics. +- Если снова полезет corruption чанков, исходная презумпция должна быть "сначала смотреть platform-agent", а не придумывать новый локальный workaround. +- Главные артефакты для чтения перед продолжением: + 1. `README.md` + 2. `docs/reports/2026-04-22-platform-streaming-final-bug-report-ru.md` + 3. `sdk/agent_api_wrapper.py` + 4. `sdk/real.py` + 5. `tests/platform/test_real.py` + +Если придётся продолжать без платформы, разумные задачи уже не про баг с чанками, а про clean/prod-ready улучшения вокруг него: + +- сделать `tokens_used` optional в локальном контракте +- развести `RealPlatformClient` на pool/adapter слои +- добавить bounded session cache / idle eviction +- убрать `sys.path` import hack в пользу нормальной dependency wiring +- переименовать конфиг `AGENT_WS_URL` в более честный `AGENT_BASE_URL` +- добавить protocol contract tests против fake WS server -1. git -C external/platform-agent pull (sync to origin/main) -2. /clear -3. /gsd-execute-phase 4 +Start with: + +1. Открыть `docs/reports/2026-04-22-platform-streaming-final-bug-report-ru.md` +2. Отправить этот отчёт платформенной команде как основной артефакт +3. Не менять transport layer до получения их ответа + +Если работа продолжается автономно без ответа платформы, следующий допустимый шаг — оформлять отдельную follow-up phase на hardening `surfaces`, а не повторно "чинить" стрим локальными обходами. diff --git a/.planning/reports/20260422-session-report.md b/.planning/reports/20260422-session-report.md new file mode 100644 index 0000000..9044d2b --- /dev/null +++ b/.planning/reports/20260422-session-report.md @@ -0,0 +1,92 @@ +# 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`*