wf-agent2/DIRECTOR_REFACTOR_CHECKLIST.md

20 KiB

Director Refactor Implementation Checklist

Goal

Bring the runtime into conformance with the architecture in AGENTS.md:

  • all collector-produced EventEnvelope objects go through Director
  • all command-result events go through the same canonical event flow
  • Director is the only runtime component allowed to route to cache and outbox
  • derivator emits derived events only through Director
  • workflows must not rely on None sinks or silent fallbacks

Hard Rules For The Refactor

  1. Do not preserve the current direct-cache path.
  2. Do not keep compatibility shims for director_sink naming.
  3. Do not allow sink=None or equivalent no-op behavior for derivator workflows.
  4. Do not store full EventEnvelope bytes in payload_store.
  5. Do not enqueue outbox items anywhere except Director.
  6. Do not emit protobuf envelopes directly from executors.

Commit 1

Commit Message

refactor: add canonical envelope-to-record payload conversion helpers

Purpose

Prepare the payload contract before wiring Director into runtime.

Files

src/agent/core/converters.py

Replace:

  • current single-step usage of event_envelope_to_record(...) as the only ingestion helper

Add:

  • extract_payload_message(envelope: events_pb2.EventEnvelope) -> Message | None
  • serialize_payload_message(envelope: events_pb2.EventEnvelope) -> bytes | None
  • event_envelope_to_record_with_payload(...) -> tuple[EventRecord, bytes | None]

Concrete diff intent:

  1. Leave event_envelope_to_record(...) in place temporarily.
  2. Implement extract_payload_message() by reading envelope.WhichOneof("payload").
  3. Implement serialize_payload_message() by serializing the oneof payload message only.
  4. Implement event_envelope_to_record_with_payload() by:
    • calling event_envelope_to_record(...)
    • calling serialize_payload_message(...)
    • returning both
  5. Do not serialize the full envelope in any new helper.

tests/unit/test_core_runtime.py

Add tests:

  1. EventEnvelope with raw_journal payload returns payload bytes for RawJournalPayload
  2. EventEnvelope with no payload returns None
  3. event_envelope_to_record_with_payload() preserves payload_kind and payload_len

tests/unit/test_batcher.py

Add or update tests so reconstructed envelope payload round-trips from payload-message bytes only.

Exit Criteria

  1. There is a single helper that yields record + payload_bytes.
  2. No new path stores full envelope bytes.
  3. Tests prove payload bytes are payload-message bytes only.

Commit 2

Commit Message

refactor: make director own cache append and outbox enqueue

Purpose

Turn Director into the authoritative runtime router for cache and outbox.

Files

src/agent/director/director.py

Replace constructor signature:

  • remove outbox_sink: DirectorSink | None = None
  • remove derivator_sink: DirectorSink | None = None

Add constructor signature:

  • cache: CacheAPI | None = None
  • outbox: OutboxQueue | None = None
  • derivator_interest_sink: Callable[[EventRecord], None] | None = None
  • trace_sink: Callable[[Mapping[str, Any]], None] | None = None

Concrete diff intent:

  1. Remove the DirectorSink protocol entirely if it becomes unused.
  2. Update DirectorOutcome:
    • add outbox_item: OutboxItem | None = None
    • add payload_attached: bool = False
    • add effective_cache_applied: bool = False
  3. Rewrite route():
    • compute decision = route_envelope(...)
    • compute effective_cache = decision.cache or decision.outbox or decision.derivator_interest
    • build (record, payload_bytes) via event_envelope_to_record_with_payload(...)
    • if effective_cache:
      • require self.cache is not None, else raise RuntimeError
      • append to cache with payload=payload_bytes
    • if decision.outbox:
      • require self.outbox is not None, else raise RuntimeError
      • enqueue using stored seq_no, event_id, envelope.routing.priority
    • if decision.derivator_interest:
      • require cached record exists
      • invoke derivator_interest_sink(record) if configured
  4. Add _trace(stage: str, **fields) and emit:
    • director.ingest.begin
    • director.route.decision
    • director.cache.append
    • director.outbox.enqueue
    • director.derivator_interest
    • director.ingest.end
  5. Keep ingest() as a thin wrapper over route().

src/agent/director/__init__.py

Update exports if DirectorSink is removed.

src/agent/director/routing.py

Concrete diff intent:

  1. Keep current policy logic.
  2. Add helper:
    • requires_cache(decision: DirectorRouteDecision) -> bool
  3. Do not add fallback behavior if cache or outbox is missing.

tests/unit/test_director.py

Rewrite tests to cover:

  1. cache_enabled=True caches record and payload
  2. outbox_enabled=True implies cache append and outbox enqueue
  3. derivator interest implies cache append
  4. requesting outbox without cache available raises
  5. payload bytes are attached when payload exists

