chore: save handoff context for next agents

This commit is contained in:
Mikhail Putilovskij 2026-04-22 01:34:47 +03:00
parent 0c2884c2b1
commit 7d270d3d31
3 changed files with 238 additions and 62 deletions

View file

@ -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
---
<current_state>
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`.
</current_state>
<completed_work>
- 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`).
</completed_work>
<remaining_work>
- 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
</remaining_work>
<decisions_made>
- 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, не симулировать это значение локально.
</decisions_made>
<blockers>
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` не имеет инженерного смысла.
</blockers>
## 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)
<context>
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
</context>
<next_action>
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`, а не повторно "чинить" стрим локальными обходами.
</next_action>