Skip to main content

Architecture

task-interleaving follows the fleet's hexagonal (ports and adapters) layout: dependencies point inward, the domain imports nothing from the rest of the module, and only cmd/ wires the layers together. Everything on this page is on develop; the one thing that is not (an MCP adapter) is called out.

Layout​

LayerPathRole
Domaininternal/domain/policyPolicy aggregate (InterleavingPolicy): per-site settings, versioned, immutable. SiteID, TaskType, Settings.
Domaininternal/domain/travelThe travel-distance port travel.Model and its v1 implementation Rectilinear (rectilinear-v1). Point, Place.
Domaininternal/domain/recommendThe pure recommender Recommend(Input); OpenTask, Candidate; RectilinearFor(policy).
Domaininternal/domain/stationtripStationTrip aggregate: position, hint lifecycle, domain events HintIssued, HintConsumed, HintExpired.
Applicationinternal/application/usecasesThe use cases (see Use cases), Intake (claim-and-apply skeleton of the consumers), Ranker (the recommender over the local copies), TripWriter (save a trip and hand its events to the outbox).
Applicationinternal/application/ports, repository, outboxThe OUT ports (PolicyRepo, StationTripRepo, TaskPool, LocationBook, EventSink, ProcessedEvents, IdempotencyStore, UnitOfWork, Clock, IDGenerator), the records they exchange and the already-encoded outbox Message. ports holds only interfaces.
Inbound adapterinternal/adapters/inbound/httpchi router for apis/openapi.yaml: handlers, RFC 7807 problem mapping (errors.go), the Idempotency-Key middleware, /healthz and /readyz. No auth middleware.
Inbound adapterinternal/adapters/inbound/kafkaThe fulfillment and layout consumers: CloudEvents decode, dispatch on the full type, retry with backoff, dead-letter topic. Decode only; every effect is a use case.
Inbound adapterinternal/adapters/inbound/expiryTimer-driven worker that calls ExpireHints every interval.
Outbound adapterinternal/adapters/outbound/postgrespgxpool repositories, unit of work (pgtx), outbox repository, embedded migrations (migrate.go, top-level migrations/).
Outbound adapterinternal/adapters/outbound/memoryIn-memory implementation of every port: a test double for the unit and BDD suites. The shipped binary never imports it (TestRuntimeBinaryHasNoInMemoryAdapters).
Outbound adapterinternal/adapters/outbound/systemThe production Clock and hint-id generator, the two adapters that need no infrastructure.
Outbound adapterinternal/adapters/outbound/eventsMaps domain facts to CloudEvents outbox messages (Sink, encoder.go).
Outbound adapterinternal/adapters/outbound/outboxThe relay loop that drains the outbox to a sink.
Outbound adapterinternal/adapters/outbound/kafkaNewWriter (acks=all, hash balancer, no fixed topic, AllowAutoTopicCreation), RelaySink and BrokerCheck (the Kafka half of /readyz: a broker answers a topic-less metadata request).
Kafka envelopeinternal/adapters/kafka/cloudeventsThe only place a CloudEvents 1.0 envelope is built or decoded: New(Spec), Decode, ContentTypeHeader, Type, DataSchema. Constants Repo = "task-interleaving", Subdomain = "wes", Context = "task-interleaving", Source = "/warehouse/task-interleaving".
Supportinternal/bootretryExponential-backoff retry for the first outbound dials at boot.
Composition rootcmd/apimain.go (run, shutdown order), config.go (env parsing, loadBootConfig), adapters.go (the Postgres adapters), consumers.go, relay.go (workers), topics.go (the consumed and produced topic lists and the boot log line; topics are not part of /readyz).
Test supportinternal/testing/{kafkatest,pgtest,repocontract}Shared testcontainers helpers (the test broker has topic auto-creation off) and the repository contract suite run against both the memory and Postgres adapters.
Fitness testsinternal/architecturearch-go and source-scanning tests; see below.