Exit Criteria

  1. Director can fully ingest an envelope into cache/outbox without app glue.
  2. OutboxQueue.enqueue() is reached from Director.
  3. Director has no cache/outbox fallbacks.

Commit 3

Commit Message

refactor: replace app direct cache path with director ingress

Purpose

Remove the current bypass in AgentApplication.

Files

src/agent/app.py

Delete:

  • _collector_result_sink(self, envelope: events_pb2.EventEnvelope) -> None
  • _cache_envelope(self, envelope: events_pb2.EventEnvelope) -> None

Add:

  • field director_runtime: Director | None = field(default=None, repr=False, compare=False)
  • method director(self) -> Director
  • method _ingest_envelope(self, envelope: events_pb2.EventEnvelope, *, origin: str, now_mono_ns_value: int | None = None) -> DirectorOutcome
  • method _director_trace_sink(self, record: Mapping[str, Any]) -> None
  • method _director_derivator_interest_sink(self, record: EventRecord) -> None

Concrete diff intent:

  1. In AgentApplication dataclass fields, add director_runtime.
  2. Add director():
    • return existing director_runtime if present
    • else create Director(cache=self.cache, outbox=self.outbox, derivator_interest_sink=self._director_derivator_interest_sink, trace_sink=self._director_trace_sink)
  3. Add _ingest_envelope(...):
    • record ingest trace stage runtime.ingest.begin
    • call self.director().ingest(envelope, now_mono_ns_value=...)
    • record ingest trace stage runtime.ingest.end
    • return DirectorOutcome
  4. Delete all direct event_envelope_to_record(...) and self.cache.append(...) logic from app ingest path.
  5. Update any helper that assumed direct cache append.

src/agent/observability/ingest_trace.py

No structural change required unless current trace schema rejects director fields.

tests/unit/test_ingest_trace.py

Replace expectations:

  • stop expecting app-level direct cache.append immediately after collector sink
  • start expecting:
    • runtime.ingest.begin
    • director.ingest.begin
    • director.route.decision
    • director.cache.append
    • optional director.outbox.enqueue
    • runtime.ingest.end

tests/unit/test_cache_api.py

No change unless app-level helpers referenced removed code.

Exit Criteria

  1. AgentApplication no longer appends collector envelopes directly to cache.
  2. AgentApplication owns a real Director.
  3. All new ingest trace stages reflect the director-based path.

Commit 4

Commit Message

refactor: rename collector director sink to envelope event sink

Purpose

Make collector interfaces match actual architecture and remove misleading naming.

Files

src/agent/collectors/journal.py

Replace:

  • JournalSink
  • director_sink

With:

  • EnvelopeSink
  • event_sink

Concrete diff intent:

  1. Rename type alias JournalSink to EnvelopeSink.
  2. Rename director_sink constructor arg to event_sink.
  3. Rename field self.director_sink to self.event_sink.
  4. Rename from_toml(..., director_sink=...) to from_toml(..., event_sink=...).
  5. In accepted path, replace:
    • if outcome.envelope is not None and self.director_sink is not None:
    • with self.event_sink(outcome.envelope)
  6. Remove optional runtime semantics for event_sink if collector is expected to emit accepted envelopes.

src/agent/collectors/dbus.py

Apply the same rename and accepted-event emission changes.

src/agent/collectors/wpa_ctrl.py

Apply the same rename and accepted-event emission changes.

src/agent/collectors/navigation.py

Apply the same rename and accepted-event emission changes.

src/agent/collectors/__init__.py

Update exported names and imports.

src/agent/app.py

In _build_collector_from_config(...), replace:

  • director_sink=self._collector_result_sink

With:

  • event_sink=lambda envelope: self._ingest_envelope(envelope, origin="collector")

Use a named helper instead of inline lambda if cleaner:

  • _collector_event_sink(self, envelope: EventEnvelope) -> None

tests/unit/test_journal_collector.py

Update constructor calls from director_sink= to event_sink=.

tests/unit/test_dbus_collector.py

Update constructor calls from director_sink= to event_sink=.

tests/unit/test_wpa_ctrl_collector.py

Update constructor calls from director_sink= to event_sink=.

tests/unit/test_navigation_collector.py

Update constructor calls from director_sink= to event_sink=.

Exit Criteria

  1. No collector file uses the name director_sink.
  2. All collectors emit only envelopes to app ingress.
  3. Tests use event_sink.

Commit 5

Commit Message

refactor: make command coordinator emit canonical results through app ingress

Purpose

Move command-result emission to the coordinator/app boundary and remove envelope emission from executors.

Files

src/agent/commands/coordinator.py

Change constructor signature:

  • from sink: CommandResultSink | None = None
  • to sink: CommandResultSink

