wf-agent3/north_bridge_implement_plan.md

16 KiB
Raw Permalink Blame History

WiFi Agent Gen3 — Plan for north_bridge introduction

1. Цель внедрения

Цель внедрения — заменить текущую export/director-centric часть архитектуры на north_bridge как единый application-level northbound delivery module.

В результате:

  • adapter core продолжает формировать canonical dataclasses и конвертировать их в protobuf;
  • основным экспортным получателем становится north_bridge;
  • north_bridge получает protobuf события от адаптеров;
  • north_bridge доставляет события в WebUI;
  • north_bridge получает команды от WebUI и возвращает ответы;
  • прежние stdout directors и senders выводятся из архитектуры и не поддерживаются как legacy path.

2. Migration principles

  • Не ломать adapter skeleton runtime shape.
  • Не переносить WebSocket/session logic в adapter layer.
  • Сохранить protobuf как единый inter-module format.
  • Команды инициируются только из control plane sources: CLI, north_bridge, scheduler, derivator и tests.
  • Выполнять migration без сохранения legacy director path как постоянного или переходного architectural target.
  • Каждый Step = отдельный commit.
  • Каждый Step должен оставлять проект в работоспособном состоянии.

3. Phase plan

Phase 0. Architecture alignment

Step 0.1 — Introduce north_bridge into architecture docs

Goal
Зафиксировать целевую архитектуру в документации.

Scope

  • Обновить architecture document.
  • Заменить primary export/director language на north_bridge-centric language.
  • Зафиксировать вывод прежних stdout directors из целевой архитектуры.

Result

  • Архитектурная документация соответствует целевой модели.

Commit
docs: introduce north bridge as primary northbound delivery module


Phase 1. Shared contracts and protobuf alignment

Step 1.1 — Add north bridge shared ports

Goal
Ввести shared ports для north bridge.

Scope

  • Добавить в app.shared.contracts:
    • NorthBridgeIngressPort
    • NorthBridgeCommandPort
    • NorthBridgeStatusSnapshot
  • Не ломать существующие CommandRequest / CommandResult.

Result

  • Появились стабильные shared contracts для north bridge.

Commit
feat: add shared north bridge ports and status contracts


Step 1.2 — Add protobuf schemas for north bridge protocol

Goal
Определить protobuf protocol envelopes for WebUI boundary.

Scope

  • Добавить versioned protobuf messages for:
    • ClientEnvelope
    • ServerEnvelope
    • CommandRequestEnvelope
    • CommandResponseEnvelope
    • EventEnvelope
    • SubscribeRequest
    • UnsubscribeRequest
    • ErrorResponse
    • Ping / Pong
  • Сохранить separation between application event wire messages and client protocol envelopes.

Result

  • Есть protobuf contract для северной границы.

Commit
feat: add protobuf schemas for north bridge client server protocol


Step 1.3 — Add protobuf conversion helpers for north bridge

Goal
Подготовить кодеки и мапперы для north bridge.

Scope

  • Добавить conversion helpers:
    • application protobuf -> north bridge event envelope
    • command result -> response envelope
    • protocol error -> error envelope

Result

  • Есть единая protobuf conversion layer for north bridge.

Commit
feat: add protobuf conversion helpers for north bridge protocol


Phase 2. Adapter export redirection

Step 2.1 — Replace MessageExportPort target semantics

Goal
Перенаправить архитектурный смысл export path from director to north bridge.

Scope

  • Уточнить MessageExportPort semantics либо ввести dedicated ingress port usage in runtime wiring.
  • Не менять internal adapter dataclass pipeline.
  • Зафиксировать, что adapter export delivers protobuf to application northbound ingress.

Result

  • Export path ориентирован на north bridge ingress, а не на director sink.

Commit
refactor: redirect adapter export path semantics to north bridge ingress


Step 2.2 — Add runtime wiring for adapter to north bridge protobuf delivery

Goal
Подключить адаптеры к north bridge на уровне app wiring.

Scope

  • Обновить composition root.
  • Сделать так, чтобы adapter runtime публиковал protobuf wire messages в NorthBridgeIngressPort.
  • Сохранить fake ingress implementations for tests.

Result

  • Адаптеры могут отдавать protobuf directly into north bridge ingress path.

Commit
feat: wire adapter runtime export flow to north bridge ingress


Phase 3. North bridge module skeleton

Step 3.1 — Create north_bridge package skeleton

Goal
Создать каркас модуля app.north_bridge.

