20 KiB
Director Refactor Implementation Checklist
Goal
Bring the runtime into conformance with the architecture in AGENTS.md:
- all collector-produced
EventEnvelopeobjects go throughDirector - all command-result events go through the same canonical event flow
Directoris the only runtime component allowed to route to cache and outbox- derivator emits derived events only through
Director - workflows must not rely on
Nonesinks or silent fallbacks
Hard Rules For The Refactor
- Do not preserve the current direct-cache path.
- Do not keep compatibility shims for
director_sinknaming. - Do not allow
sink=Noneor equivalent no-op behavior for derivator workflows. - Do not store full
EventEnvelopebytes inpayload_store. - Do not enqueue outbox items anywhere except
Director. - 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 | Noneserialize_payload_message(envelope: events_pb2.EventEnvelope) -> bytes | Noneevent_envelope_to_record_with_payload(...) -> tuple[EventRecord, bytes | None]
Concrete diff intent:
- Leave
event_envelope_to_record(...)in place temporarily. - Implement
extract_payload_message()by readingenvelope.WhichOneof("payload"). - Implement
serialize_payload_message()by serializing the oneof payload message only. - Implement
event_envelope_to_record_with_payload()by:- calling
event_envelope_to_record(...) - calling
serialize_payload_message(...) - returning both
- calling
- Do not serialize the full envelope in any new helper.
tests/unit/test_core_runtime.py
Add tests:
EventEnvelopewithraw_journalpayload returns payload bytes forRawJournalPayloadEventEnvelopewith no payload returnsNoneevent_envelope_to_record_with_payload()preservespayload_kindandpayload_len
tests/unit/test_batcher.py
Add or update tests so reconstructed envelope payload round-trips from payload-message bytes only.
Exit Criteria
- There is a single helper that yields
record + payload_bytes. - No new path stores full envelope bytes.
- 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 = Noneoutbox: OutboxQueue | None = Nonederivator_interest_sink: Callable[[EventRecord], None] | None = Nonetrace_sink: Callable[[Mapping[str, Any]], None] | None = None
Concrete diff intent:
- Remove the
DirectorSinkprotocol entirely if it becomes unused. - Update
DirectorOutcome:- add
outbox_item: OutboxItem | None = None - add
payload_attached: bool = False - add
effective_cache_applied: bool = False
- add
- Rewrite
route():- compute
decision = route_envelope(...) - compute
effective_cache = decision.cache or decision.outbox or decision.derivator_interest - build
(record, payload_bytes)viaevent_envelope_to_record_with_payload(...) - if
effective_cache:- require
self.cache is not None, else raiseRuntimeError - append to cache with
payload=payload_bytes
- require
- if
decision.outbox:- require
self.outbox is not None, else raiseRuntimeError - enqueue using stored
seq_no,event_id,envelope.routing.priority
- require
- if
decision.derivator_interest:- require cached record exists
- invoke
derivator_interest_sink(record)if configured
- compute
- Add
_trace(stage: str, **fields)and emit:director.ingest.begindirector.route.decisiondirector.cache.appenddirector.outbox.enqueuedirector.derivator_interestdirector.ingest.end
- Keep
ingest()as a thin wrapper overroute().
src/agent/director/__init__.py
Update exports if DirectorSink is removed.
src/agent/director/routing.py
Concrete diff intent:
- Keep current policy logic.
- Add helper:
requires_cache(decision: DirectorRouteDecision) -> bool
- Do not add fallback behavior if cache or outbox is missing.
tests/unit/test_director.py
Rewrite tests to cover:
cache_enabled=Truecaches record and payloadoutbox_enabled=Trueimplies cache append and outbox enqueue- derivator interest implies cache append
- requesting outbox without cache available raises
- payload bytes are attached when payload exists
Exit Criteria
Directorcan fully ingest an envelope into cache/outbox without app glue.OutboxQueue.enqueue()is reached fromDirector.Directorhas 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:
- In
AgentApplicationdataclass fields, adddirector_runtime. - Add
director():- return existing
director_runtimeif present - else create
Director(cache=self.cache, outbox=self.outbox, derivator_interest_sink=self._director_derivator_interest_sink, trace_sink=self._director_trace_sink)
- return existing
- 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
- record ingest trace stage
- Delete all direct
event_envelope_to_record(...)andself.cache.append(...)logic from app ingest path. - 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.appendimmediately after collector sink - start expecting:
runtime.ingest.begindirector.ingest.begindirector.route.decisiondirector.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
AgentApplicationno longer appends collector envelopes directly to cache.AgentApplicationowns a realDirector.- 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:
JournalSinkdirector_sink
With:
EnvelopeSinkevent_sink
Concrete diff intent:
- Rename type alias
JournalSinktoEnvelopeSink. - Rename
director_sinkconstructor arg toevent_sink. - Rename field
self.director_sinktoself.event_sink. - Rename
from_toml(..., director_sink=...)tofrom_toml(..., event_sink=...). - In accepted path, replace:
if outcome.envelope is not None and self.director_sink is not None:- with
self.event_sink(outcome.envelope)
- Remove optional runtime semantics for
event_sinkif 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
- No collector file uses the name
director_sink. - All collectors emit only envelopes to app ingress.
- 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:
- Make
sinkmandatory. - In
__init__, raiseValueErrorifsink is None. - Keep
_emit_result(...)always calling sink. - 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:
- Move common envelope-building code here.
- Support both WPA and system command results.
- Set routing:
cache_enabled=Trueoutbox_enabled=Truepriority=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(...):
- map
CommandResult.executor_nameor target kind tosource_name - convert result to envelope via
command_result_to_envelope(...) - send envelope into
self._ingest_envelope(envelope, origin="command")
Exit Criteria
CommandCoordinatoralways emits results.- 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:
- Remove sink type alias at top of file.
- Remove
result_sinkfrom__init__. - Remove
result_sinkfromfrom_toml. - In
execute(), stop calling_emit_result(result)on any branch. - Return
CommandResultonly.
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:
- Same removal pattern as WPA executor.
- 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
- No executor emits protobuf events directly.
- 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:
- Replace
sink=Nonestyle construction with mandatory callables. - Remove any branch like:
if self.sink is None: returnif self.command_coordinator is None: return
- In derived event emission path:
- call
self.event_sink(envelope)
- call
- In command initiation path:
- call
self.command_sink(request)
- call
- 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:
- derived events always go through event sink
- workflow command requests always go through command sink
- 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
- There is no
sink=Noneworkflow runtime. - All derived events go to
Director. - 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:
- Keep the current cache lookup by
seq_no. - Tighten
_payload_from_record(...):- if
record.payload_kindimplies payload butpayload_refis missing, treat as missing payload path
- if
- Extend
BatchBuilderResultif needed:- add
missing_payload_seq_nos: tuple[int, ...] = ()
- add
- Do not add fallback for full-envelope reconstruction.
src/agent/sender/loops.py
Concrete diff intent:
- Leave normal enqueue logic untouched except that sender must assume outbox was filled by
Director. - Handle missing payload/missing record as sender-level transport-preparation failure, not by reconstructing synthetic envelopes.
tests/unit/test_batcher.py
Add tests:
- outbox item with missing cache record ends up in
missing_seq_nos - 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
- Sender path depends only on
OutboxQueue + CacheAPI + PayloadStore. - 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:
- Remove hardcoded zeros for:
events_cached_totalevents_outbox_enqueued_totalderived_events_total- command counters
- Aggregate from:
self.director().stats()self.command_coordinator().stats()self.outbox.stats()self._ensure_derivator_worker().state().statsself._sender_loop_or_none().stats()if present
src/agent/cli.py
Concrete diff intent:
- Update ingest trace rendering to include:
director.cache_applieddirector.outbox_applieddirector decision reasonsorigin
- Remove assumptions that
cache.appendfollows 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
- CLI and trace reflect the actual director-based event path.
- 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:
journal -> director -> cachejournal -> director -> cache + outboxwpa_ctrl collector -> director -> cache + outboxif fixture support exists
tests/integration/test_command_director_flow.py
Create file.
Add tests:
submit_command -> started + succeeded envelopes -> director -> cache + outbox- rejection path also enters canonical event flow
tests/integration/test_derivator_director_flow.py
Create file.
Add tests:
cache window -> workflow -> derived envelope -> director -> cache- workflow-generated command request ->
CommandCoordinator
Exit Criteria
- Architecture is verified end-to-end.
- 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:
- Search for:
_cache_envelope_collector_result_sinkdirector_sinkresult_sink=sink=None
- Remove remaining obsolete code and comments.
Exit Criteria
- There is exactly one event ingress path for envelopes.
- There is exactly one route-to-outbox path.
- There are no workflow fallbacks.
Repo-Wide Grep Checklist
Run after each commit:
rg -n "_cache_envelope|_collector_result_sink|director_sink" src testsrg -n "sink=None" src/agent/derivator src/agent/app.pyrg -n "result_sink" src/agent/executors src/agent/app.pyrg -n "outbox.enqueue\\(" src testsrg -n "cache.append\\(" src/agent/app.py src/agent/director src tests
Expected final state:
cache.append(appears inDirectorand cache tests, not in app ingest pathoutbox.enqueue(appears inDirectorand sender retry logic onlydirector_sinkappears nowhere- derivator
sink=Noneappears nowhere
Recommended Execution Order
- Commit 1
- Commit 2
- Commit 3
- Commit 4
- Commit 5
- Commit 6
- Commit 7
- Commit 8
- Commit 9
- Commit 10
- Final cleanup
Do not reorder these commits. The sequence is chosen to avoid backtracking:
- payload contract first
- routing owner second
- app ingress third
- producers next
- command path after ingress exists
- derivator after command and director hooks exist
- sender verification after outbox is real
- diagnostics after runtime path stabilizes
- integration tests after architecture settles