Concrete diff intent:

  1. Make sink mandatory.
  2. In __init__, raise ValueError if sink is None.
  3. Keep _emit_result(...) always calling sink.
  4. Remove any branches that tolerate no sink.

src/agent/commands/results.py

Create new file.

Add:

  • command_result_to_envelope(result: CommandResult, *, source_name: str, interface: str = "", executor_name: str = "") -> events_pb2.EventEnvelope

Concrete diff intent:

  1. Move common envelope-building code here.
  2. Support both WPA and system command results.
  3. Set routing:
    • cache_enabled=True
    • outbox_enabled=True
    • priority=0

src/agent/commands/__init__.py

Export command_result_to_envelope.

src/agent/app.py

Replace _build_command_coordinator(...) body.

Current:

  • return CommandCoordinator(router=router)

New:

  • return CommandCoordinator(router=router, sink=self._on_command_result)

Add _on_command_result(...):

  1. map CommandResult.executor_name or target kind to source_name
  2. convert result to envelope via command_result_to_envelope(...)
  3. send envelope into self._ingest_envelope(envelope, origin="command")

Exit Criteria

  1. CommandCoordinator always emits results.
  2. Command results enter runtime only as envelopes through Director.

Commit 6

Commit Message

refactor: remove protobuf result emission from executors

Purpose

Executors must execute commands, not inject canonical events themselves.

Files

src/agent/executors/wpa_ctrl.py

Delete:

  • WpaCtrlResultSink
  • constructor arg result_sink
  • field self.result_sink
  • _emit_result(self, result: CommandResult) -> None
  • function command_result_to_envelope(...)

Concrete diff intent:

  1. Remove sink type alias at top of file.
  2. Remove result_sink from __init__.
  3. Remove result_sink from from_toml.
  4. In execute(), stop calling _emit_result(result) on any branch.
  5. Return CommandResult only.

src/agent/executors/system.py

Delete:

  • SystemResultSink
  • constructor arg result_sink
  • field self.result_sink
  • _emit_result(self, result: CommandResult) -> None
  • function system_command_result_to_envelope(...)

Concrete diff intent:

  1. Same removal pattern as WPA executor.
  2. Return only CommandResult.

src/agent/executors/__init__.py

Remove exports of deleted envelope helper functions.

tests/unit/test_wpa_ctrl_executor.py

Replace any assertions about emitted envelopes with assertions about returned CommandResult.

tests/unit/test_system_executor.py

Replace any assertions about emitted envelopes with assertions about returned CommandResult.

Exit Criteria

  1. No executor emits protobuf events directly.
  2. Executor output contract is only CommandResult.

Commit 7

Commit Message

refactor: make derivator sinks mandatory and route derived events through director

Purpose

Eliminate workflow fallbacks and enforce architecture for derived events and workflow-triggered commands.

Files

src/agent/derivator/worker.py

Change constructor signature:

  • remove optional sink arguments
  • require event_sink
  • require command_sink

Concrete diff intent:

  1. Replace sink=None style construction with mandatory callables.
  2. Remove any branch like:
    • if self.sink is None: return
    • if self.command_coordinator is None: return
  3. In derived event emission path:
    • call self.event_sink(envelope)
  4. In command initiation path:
    • call self.command_sink(request)
  5. If workflow config allows command initiation but command sink is missing, fail at construction time, not runtime.

src/agent/derivator/base.py

Adjust protocol definitions so sink callables are not optional.

src/agent/app.py

In _build_derivator_worker(...), replace:

  • sink=None

With:

  • event_sink=lambda envelope: self._ingest_envelope(envelope, origin="derivator")
  • command_sink=lambda request: self.submit_command(request, now_mono_ns_value=None)

Prefer named methods instead of inline lambdas:

  • _on_derived_envelope(...)
  • _submit_derivator_command(...)

tests/unit/test_derivator_worker.py

Rewrite tests to assert:

  1. derived events always go through event sink
  2. workflow command requests always go through command sink
  3. constructing a worker without mandatory sinks is an error

tests/unit/test_wifi_scan_summary.py

Update tests for sink semantics and no-fallback behavior.

Exit Criteria

  1. There is no sink=None workflow runtime.
  2. All derived events go to Director.
  3. All workflow commands go to CommandCoordinator.

Commit 8

Commit Message

refactor: align sender and batcher with director-owned outbox pipeline

Purpose

Validate that sender path depends only on outbox references and cache-stored payload bytes.

Files

src/agent/sender/batcher.py

Concrete diff intent:

  1. Keep the current cache lookup by seq_no.
  2. Tighten _payload_from_record(...):
    • if record.payload_kind implies payload but payload_ref is missing, treat as missing payload path
  3. Extend BatchBuilderResult if needed:
    • add missing_payload_seq_nos: tuple[int, ...] = ()
  4. Do not add fallback for full-envelope reconstruction.