Scope

  • Создать пакеты:
    • protocol
    • websocket
    • session
    • events
    • command
    • subscriptions
    • runtime
    • config
    • observability
    • compat
  • Добавить package imports and smoke tests.

Result

  • Структура north bridge создана.

Commit
chore: create north bridge package skeleton


Step 3.2 — Implement north bridge config schema

Goal
Ввести конфиг north bridge.

Scope

  • Добавить typed config schema:
    • bind host / port
    • websocket path
    • heartbeat intervals
    • session idle timeout
    • queue limits
    • subscription policy
    • Добавить loader and validation.

Result

  • North bridge конфигурируется типизированно.

Commit
feat: add north bridge config schema and loader


Phase 4. Ingress and fanout core

Step 4.1 — Implement in-process north bridge ingress service

Goal
Реализовать основной ingress path для protobuf application events.

Scope

  • Реализовать NorthBridgeIngressPort.
  • Принимать protobuf application event messages.
  • Передавать их во внутренний event fanout path.
  • Добавить in-memory test implementation.

Result

  • North bridge способен принимать protobuf события от adapters.

Commit
feat: implement north bridge ingress service for protobuf events


Step 4.2 — Implement subscription registry

Goal
Добавить основу для адресной доставки событий клиентам.

Scope

  • Реализовать session-scoped subscription registry.
  • Поддержать subscribe / unsubscribe.
  • Поддержать matching by event type/topic/basic envelope fields.

Result

  • North bridge умеет рассчитывать delivery set.

Commit
feat: implement north bridge subscription registry


Step 4.3 — Implement event fanout service

Goal
Реализовать маршрутизацию событий к активным сессиям.

Scope

  • Реализовать fanout from ingress to subscribed sessions.
  • Поддержать per-session outbound queue handoff.
  • Добавить tests on matching and delivery selection.

Result

  • Есть event fanout core.

Commit
feat: implement north bridge event fanout service


Phase 5. WebSocket and session layer

Step 5.1 — Implement websocket endpoint

Goal
Поднять двустороннюю северную транспортную границу.

Scope

  • Реализовать WebSocket server endpoint.
  • Поддержать binary protobuf frames.
  • Добавить protocol decode/encode boundary.

Result

  • WebUI может подключаться к north bridge.

Commit
feat: implement websocket endpoint for north bridge


Step 5.2 — Implement session manager

Goal
Добавить управление WebSocket session lifecycle.

Scope

  • Реализовать session states.
  • Добавить connect/disconnect handling.
  • Добавить heartbeat / idle timeout support.
  • Добавить outbound queue attachment to session.

Result

  • North bridge стал session-aware.

Commit
feat: implement north bridge session manager


Step 5.3 — Implement protocol codec

Goal
Реализовать protobuf client/server protocol handling.

Scope

  • Decode client envelopes.
  • Encode server envelopes.
  • Map protocol errors to protobuf error responses.
  • Add codec tests.

Result

  • Есть стабильная protocol boundary.

Commit
feat: implement north bridge protobuf protocol codec


Phase 6. Command path

Step 6.1 — Implement north bridge command bridge

Goal
Подключить клиентские команды к application command path.

Scope

  • Добавить explicit CLI subcommand wf-agent3 command ... as the control-plane entrypoint.
  • Реализовать NorthBridgeCommandPort usage.
  • Принимать CommandRequestEnvelope.
  • Передавать shared command requests во внутренний command path.
  • Возвращать CommandResponseEnvelope.
  • Command executors должны immediately export canonical command result event to north_bridge after completion, without a separate follow-up request.
  • scan должен быть explicit command, not an automatic acquisition operation.
  • DBusConnectionDriver.receive() and worker loop do not initiate commands.

Result

  • Клиентские команды проходят через north bridge.

Commit
feat: implement north bridge command bridge


Step 6.2 — Add correlation and request tracking

Goal
Обеспечить корректное сопоставление команд и ответов.

Scope

  • Support request_id, correlation_id, session_id.
  • Add request tracking for logs and observability.
  • Add timeout/error handling.

Result

  • Command request/response flow becomes reliable.

Commit
feat: add correlation and request tracking to north bridge commands


Phase 7. Compatibility transition

Step 7.1 — Remove stdout_proto and stdout_json from target runtime wiring

Goal
Убрать прежние stdout-based directors из целевого runtime path.

Scope

  • Удалить primary runtime wiring на stdout_proto и stdout_json.
  • Обновить smoke/integration scenarios под north_bridge-centric flow.
  • Не переносить stdout directors внутрь north bridge как compatibility layer.