The domain declares one port, the distance model:

// internal/domain/travel/travel.go
type Model interface {
Name() string
Distance(from, to Place) (float64, bool)
}

Distance returns metres and whether the distance is known; a Place with no point, or with a non-finite coordinate, is unknown, never 0. The recommender takes the model as input (Input.Model, required: ErrNoModel otherwise) and recommend.RectilinearFor(policy) builds the v1 model from the policy's VerticalWeight. A later model (aisle and cross-aisle routing, a candidate named in ADR 0002) implements the same interface under its own ADR.

Binaries and ports​

BinaryRolePortProbes
cmd/apiREST API, hint-expiry worker, outbox relay and the two Kafka consumers run in one process, all always on, on real Postgres and Kafka (ADR 0006).HTTP_ADDR, default :8080GET /healthz (liveness), GET /readyz (drain gate, Postgres ping, a Kafka broker answers a metadata request; never topics)
cmd/mcpRead-only MCP server (Streamable HTTP) over the existing queries; no relay, consumer or Kafka (ADR 0007).MCP_ADDR, default :8090GET /healthz
cmd/a2aRead-only A2A (Agent2Agent) server over the same read use cases: JSON-RPC at / and /a2a, Agent Card at /.well-known/agent-card.json; no relay, consumer or Kafka (ADR 0009).A2A_ADDR, default :8093GET /healthz
cmd/ti-projectorThe only writer of the analytical database; consumes warehouse.task-interleaving.analytics and exits non-zero if its consumer stops (ADR 0008).ADMIN_ADDR, default :8091GET /healthz, GET /readyz
cmd/ti-reportsRead-only reports over the analytical database: /reports/hint-adoption, /reports/freshness.HTTP_ADDR, default :8092GET /healthz

web/ is not a Go binary: the task_interleaving_mfe Module Federation remote, served by its own nginx image. How cmd/api boots, what it starts and in which order it stops is in the Runbook; every variable is in Configuration.

Container and component diagram​