src/agent/sender/loops.py

Concrete diff intent:

  1. Leave normal enqueue logic untouched except that sender must assume outbox was filled by Director.
  2. Handle missing payload/missing record as sender-level transport-preparation failure, not by reconstructing synthetic envelopes.

tests/unit/test_batcher.py

Add tests:

  1. outbox item with missing cache record ends up in missing_seq_nos
  2. payload kind with missing payload bytes is reported as missing payload

tests/unit/test_sender_loops.py

Update expectations if batch builder result changes.

Exit Criteria

  1. Sender path depends only on OutboxQueue + CacheAPI + PayloadStore.
  2. No fallback reconstruction path exists.

Commit 9

Commit Message

refactor: replace placeholder app stats and trace stages with director-based metrics

Purpose

Make diagnostics reflect the real architecture.

Files

src/agent/app.py

Replace stats() implementation.

Concrete diff intent:

  1. Remove hardcoded zeros for:
    • events_cached_total
    • events_outbox_enqueued_total
    • derived_events_total
    • command counters
  2. Aggregate from:
    • self.director().stats()
    • self.command_coordinator().stats()
    • self.outbox.stats()
    • self._ensure_derivator_worker().state().stats
    • self._sender_loop_or_none().stats() if present

src/agent/cli.py

Concrete diff intent:

  1. Update ingest trace rendering to include:
    • director.cache_applied
    • director.outbox_applied
    • director decision reasons
    • origin
  2. Remove assumptions that cache.append follows collectors directly.

tests/unit/test_ingest_trace.py

Rewrite snapshots to include director-based stages.

tests/unit/test_cli.py

Update CLI expectations for stats and trace output if necessary.

Exit Criteria

  1. CLI and trace reflect the actual director-based event path.
  2. No placeholder counter remains where real runtime stats are available.

Commit 10

Commit Message

test: add end-to-end routing coverage for collectors commands and derivator

Purpose

Lock the new architecture with integration coverage.

Files

tests/integration/test_collector_director_flow.py

Create file.

Add tests:

  1. journal -> director -> cache
  2. journal -> director -> cache + outbox
  3. wpa_ctrl collector -> director -> cache + outbox if fixture support exists

tests/integration/test_command_director_flow.py

Create file.

Add tests:

  1. submit_command -> started + succeeded envelopes -> director -> cache + outbox
  2. rejection path also enters canonical event flow

tests/integration/test_derivator_director_flow.py

Create file.

Add tests:

  1. cache window -> workflow -> derived envelope -> director -> cache
  2. workflow-generated command request -> CommandCoordinator

Exit Criteria

  1. Architecture is verified end-to-end.
  2. Regressions that reintroduce bypass paths fail tests immediately.

Final Cleanup Commit

Commit Message

chore: remove obsolete direct-ingest code paths and update docs

Purpose

Remove dead code and align repository docs with actual runtime.

Files

README.md

Update runtime flow description to match implemented architecture.

AGENTS.md

Only update if implementation details or sequencing notes need to be marked as completed.

Entire repo

Remove dead imports, stale comments, and obsolete helper names.

Concrete diff intent:

  1. Search for:
    • _cache_envelope
    • _collector_result_sink
    • director_sink
    • result_sink=
    • sink=None
  2. Remove remaining obsolete code and comments.

Exit Criteria

  1. There is exactly one event ingress path for envelopes.
  2. There is exactly one route-to-outbox path.
  3. There are no workflow fallbacks.

Repo-Wide Grep Checklist

Run after each commit:

  1. rg -n "_cache_envelope|_collector_result_sink|director_sink" src tests
  2. rg -n "sink=None" src/agent/derivator src/agent/app.py
  3. rg -n "result_sink" src/agent/executors src/agent/app.py
  4. rg -n "outbox.enqueue\\(" src tests
  5. rg -n "cache.append\\(" src/agent/app.py src/agent/director src tests

Expected final state:

  1. cache.append( appears in Director and cache tests, not in app ingest path
  2. outbox.enqueue( appears in Director and sender retry logic only
  3. director_sink appears nowhere
  4. derivator sink=None appears nowhere

  1. Commit 1
  2. Commit 2
  3. Commit 3
  4. Commit 4
  5. Commit 5
  6. Commit 6
  7. Commit 7
  8. Commit 8
  9. Commit 9
  10. Commit 10
  11. Final cleanup

Do not reorder these commits. The sequence is chosen to avoid backtracking:

  1. payload contract first
  2. routing owner second
  3. app ingress third
  4. producers next
  5. command path after ingress exists
  6. derivator after command and director hooks exist
  7. sender verification after outbox is real
  8. diagnostics after runtime path stabilizes
  9. integration tests after architecture settles