Result

  • Целевой runtime больше не зависит от stdout-based directors.

Commit
refactor: remove stdout based directors from target runtime wiring


Phase 8. Runtime integration

Step 8.1 — Implement north bridge runtime orchestration

Goal
Собрать весь north bridge в единый runtime module.

Scope

  • Config loading
  • ingress service
  • websocket endpoint
  • session manager
  • subscriptions
  • event fanout
  • command bridge
  • observability hooks

Result

  • North bridge работает как единый application module.

Commit
feat: implement north bridge runtime orchestration


Step 8.2 — Integrate north bridge into application composition root

Goal
Подключить north bridge как основной application-level northbound module.

Scope

  • Обновить composition root / app wiring.
  • Instantiate north bridge runtime in target run mode.
  • Connect adapters to north bridge ingress.
  • Keep tests and local mode operational.

Result

  • North bridge включён в основную архитектуру приложения.

Commit
feat: integrate north bridge into application composition root


Phase 9. Observability and status

Step 9.1 — Add north bridge observability

Goal
Встроить north bridge в общую observability model.

Scope

  • Track:
    • active sessions
    • events delivered
    • events dropped
    • commands processed
    • protocol errors
    • queue pressure
  • Publish NorthBridgeStatusSnapshot.

Result

  • North bridge полностью наблюдаем.

Commit
feat: add north bridge observability and status snapshots


Phase 10. Verification

Step 10.1 — Add E2E flow: adapter to north bridge to subscribed client

Goal
Проверить основной event path без legacy director layer.

Scope

  • Adapter emits protobuf event.
  • North bridge receives it.
  • Subscribed client receives event.
  • Assert observability and delivery behavior.

Result

  • Основной northbound event path подтверждён end-to-end.

Commit
test: add end to end adapter to north bridge subscribed client flow


Step 10.2 — Add E2E flow: webui command through north bridge

Goal
Проверить северный command path.

Scope

  • WebSocket client sends command.
  • North bridge decodes protobuf.
  • Command bridge invokes application command path.
  • Command completion is published as a canonical event to north_bridge immediately after executor returns.
  • Response returns to client.

Result

  • Командный северный канал подтверждён.

Commit
test: add end to end websocket command flow through north bridge


Step 10.3 — Add E2E flow: async event push to subscribed client

Goal
Проверить основной northbound event scenario.

Scope

  • WebSocket client subscribes.
  • Adapter event enters north bridge.
  • Client receives protobuf event.
  • Verify queue and session behavior.

Result

  • Асинхронная доставка событий подтверждена.

Commit
test: add end to end async event push to subscribed client


Phase 11. Cleanup of legacy architecture

Step 11.1 — Remove primary director references from docs and runtime naming

Goal
Убрать старую смысловую модель director as primary sink.

Scope

  • Update docs and comments.
  • Rename runtime wiring terms where needed.
  • Keep only compatibility mentions.

Result

  • Код и документация консистентны с north_bridge-centric architecture.

Commit
refactor: remove primary director semantics from docs and runtime naming


  1. Step 0.1
  2. Step 1.1
  3. Step 1.2
  4. Step 1.3
  5. Step 2.1
  6. Step 2.2
  7. Step 3.1
  8. Step 3.2
  9. Step 4.1
  10. Step 4.2
  11. Step 4.3
  12. Step 5.1
  13. Step 5.2
  14. Step 5.3
  15. Step 6.1
  16. Step 6.2
  17. Step 7.1
  18. Step 8.1
  19. Step 8.2
  20. Step 9.1
  21. Step 10.1
  22. Step 10.2
  23. Step 10.3
  24. Step 11.1

5. Definition of Done

Migration is complete when:

  • north bridge exists as a separate application-level package;
  • adapters export protobuf into north bridge ingress;
  • north bridge is the primary northbound delivery module;
  • WebUI communicates with the application via protobuf over WebSocket;
  • client commands and responses flow through north bridge;
  • async events are delivered to subscribed clients;
  • stdout_proto/stdout_json исключены из целевой архитектуры;
  • docs and runtime naming no longer treat director as the primary target architecture.

6. Anti-goals for this migration stage

Do not:

  • move websocket/session logic into adapter core;
  • bypass shared contracts;
  • keep direct adapter imports of application delivery implementations;
  • preserve stdout-based directors as active legacy or compatibility architecture;
  • collapse application event wire messages and client protocol envelopes into one unstructured schema.