Source: cmd/api/main.go, cmd/api/adapters.go, cmd/api/consumers.go, cmd/api/relay.go (wiring and workers), cmd/api/topics.go, internal/application/ports/ports.go (the OUT ports), internal/domain/*/*.go import lists (stationtrip imports policy, recommend, travel; recommend imports policy, travel), internal/adapters/outbound/events/sink.go and internal/architecture/architecture_test.go. The in-memory adapters are not in the diagram because the binary does not wire them.

Data stores​

One Postgres database, created by the single embedded migration (migrations/0001_interleaving_schema.up.sql, ADR 0005):

TableHolds
interleaving_policiesOne row per site, version guards every update.
station_trips, hints, candidatesThe StationTrip aggregate, the hint history (one Active hint per station, enforced by a partial unique index) and each hint's ranked candidates.
task_poolLocal copy of the open-task pool, state AVAILABLE, CLAIMED or COMPLETED.
zones, locationsLocal copy of the facility layout, including geometry and the irreversible decommissioned flag.
processed_events(consumer, event_id) claims that make the consumers idempotent.
outbox_eventsThe transactional outbox; one row per message and destination topic.
idempotency_keysStored answers of POST /recommendations.

Postgres is the only store: the service refuses to boot without DATABASE_URL and nothing is served from process memory. Kafka is the fleet's single broker; this service produces to warehouse.task-interleaving.events and warehouse.task-interleaving.analytics and consumes warehouse.fulfillment.events and warehouse.facility.events. It never creates a topic through an admin API: the cluster broker auto-creates each on first write (the relay's writer sets AllowAutoTopicCreation), infrastructure declares none, and /readyz does not wait for any topic (ADR 0006 Amendment 1).

Rules enforced by internal/architecture​

The tests run on every PR (arch-test job, make arch-test):

TestRule
TestHexagonalArchitecture (6 subtests)**.internal.domain.** depends only on domain; **.internal.application.** only on domain and application; inbound adapters do not depend on outbound adapters and vice versa; nothing under internal/ imports cmd; internal/application/ports holds only interfaces.
TestMCPAdapterDependencyRuleAn MCP adapter, if added, depends only on application and domain, and nothing depends on it.
TestA2AAdapterDependencyRule, TestNoOutboundA2AClientThe A2A adapter depends only on application and domain, nothing depends on it, and no file imports the A2A client: this context is delegated to and never delegates.
TestAgentSurfacesAreReadOnly, TestEveryAgentSurfaceMustBeBuilt, TestAgentReadOnlySensorBites, TestAgentReadOnlySensorRefusesWriteMethodsAndRawDrivers (+ this module's bite fixtures in agent_readonly_hardening_test.go)The fleet's hardened read-only agent sensor (harness templates/architecture/agent_readonly_*, config in agent_readonly_config_test.go) over the MCP and A2A adapters and cmd/mcp, cmd/a2a: usecases, ports and postgres are resolved by import path (no alias, no dot import) and referenced only for their read identifiers; no write method (Save, Do, Claim, SaveZone, ...) or raw SQL (Exec, Query, Begin, ...) is selected on any value; no pgx or database/sql import; no Kafka, outbox, event sink, expiry worker, REST or sibling agent adapter import.
TestNoAuthMiddlewareReintroducedNo "Bearer ", golang-jwt/jwt, dgrijalva/jwt-go or lestrrat-go/jwx in non-comment source under internal/adapters/inbound: REST is unauthenticated fleet-wide.
TestKafkaConsumerGroupNeverHardcodedInlineNo GroupID: "literal"; the group id comes from FULFILLMENT_CONSUMER_GROUP / LAYOUT_CONSUMER_GROUP.
TestRuntimeBinaryHasNoInMemoryAdapters, TestRuntimeBinarySensorBitesNo non-test file under cmd/** imports internal/adapters/outbound/memory: the binary runs on Postgres and Kafka only (ADR 0006). The second test proves the detector flags plain, aliased, blank, dot and nested imports.
TestNoEventEnvelopeToggleOrFlatEnvelope, TestCloudEventsOnlyCloudEvents 1.0 is the only envelope: no EVENT_ENVELOPE_MODE, no flat event_id + event_type struct, and a module that uses kafka-go must import the CloudEvents SDK.
TestKafkaWritersSetRequiredAcksEvery kafka-go Writer{...} literal sets RequiredAcks (the library default is fire-and-forget).
TestKafkaWriterTopicNotSetTwiceIf a package sets Message.Topic, no Writer in it sets Topic (kafka-go refuses such writes).
TestReplayConsumersSetCommitIntervalA reader with a process-unique group id must set CommitInterval.
TestDeadLetterCallsGuardCancellationEvery function under internal/adapters/inbound/kafka that sends to a dead-letter topic must check ctx.Err() or context.Canceled (or carry a //dlq:deterministic <reason> annotation), so a shutdown never dead-letters a message that was only mid-flight.
TestOutboxRelaysPassAttemptCapEvery NewRelay / NewOutboxRelay call passes a WithMaxAttempts(...) option; there is no skip path.
TestEventCatalogueMatchesContractEvery full CloudEvents type that apis/asyncapi.yaml declares for this service appears in the CloudEvents ADR (docs/adr/0004-cloudevents-envelope-and-type-catalogue.md).
TestKafkaIntegrationTestsUseTestcontainers, TestPostgresIntegrationTestsUseTestcontainers*_integration_test.go files boot their own broker or database; no KAFKA_BROKERS / DATABASE_URL gate, no localhost:9092.

TestAgentSurfacesAreReadOnly pins the MCP and A2A adapters to the read use cases and TestMCPOptionalToolInputsCarryOmitempty now scans the real MCP tool inputs; no sensor skips. Details and commands are on Testing.