Warehouse Management (WMS) 8 applications
Architecture
Clean code
API design
A mature, heavily documented master-data context (43 ADRs, 150 BDD scenarios) with chain-of-custody invariants and outbox publishing; a 979-line HTTP router, no pagination and a lagging Go toolchain are the main debts.
Location codes and roles follow commercial WMS practice; it must be correct, not differentiating.
- Production code
- 17,512 lines Go in 115 files, 31 packages
- Tests
- 28,589 lines, 495 test functions, 24 integration files, 150 BDD scenarios, 31 fitness tests
- Function size
- avg 11.8 lines (p95 34), 14 over 60 lines
- Complexity
- avg cyclomatic 2.7; highest Graph.Distance (15), RegisterLocationSlot.register (15)
- Layering
- 0 infrastructure imports in domain/application; 8 domain packages
- Quality gates
- coverage 90%, mutation efficacy 89%, 21 CI jobs
- Persistence
- PostgreSQL, 13 migrations, 14 tables
- Deployables
- a2a, facility, facility-projector, facility-reports, mcp
- Largest files
- internal/adapters/inbound/http/server.go (979), cmd/facility/main.go (617)
- Console remote (web/)
- 4,086 lines TS/TSX, 12 test files
- Decisions
- 43 ADRs, 133 docs pages
- Security scanning
- 1 open code-scanning, 2 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (facility API, projector, reports, MCP, A2A) + MF web remote; Postgres + outbox to Kafka
Strengths
- Eight domain packages (site, zone, aisle, slot, structure, placement, travel, shared); travel is an infrastructure-free Dijkstra graph for shortest-path distance (internal/domain/travel/graph.go, ADR-0017).
- RegisterLocationSlot enforces the Site -> Zone -> Aisle chain of custody and every PlacementRule before saving slot + LocationSlotRegistered atomically (usecases/register_location_slot.go:30-157).
- Pure producer: publishes 15 event types and consumes none, so it is a stable upstream with no inbound coupling; analytics is a separate projector + reports binary pair.
- Every resource-creating POST is wrapped by RequireIdempotencyKey (ADR-0019), with CORS deliberately allowing the header (internal/adapters/inbound/http/server.go:966-974).
Concerns
- Slot registration reads duplicates, the parent chain and all placement rules before opening the unit of work (register_location_slot.go:102-142); a concurrent rule or zone change is not re-checked inside the transaction.
- Rules.List loads every placement rule in the catalogue on each single-slot registration (register_location_slot.go:128) rather than the rules for the target zone; cost grows with the rule set.
- All 38 REST operations are unauthenticated by fleet decision (ADR-0015 noted in server.go:971), including decommission and bulk layout import.
Clean code
Strengths
- Strong test portfolio: 28.6k test LOC vs 17.5k prod, 150 BDD scenarios in 15 features, 24 integration files, contract and evals-tests CI jobs, 31 fitness tests, CodeQL and Scorecard workflows.
- Intent-rich naming and comments, e.g. metric outcome constants defined in the deciding layer with rationale (register_location_slot.go:14-28).
- No function over cyclomatic 15; average 11.8 lines per function.
Concerns
- internal/adapters/inbound/http/server.go is 979 lines with ~40 handlers and a 113-line NewRouter; cmd/facility/main.go is 617 lines; 14 functions exceed 60 lines.
- Long positional parameter lists: ExecuteWithHandlingUnit takes 7 arguments (register_location_slot.go:70) instead of a command struct, inviting argument-order mistakes.
- go.mod pins go 1.26.10 while sibling repos are on 1.27.3, and the module path is github.com/claudioed/facility-layout rather than the IQVO org.
APIs and contracts
- Large, well-specified surface: 38 operations and 61 schemas in apis/openapi.yaml plus a separate apis/openapi-reports.yaml; docs-api-drift and contract CI jobs guard spec vs handlers.
- Idempotency-Key is documented throughout (54 mentions in apis/openapi.yaml) with problem+json errors; PUT is used appropriately for geometry, role and capability replacement.
- No pagination on any list (sites, zones, location-types, placement-rules, locations by role) and no ETag/If-Match, although capabilityRevision exists and could back optimistic concurrency.
- Events follow com.warehouse.wms.facility-layout.<aggregate>.<Type> on AsyncAPI 2.6.0; SiteCapabilityChanged and SiteRoleChanged are not mirrored on the analytics topic (13 of 15 types).
REST: 42 operations (27 read, 15 write, 8 of 15 writes require Idempotency-Key)
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| GET | /reports/catalog-growth | Layout Catalog Growth report, keyed by scope and UTC day |
| GET | /reports/catalog-growth/freshness | How far the read model trails the event stream |
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| POST | /sites | Register a physical facility |
| GET | /sites | List every registered site |
| GET | /sites/{siteCode} | Get one site |
| PUT | /sites/{siteCode}/role | Set a site's role in the fulfilment network |
| GET | /site-roles/transfer-defaults | The default transfer capability of every site role |
| GET | /sites/{siteCode}/transfer-capability | Get a site's transfer capability |
| PUT | /sites/{siteCode}/transfer-capability | Set a site's transfer capability |
| POST | /sites/{siteCode}/zones | Register a behavioral zone inside a site's area |
| GET | /sites/{siteCode}/zones | List a site's zones |
| GET | /sites/{siteCode}/layout | Get a site's full drawable layout |
| GET | /sites/{siteCode}/locations | List a site's locations by role |
| POST | /sites/{siteCode}/structures | Register a fixed structure |
| GET | /sites/{siteCode}/structures | List a site's fixed structures |
| GET | /zones/{zoneId} | Get one zone |
| GET | /zones/{zoneId}/grid | Get a zone as a 2D renderable grid |
| POST | /zones/{zoneId}/aisles | Register a physical corridor inside a zone |
| GET | /zones/{zoneId}/aisles | List a zone's aisles in walk order |
| GET | /zones/{zoneId}/aisles/{aisleCode} | Get one aisle |
| PUT | /zones/{zoneId}/aisles/{aisleCode}/geometry | Set an aisle's travel centreline |
| POST | /zones/{zoneId}/cross-aisles | Register a connection between two aisles |
| GET | /zones/{zoneId}/cross-aisles | List a zone's cross-aisles |
| GET | /zones/{zoneId}/travel-graph | Get one zone's travel graph |
| POST | /location-types | Register a reusable slot classification |
| GET | /location-types | List every registered location type |
| GET | /location-types/{name} | Get one location type |
| POST | /placement-rules | Declare which location types are legal in which zones |
| GET | /placement-rules | List every defined placement rule |
| GET | /placement-rules/{ruleId} | Get one placement rule |
| POST | /locations | Register one coded location slot |
| POST | /locations/import | Bulk-import a whole building's layout |
| GET | /locations/{locationCode} | Get one location slot |
| PUT | /locations/{locationCode}/geometry | Set a location slot's physical geometry |
| PUT | /locations/{locationCode}/handling-unit | Declare a location slot's handling unit |
| GET | /locations/{locationCode}/classification | Get a location slot's resolved hazmat/temperature-class attributes |
| POST | /locations/{locationCode}/decommission | Permanently retire a location slot |
| GET | /distance | Compute the shortest travel distance between two locations |
Events published: 15 types on warehouse.facility.analytics, warehouse.facility.events
- aisle.AisleGeometryUpdated
- aisle.AisleRegistered
- crossaisle.CrossAisleRegistered
- locationslot.FacilityLayoutImported
- locationslot.LocationGeometryUpdated
- locationslot.LocationSlotDecommissioned
- locationslot.LocationSlotHandlingUnitDeclared
- locationslot.LocationSlotRegistered
- locationtype.LocationTypeRegistered
- placementrule.PlacementRuleDefined
- site.SiteCapabilityChanged
- site.SiteRegistered
- site.SiteRoleChanged
- structure.FixedStructureRegistered
- zone.ZoneRegistered
MCP tools: 8 (7 read-only)
explore_layout | write | Standard operating procedure for navigating the warehouse map (site -> zone -> aisle -> slot) to answer a placement or travel question using the read tools. |
get_facility_catalog_growth_report | read | Return the facility-layout 'Layout Catalog Growth & Change' report (slots registered/decommissioned, zones/aisles/location-types registered, placement rules defined, and bulk-import row tallies) for a time window, bucket |
list_sites | read | List every registered site on the warehouse map as {code, name, siteRole, transferOriginEnabled, transferDestinationEnabled, capabilityRevision}: siteRole is the site's role in the fulfilment network (e.g |
get_site_layout | read | Return one site's full drawable structure as a compact nested map: zones -> aisles -> slot codes, with each zone's temperature class and hazmat flag and each aisle's walk-order sequence hint |
get_zone_grid | read | Return one zone's slots as a 2D grid: rows are levels, columns are (aisle, bay) pairs in walk order, each cell holds the location codes at that coordinate |
list_functional_locations | read | List a site's non-storage functional locations by role: dock doors, yard spots, work centers (pack/sort/QC/VAS stations), drop points, staging, consolidation, or shipping locations (ADR-0016) |
get_zone_travel_graph | read | Return one zone's travel graph as nodes (aisle/bay waypoints) and directed edges (weighted in metres, flagged estimated when derived from a zone's bay pitch rather than real aisle centreline geometry) (ADR-0017) |
estimate_travel_distance | read | Compute the shortest travel distance, in metres, between two coded locations (ADR-0017) |
A2A skills: 2
- Layout of a site
- Travel distance between two locations
Recommended next steps
- Split server.go into per-resource handler files and the router into resource-scoped mount functions.
- Add cursor pagination to list endpoints and expose capabilityRevision/aggregate versions via ETag/If-Match.
- Upgrade to the fleet Go toolchain (1.27.3) and move slot pre-checks inside the unit of work.
Measured at origin/develop f6946bd (2026-10-30). Review sampled 5 files.
Architecture
Clean code
API design
Largest, among the best-tested contexts: GS1-aware receipt aggregate, ETag/If-Match on every action, cursor paging, no sync dependencies; main notes are one-site-per-deployment and a 722-line domain file.
Every warehouse needs it, but ASN, window and discrepancy rules are replaceable policy, not where the platform differentiates.
- Production code
- 17,013 lines Go in 112 files, 33 packages
- Tests
- 25,731 lines, 649 test functions, 23 integration files, 109 BDD scenarios, 30 fitness tests
- Function size
- avg 11.4 lines (p95 31), 4 over 60 lines
- Complexity
- avg cyclomatic 3.1; highest run (14), Event.validateDetail (14)
- Layering
- 0 infrastructure imports in domain/application; 5 domain packages
- Quality gates
- coverage 90%, mutation efficacy 99%, 19 CI jobs
- Persistence
- PostgreSQL, 5 migrations, 22 tables
- Deployables
- a2a, api, inbound-projector, inbound-reports, mcp
- Largest files
- internal/domain/receipt/carton.go (722), cmd/api/main.go (664)
- Console remote (web/)
- 3,670 lines TS/TSX, 14 test files
- Decisions
- 16 ADRs, 76 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (API, MCP, A2A, inbound-projector, inbound-reports); Postgres + outbox; product/facility copies from Kafka
Strengths
- No outbound HTTP clients: packaging and location facts come from product-master and facility-layout topics, so receiving never blocks on a sibling at the dock.
- ReceiveScan runs load, version check, aggregate dispatch and save in one UnitOfWork (internal/application/usecases/scan.go:128-146); refused scans commit a CartonDiscrepancyRaised finding instead of failing.
- Repositories are version-guarded (postgres/receipt_repository.go:182-189) and constraints back invariants, e.g. a partial unique index on active SSCCs (migrations/0003_cartons_and_packaging.up.sql:30).
- Analytics run in separate projector/reports binaries with their own migrations (analytics/migrations), keeping reporting off the operational schema.
Concerns
- One deployment serves one site: the schema holds no site key (internal/adapters/outbound/postgres/migrations/0003_cartons_and_packaging.up.sql:12-13), so multi-site rollout means one database and release per building.
- Cross-aggregate facts are resolved by the use case and passed to the aggregate as booleans/maps (CartonScan.ReceivedElsewhere, CasePacks in internal/domain/receipt/carton.go:182-200), so correctness depends on the caller resolving them right.
- REST/MCP are unauthenticated by fleet decision (apis/openapi.yaml:59), while POST /receipts/{id}/close finalises received stock.
Clean code
Strengths
- 25.7k test LOC for 17k prod LOC, 649 test funcs, 109 BDD scenarios (the most sampled), 23 integration-tagged files, a fuzz test, 30 fitness tests and 99% mutation gates.
- Domain errors and discrepancy kinds are named and traced to ADR decisions (ADR 0012/0014 references in internal/domain/receipt/carton.go:40-64); GS1 parsing lives in its own domain package.
- Avg 11.4 lines/function, avg cyclomatic 3.1, no production function over the cap of 15.
Concerns
- internal/domain/receipt/carton.go is 722 lines, the largest domain file sampled; ledger, scan resolution and audit-count logic could be split into separate files.
- cmd/api/main.go is 664 lines and cmd/inbound-projector/main.go run() is 80 lines at cyclomatic 14, near the cap.
- Repositories take loadedVersion as a separate argument (postgres/receipt_repository.go:177 Save) rather than reading it from the aggregate, which every caller must track.
APIs and contracts
- Good: every resource returns a strong ETag and action POSTs accept If-Match with 412 version-mismatch (apis/openapi.yaml:22-23, 1137-1352); creates take Idempotency-Key.
- Good: all lists use opaque cursor paging (limit 1-500 + nextCursor, apis/openapi.yaml:57-58); errors are RFC 9457 problem+json with typed slugs.
- Weaker: state changes are verb sub-paths (/asns/{n}/cancel, /appointments/{id}/check-in, /receipts/{id}/close) and there is no URL/media-type versioning despite 1.0.0.
- Events: 11 CloudEvents types under com.warehouse.wms.inbound-receiving.<entity>.<Event>, mirrored to an analytics topic; MCP exposes 7 read-only get/list tools.
REST: 22 operations (13 read, 9 write, 9 of 9 writes require Idempotency-Key)
| POST | /asns | Register an ASN |
| GET | /asns | List ASNs |
| GET | /asns/{asnNumber} | Get an ASN |
| GET | /asns/{asnNumber}/cartons | List the announced cartons of an ASN |
| POST | /asns/{asnNumber}/cancel | Cancel an ASN |
| POST | /appointments | Book a dock appointment |
| GET | /appointments | List dock appointments |
| GET | /appointments/{appointmentId} | Get a dock appointment |
| POST | /appointments/{appointmentId}/check-in | Check a carrier in |
| POST | /appointments/{appointmentId}/cancel | Cancel a dock appointment |
| POST | /receipts | Open a receipt |
| GET | /receipts | List receipts |
| GET | /receipts/{receiptId} | Get a receipt |
| POST | /receipts/{receiptId}/lines | Receive a quantity against a line |
| GET | /receipts/{receiptId}/cartons/{lpn}/label | Get the label data of an accepted carton |
| POST | /receipts/{receiptId}/scans | Receive by scan |
| POST | /receipts/{receiptId}/close | Close a receipt |
| GET | /docks | List the inbound dock doors |
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| GET | /reports/receiving-performance | Receiving performance and accuracy per day, and the state right now |
| GET | /reports/freshness | How far the analytics projection is behind |
Events published: 11 types on warehouse.inbound-receiving.analytics, warehouse.inbound-receiving.events
- asn.ASNCancelled
- asn.ASNRegistered
- dockappointment.DockAppointmentBooked
- dockappointment.DockAppointmentCancelled
- dockappointment.DockAppointmentCheckedIn
- dockappointment.DockAppointmentCompleted
- receipt.CartonDiscrepancyRaised
- receipt.ReceiptCartonReceived
- receipt.ReceiptClosed
- receipt.ReceiptLineReceived
- receipt.ReceiptOpened
Events consumed: 5 types from 2 topics
warehouse.facility.events, warehouse.product-master.events
- locationslot.LocationSlotDecommissioned facility-layout
- locationslot.LocationSlotRegistered facility-layout
- product.ProductPackLevelDeclared product-master
- product.ProductPackLevelRetired product-master
- product.ProductRegistered product-master
MCP tools: 7 (7 read-only)
get_asn | read | Read one advance ship notice (ASN) by number: supplier_ref, expected_arrival (omitted when none), state (Registered, Receiving, Closed or Cancelled), its lines (line_no, sku, expected_qty) and version |
list_asns | read | List ASNs in ascending number order, a page at a time (default 100, max 500), optionally only those in one state |
get_appointment | read | Read one carrier dock appointment by id: door_code, carrier, window_start and window_end (UTC), the asn_numbers it covers, state (Booked, CheckedIn, Completed or Cancelled) and version |
list_appointments | read | List dock appointments in ascending window-start order, a page at a time (default 100, max 500), optionally only those at one door, in one state, and/or overlapping a from/to time range (from: window ends after it; to: w |
get_receipt | read | Read one receipt by id: asn_number, appointment_id and door_code (omitted for a walk-in), state (Open or Closed), per-line expected_qty, received_good and received_damaged, opened_at, closed_at (omitted while open), the |
list_receipts | read | List receipts in ascending id order, a page at a time (default 100, max 500), optionally only those of one ASN (asn_number) and/or in one state (Open or Closed) |
list_docks | read | List the inbound dock doors this service knows (door_code and dock_flow Inbound or Both) in ascending code order, with the mode the local copy runs in: permissive (any door code can be booked, the list may be empty) or k |
A2A skills: 2
- Dock appointment schedule
- Receiving status of an ASN
Recommended next steps
- Decide on a multi-site model (site key in schema or documented per-site deployment automation) before scaling beyond one building.
- Split internal/domain/receipt/carton.go and cmd/api/main.go by concern.
- Adopt a REST versioning scheme and consider AIP custom methods (:close, :cancel) for consistency with retail-network services.
Measured at origin/develop aecb907 (2026-10-30). Review sampled 6 files.
Architecture
Clean code
API design
The fleet's most thoroughly tested context (1,099 test funcs, 112 BDD scenarios, 99% mutation gate) with exactly-once transfer allocation; debts are large adapter files, legacy-compat fields and mixed REST style.
Every customer promise rests on its usable answer; chaotic stow and revocable reservations are core rules.
- Production code
- 24,577 lines Go in 177 files, 36 packages
- Tests
- 44,036 lines, 1099 test functions, 49 integration files, 112 BDD scenarios, 28 fitness tests
- Function size
- avg 13.0 lines (p95 40), 14 over 60 lines
- Complexity
- avg cyclomatic 3.1; highest AllocateTransferStock.Execute (15), StageTransferReceipt.Execute (14)
- Layering
- 0 infrastructure imports in domain/application; 10 domain packages
- Quality gates
- coverage 90%, mutation efficacy 99%, 21 CI jobs
- Persistence
- PostgreSQL, 18 migrations, 22 tables
- Deployables
- a2a, inventory, inventory-projector, inventory-reports, mcp
- Largest files
- internal/adapters/outbound/facilitycache/consumer.go (711), internal/adapters/inbound/http/server.go (625), internal/adapters/inbound/kafka/task_completed_consumer.go (503)
- Console remote (web/)
- 780 lines TS/TSX, 4 test files
- Decisions
- 48 ADRs, 113 docs pages
- Security scanning
- 1 open code-scanning, 3 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (API, MCP, A2A, projector, reports) + MFE web; Postgres + outbox to Kafka; analytics read model
Strengths
- StockUnit encodes the core rule 'every item has one known bin or is Unlocated' with scan-pair validation and validated site custody (internal/domain/stock/stock_unit.go); 10 domain packages incl. GS1 GTIN/SSCC checks.
- Transfer allocation is exactly-once: ledger unique on transfer_line_id; stock, reservation and reply event commit in one unit of work with replay/conflict paths (usecases/allocate_transfer_stock.go).
- Broad event-driven integration: consumes 6 upstream topics (product-master, facility, fulfillment, inbound, returns, network planning) with DLQs, publishes 15 integration + 9 analytics events.
- Separate projector and reports binaries keep the analytics read model off the transactional path; gobreaker on the facility-layout client.
Concerns
- Legacy-compat states leak into the aggregate: empty siteID and ownerRef are valid for pre-ADR rows, and NewStockUnit still creates site-less units (internal/domain/stock/stock_unit.go:37-44,58), widening the invariant surface.
- Every use case sits in one application package (facts: 2 app packages for 24.6k prod LOC), so internal/application/usecases has no internal boundaries between reservation, transfer, container and cycle-count flows.
- REST endpoints are unauthenticated by fleet decision; POST /reservations and DELETE /reservations/{id} directly move usable stock for any caller (apis/openapi.yaml).
Clean code
Strengths
- Test depth is exceptional: 44k test LOC vs 24.6k prod, 1,099 test funcs, 49 integration-tagged files, 112 BDD scenarios, a fuzz test and 99% mutation efficacy/coverage gates (facts).
- Concurrency and idempotency reasoning is written down where it matters, e.g. the DB-level idempotency contract on AllocateTransferStock and closed rejection-reason set.
- Average function 13 lines, average cyclo 3.1, 0 functions over cyclo 15, no layer violations (facts).
Concerns
- Three adapter files exceed 500 lines: internal/adapters/outbound/facilitycache/consumer.go (711), internal/adapters/inbound/http/server.go (625, NewRouter 119 lines), internal/adapters/inbound/kafka/task_completed_consumer.go (503).
- AllocateTransferStock.Execute sits at the cyclop cap (cyclo 15, 68 lines) and reads the ledger up to three times (internal/application/usecases/allocate_transfer_stock.go:98-165).
- 14 functions exceed 60 lines, incl. encodeEvent at 87 lines in internal/adapters/outbound/kafka/publisher.go; a per-event encoder table would shrink it.
APIs and contracts
- Good: Idempotency-Key required on creating POSTs (ADR 0018) with documented idempotency-key-required/-reused problem types, typed problem URIs, and PUT /bins/{binId} as an idempotent converge.
- Gap: mixed resource styles in one spec: verb paths (/stock/stow, /stock/receive), sub-resource actions (/reservations/{id}/confirm-pick) and AIP custom methods (/containers/{lpn}:stow, :break).
- Gap: list reads (GET /reservations?demandRef, GET /bins/{binId}/containers) have no limit/cursor; no ETag/If-Match despite ADR 0019 versioning; 2 deprecated ops still served.
- Events: AsyncAPI 2.6 (storefront contexts use 3.0) with CloudEvents types com.warehouse.wms.inventory-storage.<aggregate>.<Event>; MCP exposes 5 read tools and one write (revoke_reservation).
REST: 22 operations (10 read, 12 write, 7 of 12 writes require Idempotency-Key)
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| POST | /stock/receive | Acknowledge inbound stock for a SKU |
| POST | /stock/stow | Stow received stock into a bin |
| GET | /reservations | Look up every reservation for a demand reference |
| POST | /reservations | Create a revocable reservation against usable inventory |
| DELETE | /reservations/{id} | Revoke a reservation |
| POST | /reservations/{id}/confirm-pick | Confirm a reservation's physical pick |
| GET | /inventory/{sku}/usable | Get usable inventory for a SKU |
| PUT | /bins/{binId} | Register a bin, or converge an existing bin to a capacity |
| GET | /bins/{binId} | Get a bin's capacity and occupancy |
| POST | /bins/{binId}/cycle-count | Record a physical cycle count for a bin |
| POST | /transfers/{transferLineId}/receipt | Stage a destination transfer receipt (count an arrival) |
| POST | /transfers/{transferLineId}/stow | Stow a staged transfer receipt into destination bins |
| POST | /relocations | Move stock of one SKU between two bins of the same site |
| GET | /relocations/{id} | Read one relocation |
| GET | /containers/{lpn} | Read one container |
| POST | /containers/{lpn}:stow | Stow a sealed case into a case bin |
| POST | /containers/{lpn}:break | Break a sealed case into loose eaches |
| GET | /bins/{binId}/containers | List the containers stowed in a bin |
| GET | /reports/flow-accuracy | Inventory Flow & Accuracy report (hourly) |
| GET | /reports/flow-accuracy/freshness | Freshness lag of the flow-accuracy read model |
Events published: 20 types on warehouse.inventory.analytics, warehouse.inventory.events
- bin.CycleCountCompleted
- bin.DiscrepancyDetected
- container.CaseBroken
- container.ContainerEmptied
- container.ContainerRegistered
- container.ContainerStowed
- reservation.ReservationExpired
- reservation.ReservationRevoked
- reservation.StockPicked
- reservation.StockReserved
- reservation.TransferStockAllocated
- reservation.TransferStockAllocationRejected
- stock.BinStockLevelChanged
- stock.ItemStowed
- stock.ItemUnlocated
- stock.LocationRecorded
- stock.StockReceived
- stock.StockRelocated
- stock.TransferReceiptStaged
- stock.TransferStockStowed
Events consumed: 12 types from 6 topics
warehouse.facility.events, warehouse.fulfillment.events, warehouse.inbound-receiving.events, warehouse.network-inventory-planning.events, warehouse.product-master.events, warehouse.returns-processing.events
- task.TaskCompleted fulfillment-execution
- transfer.TransferAllocationRequested network-inventory-planning
- locationslot.LocationSlotDecommissioned facility-layout
- locationslot.LocationSlotHandlingUnitDeclared facility-layout
- locationslot.LocationSlotRegistered facility-layout
- zone.ZoneRegistered facility-layout
- receipt.ReceiptCartonReceived inbound-receiving
- receipt.ReceiptLineReceived inbound-receiving
- product.ProductClassified product-master
- product.ProductPackLevelDeclared product-master
- product.ProductPackLevelRetired product-master
- disposition.ReturnLineStaged returns-processing
MCP tools: 7 (5 read-only)
get_container | read | Return one sealed-case container by its LPN: SKU, case GTIN, units per pack, quantity in eaches, owner, site, bin, state (SEALED, OPEN or EMPTY), lot, expiry and the receipt line it came from |
triage_low_stock | write | Standard operating procedure for triaging low or blocked usable inventory using the inventory-storage MCP tools. |
get_relocation | read | Return one applied intra-site stock relocation by id: SKU, quantity, source and destination bin of one site, reason (SLOTTING, CONSOLIDATION, MANUAL), source reference (e.g |
get_inventory_flow_accuracy_report | read | Return the Inventory Flow & Accuracy report (received/stowed/picked quantities, reservations created/expired/revoked, cycle-count completions, discrepancies, and unlocated items) for a time window, optionally filtered by |
check_availability | read | Return the usable quantity for a SKU: on-hand across all its bins minus active reservations and held/unlocated stock |
get_bin_occupancy | read | Return what a single bin holds: its total on-hand, reserved, and usable quantities, plus a per-StockUnit breakdown (SKU, quantities, state). |
revoke_reservation | write | Revoke a reservation, returning its bound quantity to usable inventory so a failed physical delivery never strands an order |
A2A skills: 2
- Revoke a reservation
- Usable availability of a SKU
Recommended next steps
- Split internal/application/usecases into sub-packages per flow (reservation, transfer, container, count) and break up the three >500-line adapter files.
- Converge REST actions on one style (AIP :verb) and set a removal date for the deprecated /stock/receive and confirm-pick routes.
- Backfill site/owner custody for legacy stock units and then make them mandatory in StockUnit constructors.
Measured at origin/develop 836242b (2026-10-30). Review sampled 4 files.
Architecture
Clean code
API design
Clean event-driven min/max replenishment context: pure aggregate, single shared Evaluator, version-guarded projections and a strong REST contract; gaps are runtime metrics and per-face query fan-out.
Needed for picking without stock-outs, but min/max is a well-understood rule behind a replaceable policy object.
- Production code
- 13,924 lines Go in 114 files, 34 packages
- Tests
- 19,160 lines, 494 test functions, 18 integration files, 57 BDD scenarios, 34 fitness tests
- Function size
- avg 11.3 lines (p95 28), 1 over 60 lines
- Complexity
- avg cyclomatic 3.0; highest PackLevelView (14), IdempotencyStore (14)
- Layering
- 0 infrastructure imports in domain/application; 5 domain packages
- Quality gates
- coverage 90%, mutation efficacy 90%, 16 CI jobs
- Persistence
- PostgreSQL, 4 migrations, 14 tables
- Deployables
- a2a, api, mcp, pfr-projector, pfr-reports
- Largest files
- none over 500 lines
- Console remote (web/)
- 2,044 lines TS/TSX, 10 test files
- Decisions
- 10 ADRs, 57 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (API, MCP, A2A, pfr-projector, pfr-reports); Postgres + outbox; local copies of 4 upstream topics
Strengths
- ReplenishmentRequest (internal/domain/replenishment/request.go) is pure, documents 5 invariants, enforces 2-4 in Plan/Complete, re-validates on Restore; rule 1 is backed by a partial unique index.
- All detection paths (sweep, consumers, manual request, view) go through one Evaluator (usecases/evaluator.go), so REST, events and sweeps cannot disagree on when to raise a request.
- Projections are idempotent and ordered: bin levels upsert only when the message version is newer (postgres/read_model.go:137) and every consumer runs behind a processed_events inbox.
- Purely event-driven inputs (inventory, product-master, slotting, facility layout) with outbox output; no synchronous sibling calls on any path.
Concerns
- No runtime metrics: no otel/metric or Prometheus instruments in any *.go file, so requests raised/completed, detection latency and consumer lag are not observable as metrics.
- Evaluator.Faces calls Read.Place once per forward assignment (internal/application/usecases/evaluator.go:137-145), an N+1 pattern that makes POST /sites/{siteId}/evaluate cost grow linearly in queries.
- A bin the layout copy has not seen counts as a pick face (usecases/evaluator.go:154-156); until facility events arrive, requests can be raised for bins that are not forward locations.
Clean code
Strengths
- 13.9k prod LOC, avg 11.3 lines/function, p95 28, avg cyclomatic 3.0; no production function above the cap (top three are test/analytics helpers).
- 19k test LOC, 494 test funcs, 57 BDD scenarios, 18 integration-tagged files, 34 fitness tests and a repository contract suite shared by memory and Postgres adapters.
- Validation is decomposed into small named checks (validatePlanIdentity/Sizing/Source in request.go) mapped to distinct domain errors, keeping each under complexity caps.
Concerns
- Plan and Restore validation repeat the same identity checks (validatePlanIdentity vs validateSnapshotIdentity in internal/domain/replenishment/request.go), making request.go 441 lines.
- Evaluator.plan dereferences a.Policy (usecases/evaluator.go:228) relying on the detector never returning Raise without a policy; the invariant is implicit rather than enforced by the type.
APIs and contracts
- Good: policies use ETag + If-Match on PUT and DELETE with explicit problem examples for missing/stale If-Match (apis/openapi.yaml lines 110-191, 888-912).
- Good: opaque cursor pagination (nextCursor) on all list endpoints, Idempotency-Key with body fingerprinting on POSTs, and problem+json types as stable URIs.
- Weaker: POST /replenishments/{id}/cancel and POST /sites/{siteId}/evaluate are RPC-style verbs, and there is no URL/media-type versioning despite info.version 1.0.0.
- Events: CloudEvents types com.warehouse.wms.pick-face-replenishment.<entity>.<Event>; integration and analytics topics are split; MCP exposes five read-only list/get tools.
REST: 14 operations (9 read, 5 write, 3 of 5 writes require Idempotency-Key)
| GET | /policies | List replenishment policies |
| PUT | /policies/{siteId}/{sku} | Declare or change a replenishment policy |
| GET | /policies/{siteId}/{sku} | Get a replenishment policy |
| DELETE | /policies/{siteId}/{sku} | Remove a replenishment policy |
| GET | /pick-faces | List pick faces and their replenishment status |
| POST | /replenishments | Raise a replenishment request by hand |
| GET | /replenishments | List replenishment requests |
| GET | /replenishments/{requestId} | Get a replenishment request |
| POST | /replenishments/{requestId}/cancel | Cancel an open replenishment request |
| POST | /sites/{siteId}/evaluate | Re-run detection for a site |
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| GET | /reports/replenishment-funnel | The replenishment funnel per day |
| GET | /reports/freshness | How far the analytics projection is behind |
Events published: 4 types on warehouse.pick-face-replenishment.analytics, warehouse.pick-face-replenishment.events
- policy.ReplenishmentPolicyDeclared
- replenishment.ReplenishmentCancelled
- replenishment.ReplenishmentCompleted
- replenishment.ReplenishmentRequested
Events consumed: 8 types from 4 topics
warehouse.facility.events, warehouse.inventory.events, warehouse.product-master.events, warehouse.slotting-optimization.events
- locationslot.LocationSlotDecommissioned facility-layout
- locationslot.LocationSlotRegistered facility-layout
- zone.ZoneRegistered facility-layout
- stock.BinStockLevelChanged inventory-storage
- stock.StockRelocated inventory-storage
- product.ProductPackLevelDeclared product-master
- product.ProductPackLevelRetired product-master
- slotplan.SlotPlanApproved slotting-optimization
MCP tools: 5 (5 read-only)
list_policies | read | List the declared min/max replenishment policies ordered by site then SKU, a page at a time (default 100, max 500), optionally only those of one site and/or one SKU |
get_policy | read | Read the replenishment policy of one site and SKU: min_qty, max_qty, multiple, version and declared_at |
list_pick_faces | read | List the forward pick faces of a site ordered by forward bin, a page at a time (default 100, max 500), each with its SKU, on_hand, reserved and available quantity, the policy min_qty and max_qty (omitted without a policy |
list_replenishments | read | List replenishment requests newest first, a page at a time (default 100, max 500), optionally only those of one site, one SKU and/or one state (Requested, Completed or Cancelled) |
get_replenishment | read | Read one replenishment request by id: the forward bin, the reserve source bin, the quantity, the moved quantity once completed, priority, state (Requested, Completed or Cancelled), the policy min and max it was raised un |
A2A skills: 2
- Pick-face status of a site
- Replenishment request lookup
Recommended next steps
- Add OTel counters/histograms for requests raised/completed/cancelled, detection duration and consumer lag.
- Batch the location lookups in Evaluator.Faces into one query per site.
- Gate auto-raising on a known forward location (or flag 'layout pending') instead of treating unknown bins as pick faces.
Measured at origin/develop c1dfa28 (2026-10-30). Review sampled 7 files.
Architecture
Clean code
API design
Clean master-data context with GS1-correct packaging invariants, PUT-idempotent REST, outbox events and well-annotated MCP tools; main gaps are a 537-line packaging file and unauthenticated MCP write tools.
Needed by every warehouse flow but not where the business differentiates; the handling rules are custom.
- Production code
- 10,508 lines Go in 82 files, 27 packages
- Tests
- 18,459 lines, 386 test functions, 19 integration files, 66 BDD scenarios, 29 fitness tests
- Function size
- avg 11.0 lines (p95 29), 3 over 60 lines
- Complexity
- avg cyclomatic 3.0; highest run (14), Product.checkSpecShape (14)
- Layering
- 0 infrastructure imports in domain/application; 2 domain packages
- Quality gates
- coverage 90%, mutation efficacy 95%, 19 CI jobs
- Persistence
- PostgreSQL, 3 migrations, 7 tables
- Deployables
- a2a, api, mcp, product-projector, product-reports
- Largest files
- internal/domain/product/packaging.go (538)
- Console remote (web/)
- 2,517 lines TS/TSX, 8 test files
- Decisions
- 12 ADRs, 67 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (API, projector, reports, MCP, A2A); Postgres + outbox to Kafka; producer-only system of record
Strengths
- Pure upstream system of record: consumes no sibling topics (its Kafka consumer only feeds its own analytics projector) and publishes 8 Product CloudEvents types for slotting, inventory and others to copy locally.
- Product aggregate owns packaging invariants (GS1 GTIN check digits, immutable content quantity, level ordering, weight >= contents) as named domain errors (internal/domain/product/packaging.go).
- Fleet-wide GTIN uniqueness is checked in the use case and backed by a unique index against races (internal/application/usecases/pack_levels.go requireUnassigned).
- Writes go through Writer.persist inside UoW.Do with outbox append; GTIN resolution is explicitly off the hot path, consumers resolve from their own projections (pack_levels.go ResolveGTIN, ADR 0011).
Concerns
- mustStoredGTIN panics on an invalid stored GTIN (internal/adapters/outbound/postgres/pack_level_repository.go:142-147) instead of returning a corruption error, so one bad row turns a read into a recovered 500 or a crash outside HTTP.
- The MCP server exposes WRITE tools declare_pack_level and retire_pack_level (internal/adapters/inbound/mcp/tools.go:431-432) while MCP is unauthenticated fleet-wide, so any agent on the network can change master data.
- The analytics stream carries 5 of 8 event types; the 3 pack-level events go only to warehouse.product-master.events (apis/asyncapi.yaml), so packaging changes are invisible to the analytics projection.
Clean code
Strengths
- 18.5k test LOC vs 10.5k prod LOC; 386 test funcs, 1 fuzz test, 19 integration-tagged files, 66 godog scenarios, 29 fitness tests; coverage 90% and mutation gates at 95%.
- Zero layer-import violations, no clock/uuid/struct tags in the domain, average function 11 lines and average cyclomatic 3.0.
- Use cases parse raw input into domain value objects before the transaction and keep the closure short (pack_levels.go DeclarePackLevel.Handle, RetirePackLevel.Handle).
- GS1 logic is isolated in its own domain package (internal/domain/shared/gs1: check.go, gtin.go, sscc.go, scan.go).
Concerns
- internal/domain/product/packaging.go is 537 lines (the only file over 500) and Product.checkSpecShape reaches cyclo 14, close to the cyclop 15 cap.
- DeclarePackLevel discards the ok result of ByGTIN (pack_levels.go:110 `res.Def, _ =`), so a missing definition after a successful declare would surface as a zero-valued Def rather than an error.
- cmd/product-projector/main.go run is 78 lines at cyclo 14, the highest in the repo; wiring would read better as named steps.
APIs and contracts
- Resource-oriented REST: PUT /products/{sku} and sub-resources (classification, dimensions, pack-levels/{level}) are naturally idempotent; retire is a custom method POST .../{level}:retire, documented idempotent (openapi.yaml:31).
- Errors are problem+json with stable type URIs (e.g. .../errors.product-master.warehouse-systems.dev/pack-level-not-found) and 409s on every write; list endpoints use opaque cursor pagination.
- No If-Match/ETag although products expose a version, so concurrent PUTs are last-writer-wins at the client level; no URL versioning (spec 1.0.0).
- MCP: 6 read-only tools plus 2 writes annotated Idempotent with explicit DestructiveHint, enforced by governance_test.go; good hygiene, but writes rely on network trust only.
REST: 17 operations (10 read, 7 write, 0 of 7 writes require Idempotency-Key)
| GET | /products | List products |
| PUT | /products/{sku} | Register a product or change its description |
| GET | /products/{sku} | Get a product |
| PUT | /products/{sku}/classification | Set or replace a product's handling classification |
| GET | /products/{sku}/classification | Get a product's handling classification |
| PUT | /products/{sku}/dimensions/declared | Declare a product's unit dimensions and weight |
| PUT | /products/{sku}/dimensions/measured | Record a measurement of one unit |
| GET | /products/{sku}/physical-profile | Get a product's physical profile |
| GET | /gtins/{gtin} | Resolve a GTIN to its SKU and pack level |
| GET | /products/{sku}/pack-levels | List a product's pack levels |
| PUT | /products/{sku}/pack-levels/{level} | Declare a pack level |
| POST | /products/{sku}/pack-levels/{level}:retire | Retire a pack level |
| PUT | /products/{sku}/pack-levels/{level}/measured | Record a measurement of one pack |
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| GET | /reports/master-data-quality | Master data quality per day and current coverage |
| GET | /reports/freshness | How far the analytics projection is behind |
Events published: 8 types on warehouse.product-master.analytics, warehouse.product-master.events
- product.ProductClassified
- product.ProductDescriptionChanged
- product.ProductDimensionsDeclared
- product.ProductMeasured
- product.ProductPackLevelDeclared
- product.ProductPackLevelMeasured
- product.ProductPackLevelRetired
- product.ProductRegistered
MCP tools: 8 (6 read-only)
get_product | read | Read one product by SKU: description, version, its handling classification (omitted when unclassified) and its physical profile (declared and latest measured unit dimensions/weight, the effective one used by the warehous |
list_products | read | List products in ascending SKU order, a page at a time (default 100, max 500), optionally only those whose classification carries handling_tag and/or only classified (classified=true) or unclassified (classified=false) o |
get_product_classification | read | Read the handling classification of one SKU: handling_tags in stable order (Hazmat, Fragile, TemperatureSensitive, Oversized, HighValue), temperature_class (Ambient, Chilled, Frozen; only with TemperatureSensitive), dot_ |
get_physical_profile | read | Read the physical profile of one SKU: declared dimensions (length_mm, width_mm, height_mm, weight_g, volume_mm3), the latest measurement (same fields plus measured_at and device_id), the effective dimensions (measured wi |
resolve_gtin | read | Resolve a GTIN (EAN/UPC/GTIN-14 as printed on a barcode; 8, 12, 13 or 14 digits, normalised to 14) to the SKU and packaging level it identifies: sku, level (EACH, INNER, CASE, PALLET), units_per_pack (eaches in one pack) |
get_pack_levels | read | Read the packaging hierarchy of one SKU: every pack level it ever declared, retired ones included, lowest level first |
declare_pack_level | write | WRITE |
retire_pack_level | write | WRITE |
A2A skills: 2
- Declare a packaging level with its GTIN
- Product handling and packaging profile
Recommended next steps
- Replace mustStoredGTIN's panic with a wrapped corruption error and handle the ByGTIN ok flag in DeclarePackLevel.
- Gate the MCP write tools behind a config flag or move them to a separately deployed MCP binary until auth returns.
- Split packaging.go into hierarchy/validation files and decide explicitly whether pack-level events belong on the analytics stream.
Measured at origin/develop 28de57f (2026-10-31). Review sampled 5 files.
Architecture
Clean code
API design
Solid returns context with three focused aggregates, a data-driven disposition policy and atomic save-and-publish; spec drift (/metrics), missing metrics and a red develop integration job need attention.
Value recovery matters, but the differentiator is the ledger it feeds; the disposition policy is a replaceable data object.
- Production code
- 13,993 lines Go in 108 files, 29 packages
- Tests
- 14,953 lines, 308 test functions, 11 integration files, 15 BDD scenarios, 31 fitness tests
- Function size
- avg 11.1 lines (p95 32), 1 over 60 lines
- Complexity
- avg cyclomatic 2.8; highest IdempotencyStore (14), Event.validateEnvelope (12)
- Layering
- 0 infrastructure imports in domain/application; 4 domain packages
- Quality gates
- coverage 90%, mutation efficacy 95%, 19 CI jobs
- Persistence
- PostgreSQL, 3 migrations, 14 tables
- Deployables
- a2a, api, mcp, returns-projector, returns-reports
- Largest files
- none over 500 lines
- Console remote (web/)
- 2,041 lines TS/TSX, 8 test files
- Decisions
- 8 ADRs, 52 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (API, MCP, A2A, analytics projector, reports API); Postgres + outbox to Kafka; separate analytics store
Strengths
- Three aggregates (returnauthorization, returnreceipt, disposition) with an append-only, versioned DispositionPolicy table treated as data, not code (internal/domain/disposition/policy.go).
- InspectReturnLine saves the receipt and the disposition and publishes both event sets in one unit of work (internal/application/usecases/inspect_return_line.go:77-88).
- Analytics is a separate read path: returns-projector consumes the analytics topic into its own store and returns-reports serves /reports/* (cmd/returns-projector, cmd/returns-reports).
- One use-case struct per command with explicit port fields (authorize_return.go, override_disposition.go, declare_disposition_policy.go).
Concerns
- No metrics instrumentation: no Go file references metrics/Prometheus, yet apis/openapi.yaml:424 documents GET /metrics; operational visibility is traces/logs only.
- InspectReturnLine reads the receipt and current policy before opening the unit of work (inspect_return_line.go:43-58) and does not retry on a concurrent-update conflict, unlike sibling contexts' bounded retry loops.
- Authorised quantity is capped only by MaxUnitsPerLine; the shipped-quantity check is 'planned, not built' (internal/domain/disposition/policy.go:72-73, ADR 0003), so over-returns are possible.
Clean code
Strengths
- 657 funcs, avg 11.1 lines, p95 32, none over cyclomatic 15; domain packages split by concern (values.go, events.go, snapshot.go per aggregate).
- Clear doc comments tie behaviour to ADRs and explain fail-open choices (classification() in inspect_return_line.go documents the hazmat guardrail).
- Test LOC 15k vs 14k prod, 11 integration-tagged files, shared repocontract suites for memory and postgres, 31 fitness tests, 95% mutation gate, docs-api-drift CI job.
Concerns
- The latest develop CI run is red on its integration job (.github/workflows/ci.yml:128 'integration'), so the main branch is not currently releasable.
- inspect_return_line.go, the core decision use case, has no dedicated unit test file in internal/application/usecases (it is exercised via open_return_receipt_test.go and HTTP tests); BDD covers only 15 scenarios.
- Web remote has a 486-line screen (web/src/screens/ReturnDetailScreen.tsx) and no e2e specs.
APIs and contracts
- Every write requires Idempotency-Key with documented replay and 409/422 reuse problems; errors are problem+json with typed URIs (apis/openapi.yaml:494-694).
- Resource modelling mixes styles: POST /receipts/{id}/lines/{lineNo}/inspect and /dispositions/{id}/override are verbs-as-subpaths, while sibling repos use :verb custom methods.
- Spec drift: /metrics is specified but not implemented, and the four /reports/* routes of returns-reports (internal/adapters/inbound/http/reports_handler.go:99-102) are absent from apis/openapi.yaml.
- Events (com.warehouse.wms.returns-processing.<aggregate>.<Type>) are well named, but apis/asyncapi.yaml is AsyncAPI 2.6.0 while most of the fleet uses 3.0.0; GET /returns has no pagination.
REST: 11 operations (6 read, 5 write, 5 of 5 writes require Idempotency-Key)
| POST | /returns | Authorize a return (open an RMA) |
| GET | /returns | List the RMAs of an order |
| GET | /returns/{rmaId} | Get an RMA |
| POST | /returns/{rmaId}/receipts | Open a return receipt against an RMA |
| POST | /receipts/{receiptId}/lines/{lineNo}/inspect | Grade a receipt line and decide its disposition |
| POST | /dispositions/{dispositionId}/override | Override a disposition with a reason |
| PUT | /disposition-policies/{version} | Declare a disposition policy version |
| GET | /disposition-policies/current | Get the current disposition policy |
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| GET | /metrics | Prometheus metrics |
Events published: 7 types on warehouse.returns-processing.analytics, warehouse.returns-processing.events
- disposition.DispositionDecided
- disposition.ReturnLineStaged
- returnauthorization.ReturnAuthorizationRejected
- returnauthorization.ReturnAuthorized
- returnreceipt.ReturnLineInspected
- returnreceipt.ReturnReceiptOpened
- returnreceipt.UnexpectedReturnReceived
Events consumed: 4 types from 3 topics
warehouse.fulfillment.events, warehouse.order-management.events, warehouse.product-master.events
- package.PackageManifested fulfillment-execution
- order.OrderAllocated order-management
- order.OrderPartiallyAllocated order-management
- product.ProductClassified product-master
MCP tools: 3 (3 read-only)
get_return | read | Read one return authorization (RMA) by id: the original order id and line number it was authorized against, the work unit ({order_id}-line-{line_no}) the goods shipped in, the sku, quantity and site, the reason code, the |
list_returns_by_order | read | List every return authorization (RMA) of one original order, ordered by line number then id |
get_disposition_policy | read | Read the disposition policy table: the version, the return window in days, the maximum units per return line, the veto outcome a guardrail demotes to (default DISPOSE), the declared instant and the rule table mapping eac |
A2A skills: 2
- Read the disposition policy
- Where does a return stand
Recommended next steps
- Fix the failing develop integration job before the next release.
- Reconcile apis/openapi.yaml with handlers: add the /reports/* spec, and either implement /metrics (OTel/Prometheus) or drop it.
- Add a dedicated InspectReturnLine unit test suite and a bounded retry on concurrent-update, matching sibling contexts.
Measured at origin/develop c69a0dc (2026-10-30). Review sampled 7 files.
Architecture
Clean code
API design
Strong decision-support context: a pure, deterministic planner behind a validated SlotPlan state machine, local event-fed copies instead of sync calls, and solid gates; watch transaction length and event size.
Cuts pick travel and labor but is not the fleet's differentiator; the policy is replaceable.
- Production code
- 14,087 lines Go in 93 files, 32 packages
- Tests
- 20,025 lines, 481 test functions, 23 integration files, 50 BDD scenarios, 25 fitness tests
- Function size
- avg 12.6 lines (p95 32), 3 over 60 lines
- Complexity
- avg cyclomatic 3.2; highest run (14), packLevelRoundTrip (14)
- Layering
- 0 infrastructure imports in domain/application; 3 domain packages
- Quality gates
- coverage 90%, mutation efficacy 99%, 18 CI jobs
- Persistence
- PostgreSQL, 4 migrations, 15 tables
- Deployables
- a2a, api, mcp, slotting-projector, slotting-reports
- Largest files
- cmd/api/main.go (703)
- Console remote (web/)
- 1,962 lines TS/TSX, 8 test files
- Decisions
- 13 ADRs, 56 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (API+consumers, projector, reports, MCP, A2A); Postgres + outbox to Kafka; event-fed local copies
Strengths
- Planning is a pure domain service with no I/O or clock, ranking policy behind a port, deterministic for any input order (internal/domain/planning/planner.go package doc).
- SlotPlan aggregate: Restore validates every invariant so corrupt rows never go live; Draft->Approved/Rejected->Superseded transitions return events (internal/domain/slotplan/plan.go).
- No synchronous coupling: demand, product profiles, pack levels, slots and zones are local copies fed by 11 consumed CloudEvents types from 4 contexts; one Approved plan per site enforced by a partial unique index.
- GeneratePlan stores the Draft and enqueues SlotPlanGenerated in one unit of work via the outbox (internal/application/usecases/generate_plan.go Handle).
Concerns
- The whole plan computation (demand, profiles, slot catalogue reads plus Planner.Plan) runs inside the UoW transaction (usecases/generate_plan.go:59-85), holding a DB transaction for the full solve on large sites.
- SlotPlanApproved carries the full assignment map and all moves (internal/domain/slotplan/plan.go:187-192); for a large site this can approach Kafka's default 1 MB message limit with no chunking or claim-check.
- cmd/api hosts HTTP, all consumers and the outbox relay in one process (cmd/api/main.go startConsumers/startOutboxRelay), so ingest and API scale together.
Clean code
Strengths
- 20k test LOC vs 14k prod LOC; 481 test funcs, 23 integration-tagged files, 50 godog scenarios, 25 fitness tests, a shared repository contract suite; coverage 90% and mutation gates at 99%.
- Zero layer-import violations, no clock/uuid/struct tags in the domain, no function above cyclo 15 (max 14), average function 12.5 lines.
- Typed sentinel errors in the planner (planner.go ErrRankingContract etc.) and wrapped errors with context in use cases ('read demand: %w', generate_plan.go gather).
- Use case split into small helpers (gather, zoneCodes, markCaseFaces, addCasePick, previous) that each do one thing.
Concerns
- cmd/api/main.go is 703 lines with ~30 functions of env parsing, adapter wiring, consumer specs and shutdown; config parsing would be clearer in its own package.
- GeneratePlan has optional coupled fields (PackLevels nil only when CasePickZoneCodes empty) checked at request time (generate_plan.go:33-35,162-164) rather than at construction.
- internal/domain/slotplan/plan.go (446 lines) and planning/planner.go (478 lines) are the largest domain files; planner.go validate has cyclo 12, a candidate for table-driven checks.
APIs and contracts
- Good resource model: /slot-plans with state transitions as POST /{planId}/approve and /reject, problem+json with typed URIs (e.g. .../invalid-cursor), opaque cursor pagination, Idempotency-Key on POST /slot-plans (apis/openapi.yaml).
- Approve/reject are naturally idempotent-safe (re-approve is 409 plan-not-draft) but take no If-Match/expected version even though plans expose `version`, so a client cannot assert it reviewed the latest draft.
- Event contract: 3 SlotPlan CloudEvents types on events + analytics streams; consumer side handles 11 upstream types. No URL versioning (spec 1.0.0).
- MCP tools (get_slot_plan, list_slot_plans, get_forward_slots, get_sku_velocity) are read-only with ReadOnly/Idempotent annotations (internal/adapters/inbound/mcp/tools.go:295); no agent can approve plans.
REST: 11 operations (8 read, 3 write, 1 of 3 writes require Idempotency-Key)
| POST | /slot-plans | Generate a slot plan |
| GET | /slot-plans | List slot plans |
| GET | /slot-plans/{planId} | Get a slot plan |
| POST | /slot-plans/{planId}/approve | Approve a Draft plan |
| POST | /slot-plans/{planId}/reject | Reject a Draft plan |
| GET | /forward-slots | The current approved forward-slot map |
| GET | /sku-velocity | SKU velocity over a window |
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| GET | /reports/slot-plan-funnel | The slot-plan review funnel per day |
| GET | /reports/freshness | How far the analytics projection is behind |
Events published: 3 types on warehouse.slotting-optimization.analytics, warehouse.slotting-optimization.events
- slotplan.SlotPlanApproved
- slotplan.SlotPlanGenerated
- slotplan.SlotPlanRejected
Events consumed: 11 types from 4 topics
warehouse.facility.events, warehouse.inventory.events, warehouse.order-management.events, warehouse.product-master.events
- siteskudemand.SiteSkuDemandChanged order-management
- locationslot.LocationSlotDecommissioned facility-layout
- locationslot.LocationSlotRegistered facility-layout
- zone.ZoneRegistered facility-layout
- stock.StockRelocated inventory-storage
- product.ProductClassified product-master
- product.ProductDimensionsDeclared product-master
- product.ProductMeasured product-master
- product.ProductPackLevelDeclared product-master
- product.ProductPackLevelMeasured product-master
- product.ProductPackLevelRetired product-master
MCP tools: 4 (4 read-only)
get_slot_plan | read | Read one forward pick slot plan by id: site_id, state (Draft, Approved, Rejected or Superseded), policy, the demand window (window_from, window_to), generated_at and the decision instants (approved_at, rejected_at, super |
list_slot_plans | read | List slot plans newest first, a page at a time (default 100, max 500), as summaries (ids, site, state, policy, window and assignment/move/unassigned counts), optionally only those of one site and/or in one state (Draft, |
get_forward_slots | read | Read the CURRENT forward slot map of a site: the assignments (sku, slot, abc_class) of its Approved plan, with that plan_id and approved_at |
get_sku_velocity | read | Read the demand the planner works from: per SKU the ACTIVE order lines (picks) and units over the last window_days days (default 28, max 365) of a site, fastest first, cut to limit SKUs (default 100, max 500) |
A2A skills: 2
- Current forward slot map of a site
- Review a slot plan
Recommended next steps
- Read inputs and run Planner.Plan outside the write transaction, then open the UoW only to persist the Draft and outbox event.
- Bound SlotPlanApproved size: emit moves only or a claim-check reference to GET /slot-plans/{planId} for large sites.
- Move env/config parsing out of cmd/api/main.go into a tested config package.
Measured at origin/develop 7f896c8 (2026-10-30). Review sampled 6 files.
Architecture
Clean code
API design
Solid capacity-planning context with a pure capacity model, atomic publish-plus-outbox and the largest test suite sampled; gaps are a manually seeded process-path copy, no create idempotency and broad MCP write access.
No other context computes normalized end-to-end capacity or forward shortages; high differentiation and complexity.
- Production code
- 15,916 lines Go in 124 files, 29 packages
- Tests
- 30,560 lines, 671 test functions, 30 integration files, 84 BDD scenarios, 24 fitness tests
- Function size
- avg 13.5 lines (p95 42), 6 over 60 lines
- Complexity
- avg cyclomatic 2.9; highest run (14), RegisterProcessCapacityConstraint.Handle (12)
- Layering
- 0 infrastructure imports in domain/application; 6 domain packages
- Quality gates
- coverage 90%, mutation efficacy 99%, 19 CI jobs
- Persistence
- PostgreSQL, 11 migrations, 15 tables
- Deployables
- a2a, api, mcp, planning-projector, planning-reports
- Largest files
- internal/adapters/inbound/mcp/tools.go (718), cmd/api/main.go (523)
- Console remote (web/)
- 2,000 lines TS/TSX, 8 test files
- Decisions
- 18 ADRs, 78 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (API+consumers, projector, reports, MCP, A2A); Postgres + outbox to Kafka; 6 domain packages
Strengths
- CapacityPlan aggregate does no I/O and is built from a precomputed ProcessPathCapacity plus explicit ids/timestamps (domain/capacityplan/capacity_plan.go); a double publish is refused with ErrAlreadyPublished.
- PublishCapacityPlan saves the plan and enqueues all its events in one UnitOfWork; FindByID locks FOR UPDATE inside the UoW so concurrent publishes serialise (publish_capacity_plan.go, capacity_plan_repository.go:57-64).
- Demand, inbound appointments, slot tallies and observed throughput are event-fed local read models (8 consumed CloudEvents types from 5 contexts) rather than synchronous calls.
- Separate events vs analytics streams, with analytics-only fields (bottleneck constraint) kept off integration events by design (capacity_plan.go:109-113).
Concerns
- Process paths are a manually seeded copy: POST /process-paths 'since there is no event-driven sync from process-path-management yet' (apis/openapi.yaml:167-173), so this catalogue can drift from the system of record.
- The MCP server exposes 6 write tools including create_capacity_plan and publish_capacity_plan (internal/adapters/inbound/mcp/tools.go:596-599) on an unauthenticated endpoint; published plans drive network-inventory-planning transfers.
- Concurrency relies on pessimistic FOR UPDATE locks; the aggregate has no version (capacity_plan.go:89-126), so clients get no stale-read detection across separate requests.
Clean code
Strengths
- 30.6k test LOC vs 15.9k prod LOC (largest in this sample): 671 test funcs, 30 integration-tagged files, 84 godog scenarios, 24 fitness tests; coverage 90% and mutation gates at 99%.
- Zero layer-import violations, no clock/uuid/struct tags/panics in production code, average cyclomatic 2.9, nothing above cyclo 15.
- Use cases are short and read as a script with the invariant stated up front (publish_capacity_plan.go is 65 lines); the clock is injectable (Now func) throughout.
- Domain errors carry the business reason (capacity_plan.go ErrAlreadyPublished explains why a re-announce is refused).
Concerns
- internal/adapters/inbound/mcp/tools.go is 718 lines registering 14 tools in one file, and cmd/api/main.go is 523 lines; both would read better split by tool group or concern.
- CreateCapacityPlan.handle is 69 lines/cyclo 10 and RegisterProcessCapacityConstraint.Handle cyclo 12 (internal/application/usecases/create_capacity_plan.go, register_process_capacity_constraint.go), the densest use cases.
- CapacityPlan carries many informational fields (demandSource, warnings, inbound) alongside invariants (capacity_plan.go:89-126), blurring aggregate state with read-model data.
APIs and contracts
- Broad, resource-named surface (22 ops): /capacity-plans with POST /{id}/publish transition, PUT /station-standards/{location}/{process_type} and /inbound-labour-standards/{location}/{path_id} as idempotent upserts; problem+json with 409s.
- POST /capacity-plans takes no Idempotency-Key (none anywhere in apis/openapi.yaml), so a retried create mints a duplicate DRAFT plan; POST /process-capacities is described as an upsert but still uses POST.
- No If-Match/ETag and no URL versioning (spec version 0.1.0); the spec is 1846 lines, thorough on semantics.
- Events: 6 integration + 4 analytics CloudEvents types; MCP mirrors REST with 14 tools, write tools annotated non-read-only with an IdempotentHint per tool (tools.go:596-599).
REST: 21 operations (15 read, 6 write, 0 of 6 writes require Idempotency-Key)
| POST | /process-capacities | Register (or upsert) one capacity constraint |
| GET | /process-capacities | Get the effective capacity for a process, location and window |
| GET | /process-paths | List the registered ProcessPaths |
| POST | /process-paths | Register (seed) a ProcessPath read model |
| GET | /process-paths/{id}/capacity | Get a ProcessPath's normalized, end-to-end capacity |
| GET | /capacity-plans | List the most recent CapacityPlans |
| POST | /capacity-plans | Create a DRAFT CapacityPlan and compute its shortage |
| GET | /capacity-plans/{id} | Get a CapacityPlan |
| POST | /capacity-plans/{id}/publish | Publish a DRAFT CapacityPlan |
| PUT | /station-standards/{location}/{process_type} | Declare the throughput of ONE station of a process at a site |
| GET | /station-standards | List the declared station standards |
| GET | /storage-capacity | Storage positions and stations of a site (read model) |
| GET | /demand | Expected demand of a site over a window (order-management read model) |
| PUT | /inbound-labour-standards/{location}/{path_id} | Declare the labour minutes a dock appointment costs at a site for a process path |
| GET | /inbound-labour-standards | List the declared inbound labour standards |
| GET | /inbound-demand | Inbound demand of a site over a window (inbound-receiving read model) |
| GET | /capacity-plans/{id}/variance | Planned versus observed throughput of a capacity plan (advisory) |
| GET | /reports/bottleneck-frequency | How often each bottleneck step (and binding constraint) bound a PUBLISHED plan, by site |
| GET | /reports/shortage-trend | Published plans with shortage and total shortage by site per day |
| GET | /reports/plan-throughput | Plans created vs published per day, and create-to-publish latency by site |
| GET | /reports/freshness | How far the analytics projection is behind |
Events published: 6 types on warehouse.warehouse-planning.analytics, warehouse.warehouse-planning.events
- capacityplan.BottleneckDetected
- capacityplan.CapacityPlanCreated
- capacityplan.CapacityPlanPublished
- capacityplan.CapacityShortageDetected
- processcapacity.ProcessCapacityChanged
- processcapacity.ProcessCapacityRegistered
Events consumed: 8 types from 5 topics
warehouse.facility.events, warehouse.fulfillment.events, warehouse.inbound-receiving.events, warehouse.order-management.events, warehouse.workforce.events
- task.TaskCompleted fulfillment-execution
- order.OrderAllocated order-management
- order.OrderPartiallyAllocated order-management
- shiftplan.ShiftPlanCommitted workforce-management
- locationslot.LocationSlotDecommissioned facility-layout
- locationslot.LocationSlotRegistered facility-layout
- dockappointment.DockAppointmentBooked inbound-receiving
- dockappointment.DockAppointmentCancelled inbound-receiving
MCP tools: 14 (8 read-only)
declare_inbound_labour_standard | write | Declare the labour a dock appointment costs at a site for a process path: minutes_per_appointment (required, positive) plus an optional minutes_per_asn per ASN the appointment covers |
get_inbound_demand | read | Read the inbound demand of a site over a window from the local read model fed by inbound-receiving's DockAppointmentBooked / DockAppointmentCancelled events: appointments = BOOKED dock appointments whose door window STAR |
get_capacity_plan_variance | read | Compare a stored capacity plan with what the floor actually did: the TASKS completed for the plan's bottleneck step at its location over its window (fulfillment-execution TaskCompleted events, minute resolution) against |
register_process_capacity_constraint | write | Register one capacity constraint (e.g |
get_effective_process_capacity | read | Read the effective capacity rate of a process step at a location for an exact window, the binding constraint and every registered constraint |
register_process_path | write | Declare a process path: an id, a name and an ordered, non-empty list of step process types (e.g |
get_process_path_capacity | read | Compute a registered process path's end-to-end capacity at a location and window, normalized to ORDER per hour, and the bottleneck step |
create_capacity_plan | write | Evaluate assigned demand (orders) against a process path's capacity over a window and store a DRAFT capacity plan, returning path capacity (ORDER/hour), capacity over the window, shortage (orders, 0 if none), the bottlen |
publish_capacity_plan | write | Publish a DRAFT capacity plan, making it PUBLISHED and queueing its CapacityPlanPublished (and shortage/bottleneck) events in the outbox |
get_capacity_plan | read | Read a capacity plan by id: its status (DRAFT or PUBLISHED), path capacity, capacity over window, shortage, bottleneck step, the constraint type binding it (bottleneck_constraint) and any composition warnings |
declare_station_standard | write | Declare the throughput of ONE station of a process at a site (e.g |
list_station_standards | read | List the declared station standards (throughput of one station per location and process type), optionally filtered by location |
get_storage_capacity | read | Read the facility-layout read model of a site: storage positions per zone and location type, and work-center station counts per zone and activity |
get_expected_demand | read | Read the expected demand of a site over a window from the local read model fed by order-management's published order events (OrderAllocated, OrderPartiallyAllocated): orders = distinct orders whose promise cutoff falls i |
A2A skills: 2
- Capacity of a process path in a window
- Evaluate assigned demand against a path's capacity
Recommended next steps
- Replace the POST /process-paths seed with a consumer of process-path-management's ProcessPathCreated/Updated/Deactivated events.
- Add a required Idempotency-Key to POST /capacity-plans (fleet middleware) and expose ETag/If-Match on plan transitions.
- Move publish_capacity_plan and other MCP writes behind a config flag or separate binary until auth is restored.
Measured at origin/develop 2d3bab5 (2026-10-30). Review sampled 5 files.
Warehouse Execution (WES) 8 applications
Architecture
Clean code
API design
Well-modelled exception-case context (dedup, SLA clock, audit trail, versioned policies) with outbox, analytics projector and reports binaries; the REST/MCP contracts drift from fleet conventions and lists are unpaged.
Bookkeeping around other contexts' facts; could become Core if auto-resolution at scale cuts labor cost.
- Production code
- 12,247 lines Go in 98 files, 31 packages
- Tests
- 14,997 lines, 325 test functions, 16 integration files, 20 BDD scenarios, 31 fitness tests
- Function size
- avg 11.9 lines (p95 33), 2 over 60 lines
- Complexity
- avg cyclomatic 3.1; highest validateSnapshotIdentity (14), Memory.SLABreachRows (13)
- Layering
- 0 infrastructure imports in domain/application; 3 domain packages
- Quality gates
- coverage 90%, mutation efficacy 95%, 19 CI jobs
- Persistence
- PostgreSQL, 4 migrations, 8 tables
- Deployables
- a2a, api, exceptions-projector, exceptions-reports, mcp
- Largest files
- none over 500 lines
- Console remote (web/)
- 1,700 lines TS/TSX, 7 test files
- Decisions
- 7 ADRs, 52 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (API, MCP, A2A, analytics projector, reports); Postgres + outbox to Kafka; 11 consumed fact types
Strengths
- ExceptionCase aggregate is pure (no I/O, no clock reads), with a fixed status machine, dedup key with occurrence counting, SLA due time and one audit entry per accepted transition (internal/domain/exceptioncase/case.go)
- One-open-case-per-key is enforced twice: by the OpenOrTouch domain decision and by a partial unique index, plus a version-guarded upsert for concurrent writers (internal/adapters/outbound/postgres/case_repository.go)
- Cases only open from consumed facts (POST /exceptions is a deliberate 405); consumer replays of the opening event id are no-ops (internal/application/usecases/open_or_touch.go:78)
- Analytics read side is isolated in its own projector and reports binaries fed by an analytics twin topic (ADR 0006; cmd/exceptions-projector, cmd/exceptions-reports)
Concerns
- Several consumed sources are marked 'PENDING PRODUCER PROMOTION' (analytics-only upstream today), so those exception types cannot open cases yet (apis/asyncapi.yaml:147,618,865,898)
- Every REST command records actor 'system' because the contract carries no operator identity (internal/adapters/inbound/http/server.go:15), so the audit trail cannot say who triaged, assigned or resolved a case
- Integration and analytics topics carry identical twins of all 7 events (apis/asyncapi.yaml warehouse.exception-management.analytics), doubling outbox/broker volume for one internal projector
Clean code
Strengths
- Avg 11.9 lines and cyclo 3.1 per function, none over cyclo 15 (facts); doc comments state the ADR rule each function implements (exceptioncase/case.go, usecases/open_or_touch.go)
- Strong verification: 16 integration-tagged files (incl. concurrency tests for the unique index and lost updates in postgres/cases_integration_test.go), 20 BDD scenarios, 95% mutation gate, Trivy scan in CI (facts)
- Errors are typed and mapped centrally; undeclared policy is a typed ErrPolicyUndeclared that the consumer logs and skips rather than blocking a partition (usecases/open_or_touch.go:16)
Concerns
- Misleading name: FindOpenByDedupKey returns the open case OR the most recent RESOLVED case (internal/adapters/outbound/postgres/case_repository.go:103-107), which the use case relies on for touch-after-resolve
- Composition roots are long: cmd/api/main.go run is 90 lines and cmd/exceptions-projector/main.go run 67 lines (facts), the only functions over 60 lines
- case.go is 456 lines, the largest domain file, combining the lifecycle, SLA and auto-resolve evidence (internal/domain/exceptioncase/case.go)
APIs and contracts
- Good: Idempotency-Key on all POSTs and the PUT, append-only versioned policies via PUT /exception-policies/{sourceType}, problem+json with absolute type URIs and examples, version in case bodies (apis/openapi.yaml)
- Drifts from fleet style: sub-path verbs (/triage, /assign) not :custom methods; key reuse returns 409 not 422 (apis/openapi.yaml:577); MCP output is snake_case (case_id, occurrence_count) vs camelCase REST/A2A (inbound/mcp/tools.go:37-92)
- GET /exceptions has only status/queue filters and returns the full matching list, with no pagination (apis/openapi.yaml, usecases/reads.go:23); no ETag/If-Match even though the case version is exposed
- Events use the warehouse.* namespace and AsyncAPI 2.6.0 while the logistics repos use 3.0.0; payloads are well documented with v1 dataschema URNs for both topics (apis/asyncapi.yaml)
REST: 11 operations (6 read, 5 write, 4 of 5 writes require Idempotency-Key)
| GET | /exceptions | List exception cases |
| POST | /exceptions | Cases are never created over REST (always 405) |
| GET | /exceptions/{caseId} | Get an exception case |
| POST | /exceptions/{caseId}/triage | Triage a case |
| POST | /exceptions/{caseId}/assign | Assign a case |
| POST | /exceptions/{caseId}/resolve | Resolve a case |
| GET | /exception-policies | List the handling policies |
| PUT | /exception-policies/{sourceType} | Declare a new version of a handling policy |
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| GET | /metrics | Prometheus metrics |
Events published: 7 types on warehouse.exception-management.analytics, warehouse.exception-management.events
- exceptioncase.ExceptionAssigned
- exceptioncase.ExceptionAutoResolved
- exceptioncase.ExceptionEscalated
- exceptioncase.ExceptionOpened
- exceptioncase.ExceptionResolved
- exceptioncase.ExceptionTriaged
- exceptionpolicy.ExceptionPolicyDeclared
Events consumed: 11 types from 7 topics
warehouse.fulfillment.events, warehouse.inbound-receiving.events, warehouse.inventory.events, warehouse.network-fulfillment.events, warehouse.order-management.events, warehouse.returns-processing.events, warehouse.work-planning.events
- package.PackageDiverted fulfillment-execution
- package.WeightDiscrepancyDetected fulfillment-execution
- task.TaskCPTMissed fulfillment-execution
- networkorder.AcknowledgementDeadlineAtRisk network-fulfillment
- networkorder.OrphanedHoldCancelled network-fulfillment
- order.OrderRepromised order-management
- workpool.BacklogThresholdBreached wes-work-planning
- receipt.CartonDiscrepancyRaised inbound-receiving
- bin.DiscrepancyDetected inventory-storage
- stock.ItemUnlocated inventory-storage
- returnreceipt.UnexpectedReturnReceived returns-processing
MCP tools: 4 (4 read-only)
list_open_exceptions | read | List the exception cases of the warehouse, newest opened first, optionally narrowed by status (OPEN, TRIAGED, ASSIGNED or RESOLVED; omitted means every status, open and resolved alike — resolve activity is part of the re |
get_exception | read | Read one exception case by id: the dedup identity, status, severity, queue, occurrence_count, escalated flag, assignee, the SLA clock (sla_minutes, sla_due_at), the frozen source_payload, the resolution (resolution_code, |
get_exception_policies | read | List the exception policy declared for every source type, ordered by source type: the latest version, the severity and queue a new case of that type opens with, sla_minutes, and auto_resolve — null when the type has no r |
get_sla_report | read | Read how the open caseload sits against its SLA clocks at generated_at: open_cases, breached (open cases past their sla_due_at), escalated (cases the SLA sweeper flagged) and the open counts by_severity and by_queue |
A2A skills: 2
- Find exception cases
- SLA status of the open exception caseload
Recommended next steps
- Add cursor pagination to GET /exceptions and list_open_exceptions before caseload grows
- Accept an operator identity (e.g. an X-Actor header or body field) on triage/assign/resolve so the audit trail records real actors
- Align with fleet conventions: camelCase MCP output, 422 for key reuse, AsyncAPI 3.0; rename FindOpenByDedupKey to FindLatestByDedupKey
Measured at origin/develop 47b165c (2026-10-30). Review sampled 8 files.
Architecture
Clean code
API design
Feature-rich, exhaustively tested execution context (113 BDD scenarios, 59 ADRs, breakers on sync calls), but claim-next scans the whole pool, idempotency covers 2 writes, and the Task aggregate and main.go keep growing.
Pull dispatch with leases drives throughput; Pack and SLAM slices are Supporting and kept thin.
- Production code
- 21,073 lines Go in 157 files, 40 packages
- Tests
- 38,919 lines, 1077 test functions, 40 integration files, 113 BDD scenarios, 31 fitness tests
- Function size
- avg 12.6 lines (p95 36), 13 over 60 lines
- Complexity
- avg cyclomatic 3.0; highest SealPackage.seal (15), AnalyticsPublisher.marshalData (14)
- Layering
- 0 infrastructure imports in domain/application; 7 domain packages
- Quality gates
- coverage 90%, mutation efficacy 90%, 21 CI jobs
- Persistence
- PostgreSQL, 26 migrations, 15 tables
- Deployables
- a2a, execution, fulfillment-projector, fulfillment-reports, mcp, sweep
- Largest files
- cmd/execution/main.go (869), internal/adapters/inbound/kafka/consumer.go (623), internal/domain/task/task.go (601)
- Console remote (web/)
- 406 lines TS/TSX, 1 test files
- Decisions
- 59 ADRs, 164 docs pages
- Security scanning
- 1 open code-scanning, 2 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 6 binaries (execution, sweep, MCP, A2A, projector, reports); Postgres + outbox to Kafka; sync inventory/layout
Strengths
- Sync dependencies are guarded: inventory-storage and facility-layout clients sit behind gobreaker breakers with metrics (adapters/outbound/inventorystorage/breaker.go, facilitylayout/breaker.go)
- Case break uses a stable per-task Idempotency-Key towards inventory-storage, then completes the task and publishes in one UoW, so lost answers never break twice (usecases/complete_case_break.go)
- PULL dispatch keeps CPT priority bands intact while applying task-interleaving hints fail-open (usecases/claim_next.go orderWithHint); release decisions stay in planning, facts arrive as WorkReleased
- Zero layer violations, 31 fitness tests and 26 versioned migrations (facts); separate projector/reports binaries isolate analytics load
Concerns
- Claim-next loads EVERY pending or lease-expired task of a type with no LIMIT and filters capabilities in Go (internal/adapters/outbound/postgres/task_repo.go:219-226, usecases/claim_next.go:54-82): O(pool) per claim on the hottest path
- POST /paths/{pathId}/work-requests delegates synchronously over A2A to planning with a 10s timeout and no breaker (internal/adapters/outbound/a2a/client.go:55), and the remote release is itself not idempotent
- Task aggregate is a 601-line accretion of pick, pack, relocate, replenish, break-case and transfer concerns (internal/domain/task/task.go); its package doc still says 'Pick, Pack, or SLAM'
Clean code
Strengths
- Largest test investment in the fleet: 38.9k test LOC vs 21.1k prod, 1077 test funcs, 113 BDD scenarios in 23 features, 40 integration-tagged files, a fuzz test, contract and evals jobs (facts)
- Comments explain trade-offs and ADRs at the decision point (fail-open hints, case-break key reuse, scan replay ADR 0055 in router.go:106-108)
- Low average complexity (12.6 lines, cyclo 3.0, none above 15) despite the size (facts)
Concerns
- Five files over 500 lines, led by the composition root cmd/execution/main.go (869; run() 115 lines) plus inbound/kafka/consumer.go (623), domain/task/task.go (601), outbound/kafka/publisher.go (537), inbound/http/handlers.go (530) (facts)
- Runtime panics on production paths: mustMarshal in internal/adapters/outbound/kafka/analytics_publisher.go:394-399 and an unknown work-kind panic in internal/application/usecases/complete_task.go:169
- 13 functions over 60 lines; SealPackage.seal sits at the cyclo cap of 15 (internal/application/usecases/seal_package.go); optional nil UnitOfWork 'runs them back to back' (usecases/claim_next.go:29-31)
APIs and contracts
- Idempotency-Key is enforced only on POST /tasks and POST /tasks/{id}/scans (internal/adapters/inbound/http/router.go:95-113); claim-next, complete, seal-package and slam rely on domain idempotency despite the floor client sending keys
- Operational sweeps are public writes (POST /tasks/expire-leases, /tasks/sweep-cpt-misses) on an unauthenticated API (router.go:121-122), while a dedicated sweep binary also exists
- Verb sub-paths (/claim-next, /check-in, /complete, /seal-package, /slam) are consistent within the repo but unlike the logistics repos' :custom methods; reads such as GET /tasks?orderRef are unpaginated (apis/openapi.yaml)
- Event contract is rich (10 integration + 10 analytics events, typed by aggregate) but on AsyncAPI 2.6.0; the 2.6k-line openapi.yaml documents ADR links per enum value, e.g. AnyTaskType (apis/asyncapi.yaml, apis/openapi.yaml:1814)
REST: 25 operations (10 read, 15 write, 2 of 15 writes require Idempotency-Key)
| GET | /healthz | Liveness probe |
| GET | /reports/throughput | Throughput & Lease-Health report, keyed by task type, station and UTC hour |
| GET | /reports/throughput/freshness | How far the read model trails the event stream |
| POST | /tasks | Create a task and place it in the pool |
| GET | /tasks | Look up every task recorded for an order reference |
| POST | /stations | Register or re-register a station |
| POST | /stations/{stationId}/claim-next | PULL-dispatch the best-fit pending task to this station |
| POST | /stations/{stationId}/check-in | Check a worker or robot into a station |
| POST | /stations/{stationId}/check-out | Check the current occupant out of a station |
| POST | /tasks/{id}/renew-lease | Extend the active lease held by the claiming station |
| POST | /tasks/{id}/complete | Complete a task on behalf of the station that claimed it |
| POST | /tasks/{id}/scans | Confirm one scan of an each or case GTIN against a PICK task |
| POST | /tasks/{id}/break-case | Complete a BREAK_CASE task by breaking the sealed case in inventory-storage |
| POST | /tasks/{id}/seal-package | Scan contents and seal a Package for a Pack task's order |
| GET | /packages | Look up every Package sealed for an order reference |
| GET | /packages/{id} | Read one Package, including its SLAM outcome |
| POST | /packages/{id}/slam | Run the SLAM weigh-check on a sealed package |
| GET | /queues/{taskType}/depth | Read the pending-task count for a process path (read model) |
| GET | /capacity/{capability} | Read how many registered stations hold a given capability (read model) |
| POST | /paths/{pathId}/work-requests | Ask the Work Planning agent (over A2A) to admit the next unit for a path |
| POST | /tasks/expire-leases | Sweep every Claimed task whose lease has expired back to Pending |
| POST | /tasks/sweep-cpt-misses | Sweep every still-open task whose CPT has passed and report it as missed |
| POST | /rebin/arrivals | Record one picked line arriving at the order's Rebin consolidation slot |
| GET | /healthz | Liveness check |
| GET | /readyz | Readiness check |
Events published: 15 types on warehouse.fulfillment.analytics, warehouse.fulfillment.events
- package.LabelApplied
- package.PackageDiverted
- package.PackageManifested
- package.PackageSealed
- package.WeightDiscrepancyDetected
- task.ItemPicked
- task.LeaseExpired
- task.TaskAvailable
- task.TaskCPTMissed
- task.TaskClaimed
- task.TaskCompleted
- task.TaskCreated
- transfer.TransferArrived
- transfer.TransferDispatched
- transfer.TransferPicked
Events consumed: 8 types from 4 topics
warehouse.process-path-management.events, warehouse.product-master.events, warehouse.task-interleaving.events, warehouse.work-planning.events
- processpath.ProcessPathCreated process-path-management
- processpath.ProcessPathDeactivated process-path-management
- processpath.ProcessPathUpdated process-path-management
- stationtrip.InterleavingHintIssued task-interleaving
- workunit.WorkReleased wes-work-planning
- product.ProductClassified product-master
- product.ProductPackLevelDeclared product-master
- product.ProductPackLevelRetired product-master
MCP tools: 7 (5 read-only)
get_on_time_to_cpt | read | Return the on-time-to-CPT rate for a time window, optionally filtered by process path and station: the fraction of manifested packages (SLAM pass) whose manifest time was at or before the originating SLAM task's Critical |
triage_backlog | write | Standard operating procedure for triaging the fulfillment-execution work backlog using the read tools. |
get_fulfillment_throughput_report | read | Return the fulfillment throughput report (completions, avg claim-to-complete seconds, lease expiries, weigh-check diverts) for a time window, optionally filtered by process path and station |
get_queue_status | read | Return the number of Pending tasks in a process-path queue (PICK, PACK, SLAM, RELOCATE, REPLENISH, or BREAK_CASE). |
find_claimable_work | read | Return the highest-priority (earliest-CPT) task a station could claim now in a given process path, plus how many candidates exist |
diagnose_stuck_tasks | read | List claimed tasks whose lease has expired (or expires within a given window), each with the reason it is flagged. |
complete_task | write | Complete a claimed task on behalf of the station that holds its active claim |
A2A skills: 2
- Backlog status for a process path
- Complete a claimed task
Recommended next steps
- Push capability filtering and LIMIT into the claim query (SELECT ... FOR UPDATE SKIP LOCKED LIMIT n) to make claim-next O(1)
- Extend RequireIdempotencyKey to every station-facing write (claim-next, complete, seal-package, slam) and add a breaker to the A2A planning client
- Split Task by work kind (strategy/value objects) and break cmd/execution/main.go into wiring modules; replace production panics with errors
Measured at origin/develop 2c0814b (2026-10-30). Review sampled 9 files.
Architecture
Clean code
API design
Mature, heavily tested event-fed context (102 BDD scenarios, 99% mutation gate, 36 ADRs) with sound as-of standard resolution; weak spots are a 622-line composition root and SQL inside the HTTP adapter.
Measures execution against a standard; useful but not what differentiates fulfillment (labor-performance subdomain-classification).
- Production code
- 11,609 lines Go in 85 files, 27 packages
- Tests
- 22,022 lines, 446 test functions, 23 integration files, 102 BDD scenarios, 26 fitness tests
- Function size
- avg 13.3 lines (p95 38), 8 over 60 lines
- Complexity
- avg cyclomatic 2.7; highest serve (13), run (11)
- Layering
- 0 infrastructure imports in domain/application; 4 domain packages
- Quality gates
- coverage 90%, mutation efficacy 99%, 21 CI jobs
- Persistence
- PostgreSQL, 8 migrations, 9 tables
- Deployables
- a2a, labor, labor-projector, labor-reports, mcp
- Largest files
- cmd/labor/main.go (622)
- Console remote (web/)
- 905 lines TS/TSX, 3 test files
- Decisions
- 36 ADRs, 82 docs pages
- Security scanning
- 1 open code-scanning, 1 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (labor API+consumer, projector, reports, MCP, A2A); Postgres + outbox to Kafka; analytics read model
Strengths
- Respects the fleet ban on sibling REST/MCP calls: inputs arrive only via TaskCompleted on Kafka, and team-lift/travel data are declared, never looked up (internal/domain/standard/standard.go TeamLift, ADR 0015/0035).
- RecordTaskPerformance writes the processed-event marker, performance row, idle gap and outbox event in one unit of work, so redelivery never double-counts (usecases/record_task_performance.go Execute).
- LaborStandard revision closes the prior effective range instead of overwriting, and scoring resolves the standard active AS OF CompletedAt, keeping history accurate under replay (standard.go Close/IsActiveAt).
- CQRS split: labor-projector and labor-reports binaries serve the hourly report from a separate rollup with a freshness endpoint (apis/openapi-reports.yaml).
Concerns
- The inbound HTTP adapter runs raw SQL against pgxpool for idempotency (internal/adapters/inbound/http/idempotency.go:76,112) instead of going through a port, and the file says it was ported verbatim from order-management (fleet-level copy).
- Idle gaps are computed against the associate's latest saved completion (record_task_performance.go:212 RecentByAssociateID(...,1)), not the latest before CompletedAt, so out-of-order delivery can overstate a gap rather than only skip it.
- UnitOfWork, IdlePeriods and Logger are optional nil-able fields on the use case (record_task_performance.go:65-86); a nil UnitOfWork silently drops atomicity, relying on the composition root to wire it.
Clean code
Strengths
- 22k test LOC for 11.6k prod LOC; 446 test funcs, 23 integration-tagged files, 102 godog scenarios, 26 fitness tests; coverage gate 90% and gremlins efficacy/coverage gates at 99%.
- Zero layer-import violations, no time.Now/uuid/struct tags in the domain, average cyclomatic 2.7 and no function above cyclo 15.
- Domain errors are named sentinels with business rationale (standard.go ErrTeamLiftRequiresCaseUnit etc.), and use-case phases are small named helpers (record_task_performance.go record/recordIdleGap).
- Idempotency middleware documents its correctness and concurrency argument inline and cites ADR 0016 (idempotency.go:23-75).
Concerns
- cmd/labor/main.go is 622 lines with serve at 113 lines/cyclo 13 and run at 92 lines; wiring for HTTP, consumer, relay and readiness would read better split into files.
- Constructors take long positional lists: RehydrateForUnit has 9 parameters and NewForUnit 7 (internal/domain/standard/standard.go:144,177), a source of argument-order bugs; Rehydrate also skips invariant checks.
- Comments are very long relative to code (standard.go is 265 lines for ~60 lines of logic), which ages badly as rules change; some belong in the ADRs they already cite.
APIs and contracts
- POST /standards requires Idempotency-Key with byte-for-byte replay and documents 400/409/422 as problem+json (apis/openapi.yaml:103-175); read endpoints are resource-oriented (/associates/{id}/scorecard, /task-types/{t}/utilization).
- Define and revise are both POST /standards; a revision is not addressed as PUT /standards/{taskType}, and the spec has no If-Match/ETag although the aggregate carries an optimistic version.
- No path versioning (both specs version 1.0.0, unversioned paths); the HTTP adapter has no request-size limit (no MaxBytesReader in the repo; idempotency.go:92 io.ReadAll), notable on unauthenticated endpoints.
- Events follow CloudEvents type naming (com.warehouse.wes.labor-performance.*) with an analytics stream; MCP exposes 5 read-only tools with guard-railed descriptions (coaching flag is visibility-only).
REST: 11 operations (10 read, 1 write, 1 of 1 writes require Idempotency-Key)
| GET | /healthz | Liveness probe |
| GET | /reports/performance | Labor Performance Report, keyed by TaskType and UTC hour |
| GET | /reports/performance/freshness | How far the read model trails the event stream |
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| POST | /standards | Define (or revise) the engineered labor standard for a TaskType |
| GET | /standards/{taskType} | Get the currently-active labor standard for a TaskType |
| GET | /associates/{associateId}/scorecard | Get one associate's performance scorecard |
| GET | /task-types/{taskType}/performance | Get fleet-wide (all-associates) performance for a TaskType |
| GET | /task-types/{taskType}/utilization | Get fleet-wide idle-gap / utilization for a TaskType over a trailing window |
| GET | /associates/{associateId}/utilization | Get one associate's idle-gap / utilization over a trailing window |
Events published: 3 types on warehouse.labor-performance.analytics, warehouse.labor-performance.events
- performance.TaskPerformanceRecorded
- standard.LaborStandardDefined
- standard.LaborStandardRevised
Events consumed: 1 types from 1 topics
warehouse.fulfillment.events
- task.TaskCompleted fulfillment-execution
MCP tools: 5 (4 read-only)
review_associate_performance | write | Standard operating procedure for reviewing an associate's labor performance (scorecard, trend, coaching flag) against the active standard and fleet-wide task-type performance, using the read tools. |
get_associate_scorecard | read | Return one associate's performance scorecard: task count, mean efficiency percent, a per-task-type breakdown, and a trend/coaching-flag signal computed over their most recent tasks |
get_task_type_performance | read | Return the fleet-wide (all-associates) performance read model for one task type (PICK, PACK, or SLAM): task count, mean efficiency percent, and the real measured mean duration |
get_labor_standard | read | Return the currently-active engineered labor standard (expected seconds) for one task type |
get_task_type_utilization | read | Return idleness/utilization for one task type over a trailing window: measured task time, measured idle time (recorded between-task waits that already ended), and a derived utilization percent |
A2A skills: 2
- Performance scorecard for one associate
- Performance status of a task type
Recommended next steps
- Move idempotency storage behind an application port (or a shared fleet module) instead of SQL in the HTTP adapter, and cap request bodies with http.MaxBytesReader.
- Resolve the previous completion as-of CompletedAt (latest completion before it) so out-of-order TaskCompleted events cannot inflate idle gaps.
- Split cmd/labor/main.go into config/wiring/serve files and replace long positional constructors with option or spec structs.
Measured at origin/develop bc0ad5c (2026-10-30). Review sampled 5 files.
Architecture
Clean code
API design
Mature hexagonal order context with real invariants, transactional idempotency, outbox, DLQs and 32 fitness tests; main debts are an undocumented Idempotency-Key contract and very large files/comments.
Fleet labels it Generic/Supporting: intake is commodity, but fail-closed allocation and capability-based promise are real rules.
- Production code
- 19,337 lines Go in 123 files, 33 packages
- Tests
- 35,963 lines, 759 test functions, 38 integration files, 80 BDD scenarios, 32 fitness tests
- Function size
- avg 13.5 lines (p95 45), 14 over 60 lines
- Complexity
- avg cyclomatic 3.0; highest Order.Status (14), OrderRepo.Save (13)
- Layering
- 0 infrastructure imports in domain/application; 4 domain packages
- Quality gates
- coverage 90%, mutation efficacy 97%, 21 CI jobs
- Persistence
- PostgreSQL, 16 migrations, 17 tables
- Deployables
- a2a, mcp, order, order-projector, order-reports
- Largest files
- internal/application/usecases/allocation.go (757), internal/domain/order/order.go (664), internal/adapters/inbound/kafka/repromise_consumer.go (567)
- Console remote (web/)
- 891 lines TS/TSX, 3 test files
- Decisions
- 47 ADRs, 95 docs pages
- Security scanning
- 1 open code-scanning, 2 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (API, MCP, A2A, projector, reports); Postgres + outbox to Kafka; analytics read model
Strengths
- Order aggregate (internal/domain/order/order.go) owns all line mutations with named invariant errors (BR3 ship-complete, BR6 cancel-before-release, ADR 0044 immutable site); status is derived, never stored.
- Domain is infrastructure-free: facts show no layer violations and no time.Now/uuid/struct tags in internal/domain; outbound needs go through internal/application/ports/ports.go.
- Resilience is built in: transactional outbox, DLQ consumers with shutdown fitness tests (internal/architecture/kafka_dlq_shutdown_fitness_test.go), gobreaker circuit breaker (internal/resilience/breaker.go).
- Release is choreographed via enriched OrderAllocated/OrderPartiallyAllocated events instead of a synchronous call to work-planning (apis/openapi.yaml description, ADR 0005).
Concerns
- Intake is still synchronously coupled to inventory-storage: ReceiveOrder calls ports.InventoryReservationClient (POST /reservations) inside POST /orders (internal/application/usecases/receive_order.go), so allocation latency and outages sit on the intake path.
- Several optional ports fail open when nil (Catalogue, Classification in internal/application/usecases/receive_order.go), so a mis-wired deployment silently skips path validation rather than failing at startup.
- REST endpoints are unauthenticated (fleet decision), and POST /orders mints orders and reserves stock, so any network caller can create demand.
Clean code
Strengths
- Low complexity across 19.3k prod LOC: average cyclomatic 3.0, 0 functions over cyclo 15, p95 function length 45 lines (facts).
- Heavy, layered testing: 759 test funcs, 38 integration-tagged files, 80 BDD scenarios, 32 fitness tests, 90% coverage and 97% mutation-efficacy gates.
- Idempotency middleware (internal/adapters/inbound/http/idempotency.go) is a clear, well-argued single-transaction design that captures, persists, commits, then replies.
Concerns
- Four files exceed 500 lines: internal/application/usecases/allocation.go (757), internal/domain/order/order.go (664), internal/adapters/inbound/kafka/repromise_consumer.go (567), internal/adapters/outbound/kafkacatalog/consumer.go (530).
- Doc comments are essay-length and leak process history, e.g. ReceiveOrder cites 'the task brief's point 2d' (internal/application/usecases/receive_order.go:35); this buries intent and will rot.
- OrderRepo.Save is 89 lines at cyclo 13 (internal/adapters/outbound/postgres/order_repo.go), close to the cyclop cap of 15.
APIs and contracts
- Good: consistent RFC 7807 problem+json with typed URIs, Location on 201, 409 for business-state conflicts, and an intent-level API (POST /orders, retry-allocation, release) instead of exposing saga steps.
- Gap: POST /orders requires an Idempotency-Key header at runtime (internal/adapters/inbound/http/server.go:105) but apis/openapi.yaml never declares the header or its 400/422 problem types.
- Gap: aggregate carries an optimistic-concurrency version but no ETag/If-Match is exposed; there is no order list/search endpoint or pagination; versioning is info.version 2.0.0 only, no path or media-type version.
- Events: AsyncAPI 2.6 documents 2 produced topics with CloudEvents types com.warehouse.wes.order-management.order.*, consumer idempotency on ce id, and explicit assignment_version regimes on payloads.
REST: 11 operations (7 read, 4 write, 0 of 4 writes require Idempotency-Key)
| GET | /healthz | Liveness probe |
| GET | /reports/funnel | Order funnel and allocation health per process path and UTC hour |
| GET | /reports/funnel/freshness | How far the read model trails the event stream |
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| POST | /orders | Receive a new order — allocates and releases automatically |
| GET | /orders/{id} | Read an order's current state |
| DELETE | /orders/{id} | Cancel an order and revoke its reservations |
| POST | /orders/{id}/release | Release an order held at intake |
| POST | /orders/{id}/retry-allocation | Re-attempt allocation for backordered lines, then release |
| GET | /planned-capacity | List a site's planned capacity windows |
Events published: 12 types on warehouse.order-management.analytics, warehouse.order-management.events
- order.OrderAllocated
- order.OrderAllocationPartiallyFailed
- order.OrderCancelled
- order.OrderLineAllocated
- order.OrderLineBackordered
- order.OrderLineReleased
- order.OrderPartiallyAllocated
- order.OrderReceived
- order.OrderReleaseUnconfirmed
- order.OrderReleased
- order.OrderRepromised
- siteskudemand.SiteSkuDemandChanged
Events consumed: 13 types from 5 topics
warehouse.fulfillment.events, warehouse.process-path-management.events, warehouse.product-master.events, warehouse.warehouse-planning.events, warehouse.work-planning.events
- package.PackageManifested fulfillment-execution
- task.TaskCPTMissed fulfillment-execution
- cptschedule.CPTScheduleChanged process-path-management
- processpath.ProcessPathCreated process-path-management
- processpath.ProcessPathDeactivated process-path-management
- processpath.ProcessPathUpdated process-path-management
- capacityplan.BottleneckDetected warehouse-planning
- capacityplan.CapacityPlanCreated warehouse-planning
- capacityplan.CapacityPlanPublished warehouse-planning
- capacityplan.CapacityShortageDetected warehouse-planning
- workpool.PathCapacityChanged wes-work-planning
- workunit.WorkUnitCreated wes-work-planning
- product.ProductClassified product-master
MCP tools: 2 (2 read-only)
get_order | read | Return one order's current state by id: status, allow-partial-shipment flag, promise date, and every line's SKU/quantity/process-path/gift-wrap/status/reservation-id |
get_promise_health | read | Return promise-health KPIs for a time window (and optional process-path filter) from the Order Funnel & Allocation Health data product: promise basis distribution (how many promises were a real capability-derived CPT win |
A2A skills: 2
- How healthy are our delivery promises
- Where does an order stand
Recommended next steps
- Declare the Idempotency-Key header and its problem types on POST /orders in apis/openapi.yaml and add a contract test that fails on spec/handler drift.
- Split internal/application/usecases/allocation.go and order.go by concern (promise, release, cancellation) and trim history from doc comments into ADRs.
- Fail fast at startup when optional ports (catalogue, classification) are expected in production but not wired.
Measured at origin/develop 98d353e (2026-10-30). Review sampled 6 files.
Architecture
Clean code
API design
Well-built configuration context: pure-producer design honouring its no-sibling-calls rule, race-free cross-aggregate checks via ordered row locks, and deep test gates; HTTP adapter and API contract need tidying.
Industry-common catalogue extracted once so no consumer owns it; not a differentiator (subdomain-classification).
- Production code
- 10,253 lines Go in 76 files, 25 packages
- Tests
- 22,639 lines, 522 test functions, 34 integration files, 105 BDD scenarios, 28 fitness tests
- Function size
- avg 12.5 lines (p95 40), 8 over 60 lines
- Complexity
- avg cyclomatic 2.7; highest OutboxRelay.RelayOnce (12), DefineCPTSchedule.lockAndValidateEligiblePathIds (11)
- Layering
- 0 infrastructure imports in domain/application; 3 domain packages
- Quality gates
- coverage 90%, mutation efficacy 99%, 20 CI jobs
- Persistence
- PostgreSQL, 10 migrations, 8 tables
- Deployables
- a2a, mcp, pathmgmt, pathmgmt-projector, pathmgmt-reports
- Largest files
- cmd/pathmgmt/main.go (526), internal/adapters/inbound/http/server.go (503)
- Console remote (web/)
- 968 lines TS/TSX, 3 test files
- Decisions
- 39 ADRs, 86 docs pages
- Security scanning
- 1 open code-scanning, 2 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (pathmgmt API, projector, reports, MCP, A2A); Postgres + outbox to Kafka; producer-only
Strengths
- Pure upstream producer: consumes no topics and calls no sibling over REST/MCP, publishing 4 CloudEvents types on events and analytics streams, consistent with the fleet ban for this context.
- Cross-aggregate invariant (CPT cutoffs reference only Active paths) is enforced in the use case with sorted FOR SHARE locks vs FOR UPDATE on deactivate (usecases/cpt_schedule.go, deactivate_path.go, ADR 0028).
- ProcessPath aggregate validates on Define/Revise, keeps identity and structural fields immutable, and returns 'changed' so no-op revisions raise no event (internal/domain/processpath/process_path.go Revise).
- Deactivation is idempotent end-to-end and never republishes (deactivate_path.go Execute), with Save + Publish bracketed in one unit of work.
Concerns
- Use cases treat UnitOfWork as optional (nil = no transaction) and CPTSchedules as optional (nil disables the reference check) (usecases/deactivate_path.go:35-42, cpt_schedule.go:32-34), so correctness depends on composition-root wiring.
- Rehydrate takes 12 positional parameters and skips all invariant checks (internal/domain/processpath/process_path.go:146), so a corrupt row is loaded silently instead of failing loudly.
- Every CPT schedule PUT re-locks and re-validates all referenced paths inside the transaction (cpt_schedule.go:92-124); fine at catalogue scale but it serialises against deactivations by design.
Clean code
Strengths
- 22.6k test LOC vs 10.3k prod LOC; 522 test funcs, 34 integration-tagged files, 105 godog scenarios across 18 features, 28 fitness tests; coverage 90% and mutation gates at 99%.
- Zero layer-import violations, no clock/uuid/struct tags in the domain, average cyclomatic 2.7, nothing above cyclo 15.
- Use cases read as short, named steps with rationale tied to ADRs (cpt_schedule.go lockAndValidateEligiblePathIds; deactivate_path.go rejectIfReferenced names the referencing sites in its error).
- The only domain panic is a test-only MustIntake helper documented as such (internal/domain/shared/intake.go:68-79).
Concerns
- internal/adapters/inbound/http/server.go is 503 lines mixing routing, 7 handlers, DTO mapping, CORS and JSON helpers; splitting handlers from mapping would ease review.
- cmd/pathmgmt/main.go is 526 lines with run at 113 lines, and cmd/mcp and cmd/pathmgmt-projector run functions are 94-100 lines: wiring is the main complexity hotspot.
- ErrIneligiblePathId is returned without naming the offending path ids (usecases/cpt_schedule.go:120), unlike rejectIfReferenced, so callers cannot tell which cutoff entry is wrong.
APIs and contracts
- Clean resource model: /process-paths CRUD (DELETE = deactivate) and /sites/{siteId}/cpt-schedule as a PUT-replaced singleton; problem+json with 400/404/409/422 and Idempotency-Key on POST (apis/openapi.yaml).
- No If-Match/ETag anywhere in apis/openapi.yaml although aggregates carry versions; PUT /process-paths/{pathId} and the schedule PUT are last-writer-wins from the client's view.
- GET /process-paths returns a bare unpaginated array (openapi.yaml:189-197); acceptable for a small catalogue, but a wrapper object would allow pagination later without a breaking change.
- Events and MCP: 4 CloudEvents types with explicit domain naming; 4 read-only MCP tools and 2 A2A skills, deliberately no write tools for the schedule (ADR 0010). No URL versioning.
REST: 12 operations (8 read, 4 write, 1 of 4 writes require Idempotency-Key)
| GET | /healthz | Liveness probe |
| GET | /reports/catalogue-growth | Process paths defined, revised and deactivated per UTC day |
| GET | /reports/catalogue-growth/freshness | Time since the most recently projected catalogue change |
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| POST | /process-paths | Define a brand-new process path |
| GET | /process-paths | List process paths |
| GET | /process-paths/{pathId} | Get one process path by id |
| PUT | /process-paths/{pathId} | Revise an Active process path's matchPrefix/requiredCapabilities/cycleTimeP95/eligibility/intake |
| DELETE | /process-paths/{pathId} | Deactivate (retire) a process path |
| GET | /sites/{siteId}/cpt-schedule | Get one site's CPT schedule |
| PUT | /sites/{siteId}/cpt-schedule | Define or wholesale-revise a site's CPT schedule |
Events published: 4 types on warehouse.process-path-management.analytics, warehouse.process-path-management.events
- cptschedule.CPTScheduleChanged
- processpath.ProcessPathCreated
- processpath.ProcessPathDeactivated
- processpath.ProcessPathUpdated
MCP tools: 4 (4 read-only)
get_catalogue_growth_report | read | Return the process-path-management 'Process Path Catalogue Growth & Change' report (paths defined/revised/deactivated) for a time window, bucketed by day |
get_process_path | read | Return the full definition of one process path by its canonical id: matchPrefix, direct, requiredCapabilities, cycleTimeP95, eligibility, intake (the demand sources allowed to route work onto it: CUSTOMER_ORDER, STOCK_TR |
list_process_paths | read | List process paths in the catalogue |
get_cpt_schedule | read | Return one site's Critical Pull Time (CPT) schedule: timezone and the recurring daily cutoffs (cptId, localTime, daysOfWeek, shipMethod, eligiblePathIds) |
A2A skills: 2
- List the process-path catalogue
- Look up one process path
Recommended next steps
- Expose the aggregate version as an ETag and require If-Match on PUT/DELETE to give clients lost-update protection.
- Make UnitOfWork and CPTSchedules mandatory constructor dependencies (use in-memory fakes in tests) so atomicity and the reference check cannot be wired off.
- Split internal/adapters/inbound/http/server.go into handlers and mapping files and include offending path ids in ErrIneligiblePathId.
Measured at origin/develop eb0f4fb (2026-10-30). Review sampled 6 files.
Architecture
Clean code
API design
Event-driven advisory service with a tight StationTrip aggregate, ETag/If-Match concurrency and cursor paging; the strongest REST contract sampled, but it ships no runtime metrics.
Cost reduction through less travel; the detour rule is a replaceable policy and the output is advisory.
- Production code
- 13,068 lines Go in 112 files, 34 packages
- Tests
- 20,036 lines, 522 test functions, 21 integration files, 64 BDD scenarios, 33 fitness tests
- Function size
- avg 11.3 lines (p95 27), 1 over 60 lines
- Complexity
- avg cyclomatic 3.0; highest IdempotencyStore (15), Event.Validate (14)
- Layering
- 0 infrastructure imports in domain/application; 4 domain packages
- Quality gates
- coverage 90%, mutation efficacy 90%, 16 CI jobs
- Persistence
- PostgreSQL, 2 migrations, 12 tables
- Deployables
- a2a, api, mcp, ti-projector, ti-reports
- Largest files
- none over 500 lines
- Console remote (web/)
- 1,740 lines TS/TSX, 9 test files
- Decisions
- 9 ADRs, 52 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (API, MCP, A2A, ti-projector, ti-reports); Postgres + outbox; local task/layout copies fed by Kafka
Strengths
- StationTrip aggregate (internal/domain/stationtrip/trip.go) owns all hint invariants (one Active hint, ranked distinct eligible candidates, TTL, forward-only position) and raises events via DomainEvents.
- Purely event-driven: the task pool and facility geometry are local projections of fulfillment and facility-layout topics (inbound/kafka/layout_consumer.go), so recommending never calls a sibling synchronously.
- Consumers run through an inbox (usecases/apply_task_completed.go via Intake.apply) and stale completions are ignored by the aggregate; updates are version-guarded (postgres/station_trip_repository.go:132-143).
- Analytics are separated: a dedicated analytics topic, a projector binary and a reports binary (cmd/ti-projector, cmd/ti-reports) keep reporting load off the operational store.
Concerns
- No application metrics: no otel/metric or Prometheus instruments anywhere in the repo (grep across *.go), so hint issuance, adoption and consumer lag are visible only via traces/logs or the batch reports binary.
- Hint expiry is a 5s polling sweep (internal/adapters/inbound/expiry/worker.go DefaultInterval); claims check ExpiresAt in the aggregate, but reads can report a hint Active briefly after expiry and HintExpired lags by the sweep.
- Endpoints are unauthenticated by fleet decision; PUT /sites/{siteId}/policy changes behaviour for a whole site with no caller identity recorded (internal/adapters/inbound/http/policy_handlers.go).
Clean code
Strengths
- 13k prod LOC with avg 11 lines/function, p95 27, avg cyclomatic 3.0 and no production function above the cap; use cases are one file per command (internal/application/usecases/*.go).
- Heavy, layered testing: 20k test LOC, 522 test funcs, 21 integration-tagged files, 64 BDD scenarios, 33 fitness tests and a shared repository contract suite run against memory and Postgres.
- Domain code is readable and precise (e.g. rankedBefore using cmp.Or in stationtrip/trip.go), and handlers map missing fields to the domain's own errors (policy_handlers.go requiredSettings).
Concerns
- The test-side repository contract helper IdempotencyStore in internal/testing/repocontract/small.go hits cyclomatic 15, the highest in the repo; test helpers are drifting towards the cap.
- Hint TTL upper bound is checked in the HTTP adapter (maxHintTTLSeconds in internal/adapters/inbound/http/policy_handlers.go:48) rather than in the policy package that otherwise owns the ranges.
APIs and contracts
- Good: PUT /sites/{siteId}/policy uses strong ETag + If-Match with 412 version-mismatch (apis/openapi.yaml lines 27, 73-75), true optimistic concurrency exposed to clients.
- Good: GET /hints uses opaque cursor pagination with bounded limit (1-500); problem+json types are absolute URIs with worked examples; Idempotency-Key reuse with a different body is rejected.
- Missing: no URL/media-type versioning despite info.version 1.0.0; POST /recommendations is a simulation endpoint (RPC-style) rather than a resource.
- Events: CloudEvents with versioned dataschema URNs, station id as key/subject; integration vs analytics topics split. Event payloads are snake_case (policy_version) while REST is camelCase.
REST: 10 operations (8 read, 2 write, 1 of 2 writes require Idempotency-Key)
| PUT | /sites/{siteId}/policy | Declare or replace a site's interleaving policy |
| GET | /sites/{siteId}/policy | Get a site's interleaving policy |
| GET | /hints | List interleaving hints |
| GET | /hints/{hintId} | Get an interleaving hint |
| GET | /stations/{stationId} | Get a station's position and active hint |
| POST | /recommendations | Simulate the recommender for a station |
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| GET | /reports/hint-adoption | How much of the issued advice operators take, per day |
| GET | /reports/freshness | How far the analytics projection is behind |
Events published: 4 types on warehouse.task-interleaving.analytics, warehouse.task-interleaving.events
- policy.InterleavingPolicyDeclared
- stationtrip.InterleavingHintConsumed
- stationtrip.InterleavingHintExpired
- stationtrip.InterleavingHintIssued
Events consumed: 7 types from 2 topics
warehouse.facility.events, warehouse.fulfillment.events
- task.TaskAvailable fulfillment-execution
- task.TaskClaimed fulfillment-execution
- task.TaskCompleted fulfillment-execution
- locationslot.LocationGeometryUpdated facility-layout
- locationslot.LocationSlotDecommissioned facility-layout
- locationslot.LocationSlotRegistered facility-layout
- zone.ZoneRegistered facility-layout
MCP tools: 4 (4 read-only)
get_site_policy | read | Read the interleaving policy a site declared: maxDetourM (the farthest a candidate may lie from the station), maxCandidates (1..5), hintTtlSeconds, eligibleTaskTypes, verticalWeight, version and declaredAt |
list_hints | read | List interleaving hints newest first, a page at a time, optionally only those issued to one station (stationId), of one site (siteId) and/or in one state (Active, Consumed, Expired or Superseded) |
get_hint | read | Read one interleaving hint by id: stationId, siteId, state (Active, Consumed, Expired or Superseded), the task it follows (afterTaskId) and the origin location, issuedAt and expiresAt, the policyVersion it was ranked und |
get_station | read | Read what the service knows about a station: its site, its position (location code and the point in metres when the geometry is known), the last task it completed and when, and its active hint if it holds one (the short |
A2A skills: 2
- Interleaving hint status of a station
- Interleaving overview of a site
Recommended next steps
- Add OTel metrics for hints issued/consumed/expired, recommender latency and consumer lag, and wire them into the chart.
- Move the hint TTL ceiling into internal/domain/policy so all inbound adapters (REST, MCP, A2A) share it.
- Decide on a REST versioning scheme (path or media type) now that the contract is declared 1.0.0.
Measured at origin/develop e95fce9 (2026-10-30). Review sampled 8 files.
Architecture
Clean code
API design
The fleet's largest and most heavily tested context (103 BDD scenarios, 99% mutation gate, 46 ADRs), but its contracts break HTTP semantics: side-effecting GETs, and most writes, including release, lack Idempotency-Key.
Built in-house: release policy, WIP limit and flow balancing are the operational differentiator of the WES tier.
- Production code
- 19,736 lines Go in 165 files, 40 packages
- Tests
- 35,468 lines, 859 test functions, 44 integration files, 103 BDD scenarios, 27 fitness tests
- Function size
- avg 11.7 lines (p95 34), 7 over 60 lines
- Complexity
- avg cyclomatic 2.8; highest EnqueueWorkUnit.applyPackAware (15), Publisher.workReleasedData (14)
- Layering
- 0 infrastructure imports in domain/application; 12 domain packages
- Quality gates
- coverage 90%, mutation efficacy 99%, 21 CI jobs
- Persistence
- PostgreSQL, 17 migrations, 17 tables
- Deployables
- a2a, mcp, wes, wes-projector, wes-reports
- Largest files
- internal/adapters/inbound/kafka/consumer.go (781), internal/adapters/inbound/http/handlers.go (689), internal/adapters/outbound/kafka/publisher.go (589)
- Console remote (web/)
- 1,695 lines TS/TSX, 3 test files
- Decisions
- 46 ADRs, 120 docs pages
- Security scanning
- 1 open code-scanning, 2 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (wes API+consumers, MCP, A2A, analytics projector, reports); Postgres + outbox to Kafka; 12 domain pkgs
Strengths
- WorkPool and WorkUnit aggregates own release policy (earliest CPT, WIP limit, feed modes); ReleaseNextWork retries on pool version conflicts so stale pools never overwrite newer ones (usecases/release_next_work.go)
- The one sync dependency (facility-layout travel distance) has a 5s timeout, a gobreaker circuit breaker with metrics, and a permissive fallback mode (adapters/outbound/traveldistance/, internal/resilience/breaker.go)
- Event-driven integration: upstream facts (product classification, pack levels, inventory, slot plans, replenishment) land in local copies, not sync calls; analytics has its own projector/reports (apis/asyncapi.yaml)
- Zero layer violations and 27 fitness tests per facts; 17 migrations show the schema evolving under versioned control
Concerns
- Reads publish events: SampleBacklog raises BacklogThresholdBreached on every call over threshold (usecases/sample_backlog.go:91-104) behind GET /paths/{pathId}/telemetry; GET /rebalance does the same, so polling dashboards create event storms
- Atomicity is opt-in: use cases take WithUnitOfWork and 'nil keeps the calls running back to back' (usecases/release_next_work.go:45-50), so a composition-root wiring slip silently drops the save+publish guarantee
- Outbound publisher reads the WorkUnit repository to enrich WorkReleased (internal/adapters/outbound/kafka/publisher.go:333), so the event payload depends on read ordering inside the tx, not on the domain event
Clean code
Strengths
- Best test suite in the fleet sample: 35.5k test LOC vs 19.7k prod, 103 BDD scenarios in 14 features, 44 integration-tagged files, a contract job, 99% mutation efficacy/coverage gates (facts)
- Function-level complexity stays low (avg 11.7 lines, cyclo 2.8, none over 15), and comments record why defensive code exists, e.g. MaxWIPLimit found by Schemathesis (internal/domain/release/work_pool.go:5-10)
- 46 ADRs and 120 doc pages; code comments cite ADR numbers for each behaviour (e.g. ADR-0014 atomic scope, ADR-0018 capacity reporting in usecases/sample_backlog.go)
Concerns
- Three adapter files exceed 500 lines: inbound/kafka/consumer.go (781), inbound/http/handlers.go (689), outbound/kafka/publisher.go (589); Publisher.workReleasedData alone is 99 lines at cyclo 14 (facts)
- Release path carries data-repair logic for lost updates from 'before this pool was versioned' (usecases/release_next_work.go:75-78,111-135); legacy healing in the hot path should be a one-off migration
- Go toolchain 1.26.10 while the other Go repos sampled are on 1.27.3 (go.mod), so fleet tooling and vuln baselines diverge
APIs and contracts
- Only POST /paths/{pathId}/work-units, itself deprecated, requires Idempotency-Key (internal/adapters/inbound/http/router.go:45-66); POST /release is unkeyed, so a client retry after a lost response releases a second unit
- GET /paths/{pathId}/telemetry and /rebalance are unsafe: they publish BacklogThresholdBreached, PathThrottled or LaborReassignmentFlagged (http/handlers.go:553,584); MCP marks them destructive (mcp/tools.go:119-129), REST does not
- Resource modelling is mixed: verb sub-paths (/charge, /plan, /release, /complete) next to PUT /pool and GET /work-units?reference; two endpoints are deprecated with no Sunset header (apis/openapi.yaml:389,923)
- Good: problem+json with detailed slugs, separate versioned reports spec (apis/openapi-reports.yaml), 11 events + analytics twins with typed names; but AsyncAPI is 2.6.0 and topics use warehouse.* (apis/asyncapi.yaml)
REST: 17 operations (11 read, 6 write, 1 of 6 writes require Idempotency-Key)
| GET | /healthz | Liveness probe |
| GET | /reports/throughput | Release throughput and backlog health per process path and UTC hour |
| GET | /reports/throughput/freshness | How far the read model trails the event stream |
| GET | /healthz | Health check |
| GET | /readyz | Readiness check |
| POST | /paths/{pathId}/charge | Receive a charge forecast for a process path |
| POST | /paths/{pathId}/plan | Commit this service's shift plan for a process path |
| POST | /paths/{pathId}/work-units | Enqueue a work unit onto a process path's work pool |
| POST | /paths/{pathId}/release | Release the next highest-priority work unit on a process path |
| PUT | /paths/{pathId}/pool | Configure a process path's work pool (feed mode and WIP limit) |
| GET | /paths/{pathId}/telemetry | Sample live backlog telemetry for a process path |
| GET | /paths/{pathId}/rebalance | Get the flow-balancing recommendation for a process path |
| GET | /paths/{pathId}/labor-plan-view | Get the latest labor plan Workforce Management reported for a path |
| GET | /work-units | Look up work units by their external order-line reference |
| GET | /work-units/{id} | Get one work unit by its own identity |
| POST | /work-units/{id}/complete | Record completion of a released work unit |
| GET | /inventory-view/{sku} | Get the latest observed usable inventory for a SKU |
Events published: 11 types on warehouse.wes.analytics, warehouse.work-planning.events
- charge.ChargeForecastReceived
- pathplan.PathPlanDriftDetected
- plan.ShiftPlanCommitted
- workpool.BacklogThresholdBreached
- workpool.LaborReassignmentFlagged
- workpool.PathCapacityChanged
- workpool.PathThrottled
- workpool.RateDeviationDetected
- workunit.WorkReleased
- workunit.WorkUnitCompleted
- workunit.WorkUnitCreated
Events consumed: 17 types from 5 topics
warehouse.inventory.events, warehouse.network-inventory-planning.events, warehouse.pick-face-replenishment.events, warehouse.product-master.events, warehouse.slotting-optimization.events
- task.TaskCompleted fulfillment-execution
- workdemand.WorkDemandReleased network-inventory-planning
- order.OrderAllocated order-management
- order.OrderPartiallyAllocated order-management
- processpath.ProcessPathCreated process-path-management
- processpath.ProcessPathDeactivated process-path-management
- processpath.ProcessPathUpdated process-path-management
- shiftplan.ShiftPlanCommitted workforce-management
- reservation.ReservationRevoked inventory-storage
- reservation.StockReserved inventory-storage
- replenishment.ReplenishmentCancelled pick-face-replenishment
- replenishment.ReplenishmentRequested pick-face-replenishment
- product.ProductClassified product-master
- product.ProductPackLevelDeclared product-master
- product.ProductPackLevelMeasured product-master
- product.ProductPackLevelRetired product-master
- slotplan.SlotPlanApproved slotting-optimization
MCP tools: 5 (1 read-only)
balance_flow | write | Standard operating procedure for balancing flow on a process path: read telemetry, decide when to throttle, release, or reassign, and know when to escalate. |
get_release_throughput_report | read | Return the Release Throughput & Backlog Health report (work released, work units completed, backlog-threshold breaches, path throttles, rate-deviation detections) per process path and hour, for a time window, optionally |
get_backlog_telemetry | write | Return the live backlog read model for a process path: pending backlog depth, released WIP, feed mode (ReleaseFed or FlowFed), and whether it is over its alarm threshold |
get_rebalance_recommendation | write | Return the Drum-Buffer-Rope flow-balancing recommendation for a process path: NoActionNeeded, ThrottleUpstream (a flow-fed path over its alarm threshold), or ReassignLabor (a release-fed path saturated at its WIP limit w |
release_next_work | write | Release the next highest-priority (earliest-CPT) pending work unit into a process path's pool, per the release policy |
A2A skills: 2
- Flow status for a process path
- Release the next work unit
Recommended next steps
- Make GET /telemetry and /rebalance pure reads; move threshold/throttle event emission to a scheduled evaluator that publishes on state change only
- Require Idempotency-Key on every write, at least POST /release, /complete and PUT /pool, using the existing middleware
- Make UnitOfWork mandatory in constructors and split consumer.go, handlers.go and publisher.go by event or route family
Measured at origin/develop 68fe325 (2026-10-30). Review sampled 9 files.
Architecture
Clean code
API design
Most tested and documented context (40 ADRs, 102 BDD scenarios, 99% mutation gate); the 2026-11-01 REST cutover and file split fixed verb routes, unkeyed POSTs and 500-line files. Nil-optional wiring remains.
Allocating workforce to workload is necessary and industry-common, not a differentiator.
- Production code
- 13,712 lines Go in 106 files, 34 packages
- Tests
- 25,323 lines, 615 test functions, 23 integration files, 102 BDD scenarios, 27 fitness tests
- Function size
- avg 13.0 lines (p95 39), 8 over 60 lines
- Complexity
- avg cyclomatic 2.8; highest Deps.staffingStatus (14), AssignLabor.Execute (12)
- Layering
- 0 infrastructure imports in domain/application; 5 domain packages
- Quality gates
- coverage 90%, mutation efficacy 99%, 22 CI jobs
- Persistence
- PostgreSQL, 6 migrations, 12 tables
- Deployables
- a2a, mcp, workforce, workforce-projector, workforce-reports
- Largest files
- none over 500 lines
- Console remote (web/)
- 1,129 lines TS/TSX, 3 test files
- Decisions
- 40 ADRs, 106 docs pages
- Security scanning
- 1 open code-scanning, 2 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (workforce API, MCP, A2A, projector, reports); Postgres + outbox; 2 sync clients behind gobreaker
Strengths
- labor-performance and fulfillment-execution calls sit behind per-dependency gobreaker breakers with state gauges (outbound/laborperformance/breaker.go; wiring in cmd/workforce/main_clients.go).
- Fail-open vs fail-loud is a deliberate, documented choice per dependency: measured-rate reads fail open, installed-capacity (gates a commit) never blind-retries and fails loud (cmd/workforce/main_clients.go:115-131).
- Use cases save both aggregates and publish via the outbox inside one UnitOfWork (internal/application/usecases/assign_labor.go:104-114); the idempotency middleware's transaction is joined by the use case.
- Analytics split into a projector and a reports binary with its own spec (apis/openapi-reports.yaml) and freshness endpoint.
Concerns
- Use cases still treat UnitOfWork, Catalogue and Metrics as optional with nil meaning non-atomic or unvalidated behaviour (internal/application/usecases/assign_labor.go:34-45); a wiring slip silently drops atomicity or path validation.
- The certification invariant lives outside the aggregate: LaborAssignment.Assign trusts a caller-computed hasCertification bool (internal/domain/assignment/labor_assignment.go:106-107).
- Two synchronous REST dependencies remain on the planning path (labor-performance, fulfillment-execution); in the default permissive mode every CommitShiftPlan fails until INSTALLED_CAPACITY_MODE=http is set (cmd/workforce/main_clients.go:115-131).
Clean code
Strengths
- Strongest test estate sampled: 25.3k test LOC vs 13.7k prod, 615 test funcs, 102 BDD scenarios, 22 integration-tagged files, 27 fitness tests, 99% mutation efficacy/coverage, plus CodeQL, Trivy and contract jobs.
- File-length budget (300 code lines per prod Go file, CI job) enforced; move-only split cut cmd/workforce/main.go 622->281 and router.go 546->194; largest file now 489 (inbound/kafka/analytics_consumer.go).
- Code comments trace decisions to ADRs (40 ADRs), e.g. the certification-family resolution in usecases/assign_labor.go:19-27. Average cyclomatic complexity stays low (2.8), no function above 15.
Concerns
- Size drift in functions: 8 functions over 60 lines (cmd/workforce/main.go run at 97, inbound/http/idempotency.go runFreshRequest at 85, cmd/mcp/main.go run at 75) and p95 of 39 lines, the highest sampled.
- No file exceeds 500 lines any more, but laborperformancecache/consumer.go (470), kafkacatalog/consumer.go (405) and cmd/a2a/main.go (381) remain above the 300-line budget and rely on the ratchet.
- Long explanatory comments on struct fields describing test-only nil behaviour (usecases/assign_labor.go:35-45) signal configuration paths kept alive for old tests.
APIs and contracts
- Good: ADR 0040 REST guideline cutover (2026-11-01): all 8 POSTs require Idempotency-Key (409 on reuse); noun routes (shift-starts, break-starts, plan-proposals) replace verb paths (apis/openapi.yaml).
- Good: RFC 9457 problems; keyset paging (limit 1-500, opaque cursor) on the labor report; /buildings/{buildingId}/... staffing-gap and the buildingId alias are deprecated: true with siteCode replacement (ADR 0035).
- Missing: no ETag/If-Match on any operation (not evidenced in apis/openapi.yaml), and no URL versioning despite 1.0.0 after a breaking cutover.
- Events: 1 integration event (ShiftPlanCommitted) and 10 analytics types; MCP exposes assign_labor as a write tool alongside read-only gap/report tools; A2A has 2 skills.
REST: 16 operations (8 read, 8 write, 8 of 8 writes require Idempotency-Key)
| GET | /healthz | Liveness probe |
| GET | /reports/labor | Labor utilization and staffing per process path and UTC hour |
| GET | /reports/labor/freshness | How far the read model trails the event stream |
| GET | /healthz | Liveness check |
| GET | /readyz | Readiness check |
| POST | /associates/{id}/shift-starts | Start an associate's shift |
| POST | /associates/{id}/certifications | Add a certification to an associate |
| POST | /paths/{pathId}/plan-proposals | Propose planned heads for a path (pure computation, not committed) |
| POST | /shift-plans | Commit a shift's headcount split across paths |
| POST | /associates/{id}/assignments | Assign an associate to a path |
| POST | /associates/{id}/break-starts | Start a logged break for an associate |
| POST | /associates/{id}/break-ends | End a logged break for an associate |
| GET | /paths/{pathId}/staffing-gap | Get the staffing gap for a path within a committed shift plan |
| GET | /sites/{siteCode}/shifts/{shiftId}/staffing-gap | List the staffing gap for every path planned within one committed shift plan of a site (canonical route) |
| GET | /buildings/{buildingId}/shifts/{shiftId}/staffing-gap | DEPRECATED -- use GET /sites/{siteCode}/shifts/{shiftId}/staffing-gap. List the staffing gap for every path planned within one committed shift plan (fleet-wide, all-paths view) |
| POST | /associates/{id}/shift-ends | End an associate's shift |
Events published: 10 types on warehouse.workforce.analytics, warehouse.workforce.events
- assignment.LaborAssigned
- assignment.LaborReassigned
- associate.AssociateBreakEnded
- associate.AssociateBreakStarted
- associate.AssociateCertified
- associate.AssociateShiftEnded
- associate.AssociateShiftStarted
- shiftplan.PathUnderstaffed
- shiftplan.ShiftPlanCommitted
- shiftplan.ShiftPlanProposed
Events consumed: 4 types from 2 topics
warehouse.labor-performance.events, warehouse.process-path-management.events
- performance.TaskPerformanceRecorded labor-performance
- processpath.ProcessPathCreated process-path-management
- processpath.ProcessPathDeactivated process-path-management
- processpath.ProcessPathUpdated process-path-management
MCP tools: 5 (3 read-only)
cover_staffing_gaps | write | Standard operating procedure for reading staffing gaps and covering understaffed paths with certified, available associates. |
get_workforce_labor_report | read | Return the workforce Labor Utilization & Staffing report (shifts started/ended, break count and avg break seconds, certifications, labor assigned/reassigned, understaffing events) for a time window, optionally filtered b |
get_staffing_gap | read | Return planned vs active heads for a process path within a site's committed shift plan, and whether it is understaffed |
propose_path_heads | read | Compute the headcount needed to cover a path's charge at a planned rate (ceil(charge/rate)) for a site (siteCode; buildingId is deprecated in favour of siteCode and is an alias with the same value) |
assign_labor | write | Assign an associate to a process path, ending their prior active assignment if any |
A2A skills: 2
- Assign an associate to a process path
- Staffing status for a process path
Recommended next steps
- Make UnitOfWork and Catalogue mandatory constructor dependencies and delete the nil-tolerant branches kept for older tests.
- Move the certification check into the LaborAssignment aggregate so Assign cannot be called with a caller-computed bool.
- Add ETag/If-Match to shift and assignment resources, and split the remaining 400+ line consumers and 75-97 line run() functions under the file/function budgets.
Measured at origin/develop f8cb438 (2026-11-02). Review sampled 7 files.
Retail Network 12 applications
Architecture
Clean code
API design
A deeply reasoned anti-corruption layer with best-in-fleet resilience (breaker, jittered retries, outbox, resumable polling) and very thorough tests; the gap is last-writer-wins persistence on a multi-writer aggregate.
Revenue-channel enabler: the ACL and 24h answer protocol are custom, but the capability knowledge it uses is owned by other contexts.
- Production code
- 19,782 lines Go in 123 files, 36 packages
- Tests
- 37,181 lines, 876 test functions, 34 integration files, 96 BDD scenarios, 35 fitness tests
- Function size
- avg 13.8 lines (p95 38), 10 over 60 lines
- Complexity
- avg cyclomatic 3.3; highest LiveGateway.SubmitInventoryFeed (14), planInventoryFeeds (14)
- Layering
- 0 infrastructure imports in domain/application; 3 domain packages
- Quality gates
- coverage 90%, mutation efficacy 99%, 18 CI jobs
- Persistence
- PostgreSQL, 12 migrations, 22 tables
- Deployables
- a2a, mcp, netfulfil, netfulfil-projector, netfulfil-reports
- Largest files
- internal/adapters/outbound/retailnetwork/gateway_live.go (604)
- Console remote (web/)
- 463 lines TS/TSX, 2 test files
- Decisions
- 31 ADRs, 59 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal ACL context; 5 binaries (netfulfil API+poller, projector, reports, MCP, A2A); Postgres + outbox; polls retail-network
Strengths
- ReceiveNetworkDemand documents a 6-step translate/record/hold/record/answer/commit sequence and resumes NEW orders on redelivery instead of re-answering (usecases/receive_network_demand.go:21-116).
- Network client wraps every call in a timeout, jittered exponential backoff (5 attempts, 2s cap), rate-limit handling and a gobreaker circuit breaker (adapters/outbound/retailnetwork/client.go).
- Feasibility is asked of order-management, never computed locally (ADR 0001 §7), keeping promise math in one place; holds are recorded before any decision depends on them (ADR 0024).
- Outbox relay uses FOR UPDATE SKIP LOCKED so rolling deploys can run two relays safely (adapters/outbound/postgres/outbox_relay.go:168).
Concerns
- NetworkOrder save is an unconditional upsert of state with no version check (adapters/outbound/postgres/network_order_repo.go:67-78), while the poller, deadline sweep and reconcile use cases all write the same order: last writer wins.
- Many outbound integrations (17 outbound adapter packages incl. ordermanagement, inventoryclient, productmaster, fleetrest) make this context sensitive to several sibling contracts at once.
- The single write route (POST /network-orders/{networkRef}/shipment-confirmation) is unauthenticated by fleet decision and triggers an external submission to the network.
Clean code
Strengths
- Exceptional test depth: 37k test LOC vs 19.8k prod, 876 test funcs, 96 BDD scenarios in 13 features, 34 integration files, 35 fitness tests, 99% mutation efficacy gate.
- Comments explain why, not what (e.g. the idempotency rationale in receive_network_demand.go:69-84 and immutable-line upsert in network_order_repo.go:85-90); 31 ADRs back the decisions.
- One struct per use case with explicit port fields (ReceiveNetworkDemand, ConfirmNetworkOrderShipment, SweepOrphanedHolds) and no function over cyclomatic 15.
Concerns
- Longer functions than siblings: 10 over 60 lines, p95 38; cmd/netfulfil/main.go run is 107 lines and cmd/mcp/main.go run 84.
- internal/adapters/outbound/retailnetwork/gateway_live.go is 604 lines; README.md is 670 lines (42 KB), hard to keep current.
- Web remote is minimal (web/, 463 LOC, 2 test files, no e2e).
APIs and contracts
- REST is deliberately read-mostly (ADR 0001 §5: demand arrives by polling); problem+json errors with typed slugs such as network-order-not-found (apis/openapi.yaml:315).
- Shipment confirmation is idempotent by state (already CONFIRMED returns 204) rather than by Idempotency-Key, so two concurrent first calls can both submit to the network.
- GET /network-orders and /capability-offers return full lists with no pagination; spec omits URI/media-type versioning.
- apis/asyncapi.yaml is AsyncAPI 2.6.0; analytics events carry an 'Analytics' suffix (NetworkOrderReceivedAnalytics) duplicating 7 integration types instead of reusing type names per topic.
REST: 10 operations (9 read, 1 write, 0 of 1 writes require Idempotency-Key)
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
| GET | /metrics | Prometheus metrics |
| GET | /inbound-status | Is the inbound polling leg alive? |
| GET | /network-orders | List orders still awaiting an answer |
| GET | /network-orders/{networkRef} | Get one network order |
| POST | /network-orders/{networkRef}/shipment-confirmation | Confirm shipment of one network order |
| GET | /capability-offers | List every currently-advertised capability offer |
| GET | /reports/acknowledgement | Network Order Acknowledgement & Translation report |
| GET | /reports/acknowledgement/freshness | How far the report lags real time |
Events published: 7 types on warehouse.network-fulfillment.analytics, warehouse.network-fulfillment.events
- networkorder.AcknowledgementDeadlineAtRisk
- networkorder.NetworkOrderAcknowledged
- networkorder.NetworkOrderReceived
- networkorder.NetworkOrderRejected
- networkorder.NetworkOrderShipmentConfirmed
- networkorder.NetworkOrderSubmitted
- networkorder.OrphanedHoldCancelled
Events consumed: 8 types from 3 topics
warehouse.inbound-receiving.events, warehouse.process-path-management.events, warehouse.work-planning.events
- cptschedule.CPTScheduleChanged process-path-management
- processpath.ProcessPathCreated process-path-management
- processpath.ProcessPathDeactivated process-path-management
- processpath.ProcessPathUpdated process-path-management
- workpool.PathCapacityChanged wes-work-planning
- receipt.CartonDiscrepancyRaised inbound-receiving
- receipt.ReceiptCartonReceived inbound-receiving
- receipt.ReceiptClosed inbound-receiving
MCP tools: 5 (4 read-only)
answer_network_demand | write | Standard operating procedure for inspecting network demand and this context's answers to it — one order, the unanswered/answered working sets, or a day-bucketed acknowledgement trend — using the read tools. |
get_acknowledgement_report | read | Return the network-fulfillment 'Network Order Acknowledgement & Translation' report for a time window, bucketed by day: orders received, orders acknowledged, orders rejected (split by untranslatable-SKU catalogue gap vs |
get_network_order | read | Get one network order by its network reference (the external network's own purchase-order number, e.g |
list_network_orders | read | List network orders, optionally filtered by state (NEW, SUBMITTED, ACKNOWLEDGED, REJECTED, or CONFIRMED) |
list_capability_offers | read | List every currently-advertised CapabilityOffer (ADR 0001 §8): the throughput-constrained advertised quantity this context would tell the network it can ship, per SKU and site, and whether that figure is limited by physi |
A2A skills: 2
- Availability this context advertises to the network
- Where the network's demand stands
Recommended next steps
- Add an aggregate version column and conditional UPDATE to network_orders, retrying on conflict in the poller and sweeps.
- Require Idempotency-Key (or a row lock) on shipment-confirmation before calling the external network.
- Paginate /network-orders and /capability-offers, and split gateway_live.go by network operation.
Measured at origin/develop c2508dc (2026-10-30). Review sampled 6 files.
Architecture
Clean code
API design
Most complex saga in the sample: a well-documented transfer state machine driven by events, fail-closed approval and idempotent replies; weaker mutation gate and some large files temper an otherwise strong design.
The only place stock at one site is weighed against demand and capacity at another; classified Core in the DDD docs.
- Production code
- 14,254 lines Go in 92 files, 24 packages
- Tests
- 22,321 lines, 477 test functions, 18 integration files, 128 BDD scenarios, 24 fitness tests
- Function size
- avg 13.6 lines (p95 40), 10 over 60 lines
- Complexity
- avg cyclomatic 3.1; highest ProposalInput.validate (15), SnapshotRepo.Load (13)
- Layering
- 0 infrastructure imports in domain/application; 3 domain packages
- Quality gates
- coverage 90%, mutation efficacy 83%, 18 CI jobs
- Persistence
- PostgreSQL, 8 migrations, 15 tables
- Deployables
- a2a, mcp, network-inventory-planning, nip-projector, nip-reports
- Largest files
- cmd/network-inventory-planning/main.go (737), internal/domain/transfer/saga.go (600)
- Console remote (web/)
- 3,766 lines TS/TSX, 12 test files
- Decisions
- 20 ADRs, 67 docs pages
- Security scanning
- 1 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 5 binaries (API+saga consumers, projector, reports, MCP, A2A); event-choreographed transfer saga, Postgres outbox
Strengths
- InterWarehouseTransfer is an explicit saga state machine (DRAFT..RECEIVED/UNFULFILLABLE/CANCELLED) with typed IllegalTransitionError and closed rejection vocabulary (internal/domain/transfer/saga.go).
- Approval is fail-closed: stale or missing read-model facts refuse with 422, unusable models 503, and approve + allocation request + audit events commit in one UoW via the outbox (usecases/approve_transfer.go).
- Reply handling separates deterministic failures (skip) from poison payloads (dead-letter to <topic>.dlq and commit past), avoiding partition wedging (approve_transfer.go IsDeterministic/IsRefusedReply, ADR 0013).
- Integration is fully asynchronous: 18 CloudEvents types across inventory, fulfillment, planning, facility, order-management and product-master; TransferStuckDetected surfaces sagas that stop advancing.
Concerns
- No compensation once stock is ALLOCATED: CANCELLED is only legal before allocation and revocation is deferred to a later phase (internal/domain/transfer/saga.go:19-24), so post-allocation failures need manual handling.
- Approval validates against the read-model snapshot before opening the UoW (approve_transfer.go:95-121), and the ApprovalEvents publisher is optional on reply use cases (approve_transfer.go:257-260, nil skips analytics).
- The domain carries wire-format JSON tags on CaseRounding (internal/domain/transfer/casemultiple.go:45-53), the only struct-tag leak flagged in the sampled repos.
Clean code
Strengths
- 22.3k test LOC vs 14.3k prod LOC; 477 test funcs, 18 integration-tagged files, 128 godog scenarios (most in this sample), 24 fitness tests, coverage gate 90%.
- Zero layer-import violations and no time.Now/uuid in the domain; the clock is injected (approve_transfer.go Now func) and errors are wrapped with sentinel classification for HTTP mapping.
- Error-to-status mapping is documented at the use-case boundary (approve_transfer.go Execute doc: 422/503/409/200 replay).
Concerns
- Mutation gates are 83% efficacy / 88% coverage, well below the 95-99% used by sibling repos (.github CI gates per facts), so the saga has the weakest mutation protection where it matters most.
- Two files exceed 500 lines: cmd/network-inventory-planning/main.go (737, wireSagas 101 lines) and internal/domain/transfer/saga.go (599); ProposalInput.validate sits at cyclo 15, on the cap.
- Use cases exceed 80 lines (ApproveTransfer.Execute 80 lines/cyclo 13, RunScheduledRebalance.Execute 85 lines in usecases/scheduled_rebalance.go), and transfer IDs are minted with uuid inside the use case rather than via an ID port.
APIs and contracts
- Only repo in this sample with path versioning (/v1/...); approve is POST /v1/transfers:approve with a required Idempotency-Key, 409 on key reuse with a different payload and 200 replay (apis/openapi.yaml:109-119).
- Catalogues use strong ETags with If-Match and 412 (openapi.yaml:215, 581-595), but If-Match is optional and PUT targets the collection (/v1/rebalance-policies) with the id in the body rather than /{id}.
- Errors are RFC 7807 problem+json throughout, with explicit 503 for unusable read models; list endpoints are paged.
- Events documented in AsyncAPI 3.0 with dataschema; MCP offers 4 read tools (get/list/find_stuck/simulate) and no write tools, so agents cannot approve transfers.
REST: 16 operations (12 read, 4 write, 1 of 4 writes require Idempotency-Key)
| GET | /healthz | Liveness probe. |
| POST | /v1/transfer-proposals:generate | Generate advisory transfer proposals from an explicit snapshot. |
| GET | /v1/transfer-simulations | Simulate advisory transfer options from local read models. |
| POST | /v1/transfers:approve | Approve a transfer proposal and start the allocation saga. |
| GET | /v1/rebalance-runs | List scheduled rebalance runs, newest first. |
| GET | /v1/rebalance-policies | List the Rebalance Policy catalogue. |
| PUT | /v1/rebalance-policies | Create or revise one Rebalance Policy (idempotent). |
| GET | /v1/transfer-lanes | List the Transfer Lane catalogue. |
| PUT | /v1/transfer-lanes | Create or revise one Transfer Lane (idempotent). |
| GET | /v1/transfers | List transfers, newest first. |
| GET | /v1/transfers/{id} | Get one transfer with its audit trail. |
| GET | /reports/transfer-funnel | How many distinct transfers reached each saga state, per day |
| GET | /reports/state-dwell | Saga age percentiles at the moment of leaving each state, per day |
| GET | /reports/stuck-transfers | TransferStuckDetected occurrences per state per day, plus the latest ones |
| GET | /reports/rebalance-runs | Scheduled rebalance runs, proposals against rejected, per day |
| GET | /reports/freshness | How far the analytics projection is behind |
Events published: 6 types on warehouse.network-inventory-planning.analytics, warehouse.network-inventory-planning.events
- saga.RebalanceRunCompleted
- saga.TransferStateAdvanced
- saga.TransferStuckDetected
- transfer.TransferAllocationRequested
- transfer.TransferPlanApproved
- workdemand.WorkDemandReleased
Events consumed: 12 types from 6 topics
warehouse.facility.events, warehouse.fulfillment.events, warehouse.inventory.events, warehouse.order-management.events, warehouse.product-master.events, warehouse.warehouse-planning.events
- transfer.TransferArrived fulfillment-execution
- transfer.TransferDispatched fulfillment-execution
- transfer.TransferPicked fulfillment-execution
- siteskudemand.SiteSkuDemandChanged order-management
- capacityplan.CapacityPlanPublished warehouse-planning
- site.SiteCapabilityChanged facility-layout
- reservation.TransferStockAllocated inventory-storage
- reservation.TransferStockAllocationRejected inventory-storage
- stock.TransferReceiptStaged inventory-storage
- stock.TransferStockStowed inventory-storage
- product.ProductPackLevelDeclared product-master
- product.ProductPackLevelRetired product-master
MCP tools: 4 (4 read-only)
get_transfer | read | Read one inter-warehouse transfer by id: its current state (DRAFT, PROPOSED, APPROVED, ALLOCATING, ALLOCATED, PICKED, IN_TRANSIT, ARRIVED, RECEIVED, UNFULFILLABLE or CANCELLED), sku, quantity, picked quantity, origin and |
list_transfers | read | Page through inter-warehouse transfers, newest first, optionally filtered by state and by a site (origin or destination) |
find_stuck_transfers | read | Find transfers that are not advancing: those in a NON-terminal state (RECEIVED, UNFULFILLABLE and CANCELLED are finished and never reported) whose state has been unchanged for longer than older_than_minutes, stalest firs |
simulate_transfer_options | read | Read the advisory network simulation from the local read models: per site, whether it may originate or receive transfers, its total demand, its capacity over the published plan window and the resulting headroom (negative |
A2A skills: 2
- Find transfers that are not advancing
- Status of one transfer
Recommended next steps
- Raise the gremlins thresholds toward the fleet's 95%+ starting with internal/domain/transfer, the saga core.
- Design and implement the post-ALLOCATED revocation/compensation path so stuck or cancelled transfers release reservations automatically.
- Split saga.go by phase and extract wireSagas from main.go; move CaseRounding JSON tags into an adapter DTO.
Measured at origin/develop b3a6c3b (2026-10-30). Review sampled 5 files.
Architecture
Clean code
API design
A small, disciplined read-model context: invariant-checked scorecard aggregate, outbox + DLQ eventing, zero layer violations and strict gates; main risk is aggregate size for busy 30-day windows.
Risk reducer: supplies a trustworthy grade but decides nothing. The promise and sourcing decisions sit elsewhere.
- Production code
- 9,420 lines Go in 86 files, 27 packages
- Tests
- 14,505 lines, 373 test functions, 17 integration files, 48 BDD scenarios, 34 fitness tests
- Function size
- avg 10.3 lines (p95 26), 2 over 60 lines
- Complexity
- avg cyclomatic 2.7; highest consumeLoop.run (10), ValidID (10)
- Layering
- 0 infrastructure imports in domain/application; 2 domain packages
- Quality gates
- coverage 90%, mutation efficacy 95%, 17 CI jobs
- Persistence
- PostgreSQL, 3 migrations, 8 tables
- Deployables
- a2a, api, mcp
- Largest files
- none over 500 lines
- Console remote (web/)
- 1,325 lines TS/TSX, 6 test files
- Decisions
- 11 ADRs, 15 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 3 binaries (API+consumers+scheduler, MCP, A2A); Postgres + outbox relay to Kafka; event-fed scorecards
Strengths
- Domain is infrastructure-free: NodeScorecard (internal/domain/scorecard/scorecard.go) validates every invariant on Open/Restore and returns events from Recompute rather than publishing.
- Purely event-driven integration: 17 consumed CloudEvents types from 6 contexts, processed_events inbox for dedupe, DLQ in internal/adapters/inbound/kafka/deadletter.go, outbox relay for the 2 produced types.
- Recompute use case commits Save and Outbox.Append in one unit of work with optimistic version checks (internal/application/usecases/recompute.go, postgres/scorecard_repository.go Save).
- Ordered graceful shutdown in cmd/api/run.go: consumers and scheduler stop before the relay so nothing committed is stranded; OTel traces carried through slog.
Concerns
- The aggregate holds every in-window observation (map in scorecard.go); each Get/Save loads and diffs the full set (scorecard_repository.go replaceObservations), so per-event cost grows with window volume (~1.9k rows in the spec example).
- The recompute scheduler runs inside every cmd/api replica (cmd/api/run.go:80) with no lease; duplicate work is absorbed by optimistic-version conflicts (recompute.go Conflicts) rather than avoided.
- Consumers, scheduler, relay and HTTP share one process in cmd/api/run.go, so ingest load and read traffic cannot be scaled independently.
Clean code
Strengths
- 9.4k prod LOC vs 14.5k test LOC; avg function 10 lines, avg cyclomatic 2.7, 0 functions over cyclo 15, no file over 500 lines, 0 layer-import violations.
- Layered test suite: 373 unit tests, 17 integration-tagged files (testcontainers), 48 godog scenarios, 34 fitness tests, coverage gate 90% and gremlins mutation gates at 95%.
- Comments tie behaviour to ADRs and model rules (e.g. 'ADR 0002, A11, A13' in scorecard.go), and errors are wrapped with context throughout recompute.go.
- A shared repository contract suite (internal/adapters/outbound/repocontract) runs against both the memory and Postgres adapters, keeping fakes honest.
Concerns
- Recompute.one signals 'nothing to do' with a -1 sentinel count (internal/application/usecases/recompute.go:68-96), which callers must special-case; a small result type would read better.
- The two longest functions, telemetry.Setup and cmd/api run (66 lines each, internal/adapters/outbound/telemetry/telemetry.go, cmd/api/run.go), are wiring code that could be split into named steps.
APIs and contracts
- REST surface is two read-only, well-documented GETs (apis/openapi.yaml) with keyset pagination (limit/after/nextCursor), enums for grade and window, and RFC 9457 problem+json examples.
- Spec gap: handlers return 400 for unknown query params or non-integer limit (internal/adapters/inbound/http/handlers.go listInput) and 500 from the recoverer, but openapi.yaml documents only 404/422.
- No URL or media-type versioning (info.version 0.1.0, unversioned paths); events are better: every message has a versioned dataschema URN (e.g. ...NodeScorecardUpdated:v1) and a strict CloudEvents envelope.
- MCP tools get_scorecard and list_scorecards_by_grade carry ReadOnly/Idempotent annotations (internal/adapters/inbound/mcp/tools.go:153) and mirror the REST queries; endpoints are unauthenticated by fleet decision.
REST: 2 operations (2 read, 0 write)
| GET | /scorecards/{nodeId} | Get both scorecards (7-day and 30-day) of one node (GetScorecard) |
| GET | /scorecards | List the scorecards whose current grade matches (ListScorecardsByGrade) |
Events published: 2 types on retailnetwork.node-performance.analytics, retailnetwork.node-performance.events
- scorecard.NodeScorecardUpdated
- scorecard.NodeThresholdBreached
Events consumed: 15 types from 6 topics
retailnetwork.delivery-promise.events, retailnetwork.node-topology.events, retailnetwork.offer-availability.events, retailnetwork.seller-inbound.events, retailnetwork.shipping-and-tracking.events, retailnetwork.vendor-connectivity.events
- promise.PromiseBroken delivery-promise
- promise.PromiseKept delivery-promise
- inventoryfeed.InventoryFeedApplied offer-availability
- node.NodeOperationalProfileDeclared node-topology
- node.NodeRegistered node-topology
- journey.PackageHandedOver shipping-and-tracking
- inboundshipment.InboundShipmentShipped seller-inbound
- inboundreceipt.InboundReceiptSubmitted vendor-connectivity
- purchaseorder.PurchaseOrderAccepted vendor-connectivity
- purchaseorder.PurchaseOrderExpired vendor-connectivity
- purchaseorder.PurchaseOrderIssued vendor-connectivity
- purchaseorder.PurchaseOrderRejected vendor-connectivity
- purchaseorder.VendorShipmentConfirmed vendor-connectivity
- submission.SubmissionProcessed vendor-connectivity
- vendoraccount.VendorOnboarded vendor-connectivity
MCP tools: 2 (2 read-only)
get_scorecard | read | Read both scorecards of a node: the 7-day and the 30-day window, in that order, each with its state (PROVISIONAL or GRADED), its grade (A, B, C, D, or PROVISIONAL below the observation minimum of 50), its metrics (onTime |
list_scorecards_by_grade | read | List the scorecards whose current grade matches, ordered by scorecardId ascending, one page at a time: grade is required (A, B, C, D or PROVISIONAL), the window filter (7d or 30d), the page size (1..500, default 100) and |
A2A skills: 2
- How is this node performing
- Which nodes sit at this grade
Recommended next steps
- Bound aggregate load cost: store per-window counters/buckets instead of the full observation map, or cap and benchmark Get/Save at 30d volumes.
- Document 400 and 500 problem responses in apis/openapi.yaml so the spec matches handlers.go and the recoverer.
- Add a lease (advisory lock) for the recompute scheduler, or move it and the consumers to a worker binary.
Measured at origin/develop b2ffcd1 (2026-10-30). Review sampled 8 files.
Architecture
Clean code
API design
Strong registry context: rich Node aggregate with append-only profile revisions, DB-backed uniqueness behind domain checks, 104 BDD scenarios; main gaps are unpaginated node/lane lists and no consumed events.
An enabler every promise and route rests on; nobody picks a network for its node registry.
- Production code
- 11,285 lines Go in 95 files, 30 packages
- Tests
- 17,910 lines, 422 test functions, 20 integration files, 104 BDD scenarios, 35 fitness tests
- Function size
- avg 9.6 lines (p95 30), 1 over 60 lines
- Complexity
- avg cyclomatic 2.7; highest checkLocation (15), checkSnapshot (14)
- Layering
- 0 infrastructure imports in domain/application; 5 domain packages
- Quality gates
- coverage 90%, mutation efficacy 90%, 17 CI jobs
- Persistence
- PostgreSQL, 3 migrations, 7 tables
- Deployables
- a2a, api, mcp
- Largest files
- none over 500 lines
- Console remote (web/)
- 1,305 lines TS/TSX, 8 test files
- Decisions
- 11 ADRs, 15 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD Open Host Service; 3 binaries (API, MCP, A2A) + MFE web; Postgres + outbox to Kafka; producer only
Strengths
- Node aggregate validates type/operator/subtype compatibility and region existence at registration (internal/domain/node/node.go:101-131); operational profiles are immutable revision rows (ADR 0003).
- Duplicate checks are backed by partial unique indexes (lanes_one_open_key, nodes_vendor_ref_key in migrations/0001_node_topology_schema.up.sql) mapped to typed domain errors (postgres/errors.go).
- Every write runs in one unit of work and publishes via outbox (internal/application/usecases/lanes.go), with 9 CloudEvents types under com.retailnetwork.logistics.node-topology.*.
- Five small aggregates (node, lane, region, servicearea, shared) with no layer violations and no time/uuid in domain (facts).
Concerns
- Pure producer (AsyncAPI consumed is empty): vendor-connectivity writes nodes via synchronous REST (apis/openapi.yaml:14-16), so vendor onboarding depends on this service being up.
- Write routes (register, retire, assign service area) are unauthenticated by fleet decision (apis/openapi.yaml:18), so any caller can retire a node used for routing.
Clean code
Strengths
- Small, uniform functions: 11.3k prod LOC, average 9.6 lines, p95 30, average cyclo 2.7, no file over 500 lines (facts).
- Very strong test pyramid: 17.9k test LOC, 422 test funcs, 104 BDD scenarios, 20 integration-tagged files incl. concurrency_integration_test.go, 35 fitness tests.
- Use cases are short, linear transactions with clear names (OpenLane, CloseLane in internal/application/usecases/lanes.go).
Concerns
- checkLocation is at the cyclop cap (cyclo 15 in 15 lines, internal/domain/node/node.go) and lane checkSnapshot at 14 (internal/domain/lane/lane.go).
- internal/domain/node/node.go is 467 lines mixing types, registration, lifecycle and validation; validation could move beside profile_validate.go.
- Mutation gate at 90% (facts) trails checkout (95%) and storefront-bff (98%).
APIs and contracts
- Good: AIP-style lifecycle custom methods (:activate, :suspend, :retire, :close), PUT for idempotent declarations (operational-profile, service-areas/{postalPrefix}), Idempotency-Key on writes, RFC 9457 problem types.
- Good: explicit concurrency on profiles via profileRevision that must strictly increase (stale-profile-revision 409), an application-level alternative to If-Match.
- Gap: GET /nodes and GET /lanes take filters but no limit/cursor (apis/openapi.yaml:76-92), unlike pricing's after/limit; only regions document 'not paginated'. Version 0.1.0, no versioning scheme.
- Events: AsyncAPI 3.0 with 9 lifecycle events on one topic; MCP exposes 6 read tools mirroring the Open Host Service reads.
REST: 15 operations (6 read, 9 write, 9 of 9 writes require Idempotency-Key)
| POST | /nodes | Register a node (RegisterNode) |
| GET | /nodes | List nodes by type, region and status (ListNodes) |
| GET | /nodes/{nodeId} | Get one node with its current operational profile (GetNode) |
| PUT | /nodes/{nodeId}/operational-profile | Declare a new operational profile revision (DeclareOperationalProfile) |
| POST | /nodes/{nodeId}:activate | Activate a node (ActivateNode) |
| POST | /nodes/{nodeId}:suspend | Suspend a node (SuspendNode) |
| POST | /nodes/{nodeId}:retire | Retire a node (RetireNode) |
| POST | /lanes | Open a lane between two nodes (OpenLane) |
| GET | /lanes | List lanes by origin and destination (ListLanes) |
| POST | /lanes/{laneId}:close | Close a lane (CloseLane) |
| PUT | /service-areas/{postalPrefix} | Assign a postal prefix to a delivery station (AssignServiceArea) |
| GET | /service-areas/{postalPrefix} | Resolve which delivery station serves a postal prefix (ResolveServiceArea) |
| POST | /regions | Define a region (DefineRegion) |
| GET | /regions | List regions (ListRegions) |
| GET | /regions/{regionId} | Get a region (GetRegion) |
Events published: 9 types on retailnetwork.node-topology.events
- lane.LaneClosed
- lane.LaneOpened
- node.NodeActivated
- node.NodeOperationalProfileDeclared
- node.NodeRegistered
- node.NodeRetired
- node.NodeSuspended
- region.RegionDefined
- servicearea.ServiceAreaAssigned
MCP tools: 6 (6 read-only)
get_node | read | Read one network node with its current operational profile: type (FULFILLMENT_CENTER, INBOUND_CROSS_DOCK, RETURNS_CENTER, SORTATION_CENTER, DELIVERY_STATION or AIR_HUB), subtype, operator, vendor's own code, region, time |
list_nodes | read | List the network's nodes by id ascending, optionally filtered by type (FULFILLMENT_CENTER, INBOUND_CROSS_DOCK, RETURNS_CENTER, SORTATION_CENTER, DELIVERY_STATION or AIR_HUB), region and/or status (PROPOSED, ACTIVE, SUSPE |
list_lanes | read | List the directed lanes between nodes by id ascending, optionally only those leaving one origin node and/or arriving at one destination node (the filters combine with AND) |
resolve_service_area | read | Resolve which delivery station serves a postal prefix: the prefix (matched exactly), the deliveryStationNodeId, the station's regionId and the assignmentVersion |
get_region | read | Read one region of the network by its id: the code and the name it was defined with |
list_regions | read | List every region of the network by id ascending (code and name) |
A2A skills: 2
- Delivery station serving a postal prefix
- Find network nodes
Recommended next steps
- Add cursor pagination (after/limit) to GET /nodes and GET /lanes before the network grows past a few hundred nodes.
- Raise the mutation gate from 90% to the fleet's 95%+ and add web/ MFE tests (8 test files for 1.3k TS LOC).
- Split internal/domain/node/node.go validation helpers into their own file and simplify checkLocation below the cap.
Measured at origin/develop 1392939 (2026-10-30). Review sampled 6 files.
Architecture
Clean code
API design
Rich, well-tested last-mile context (waves, routes, attempts, return policy) with outbox, read-only MCP/A2A and a console remote; RecordAttempt spans several aggregates and the version-arithmetic persistence is fragile.
Fleet classifies it Supporting: it feeds the Core promise and sourcing with wave capacity, but stop counting is plain.
- Production code
- 11,073 lines Go in 89 files, 30 packages
- Tests
- 14,452 lines, 323 test functions, 9 integration files, 36 BDD scenarios, 35 fitness tests
- Function size
- avg 9.9 lines (p95 27), 1 over 60 lines
- Complexity
- avg cyclomatic 2.7; highest routeWaveQueries (12), checkSnapshotAttempts (11)
- Layering
- 0 infrastructure imports in domain/application; 5 domain packages
- Quality gates
- coverage 90%, mutation efficacy 95%, 17 CI jobs
- Persistence
- PostgreSQL, 1 migrations, 15 tables
- Deployables
- a2a, api, mcp
- Largest files
- none over 500 lines
- Console remote (web/)
- 1,312 lines TS/TSX, 7 test files
- Decisions
- 9 ADRs, 12 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 3 binaries (API+relay+consumers, read-only MCP, A2A) + MF web remote; Postgres + outbox to Kafka; local read models
Strengths
- Four aggregates (DeliveryWave, Route, DeliveryServicePartner, PackageHistory) with named invariants as typed errors, e.g. capacity, stop-key, inducted-only and delivered-once rules (internal/domain/route/route.go)
- Upstream facts (stations, service areas, labels, LoadArrived) arrive by consumed CloudEvents into rm_* read models; there are no synchronous sibling calls (apis/asyncapi.yaml, postgres/readmodels.go)
- MCP adapter holds only read use cases, every tool is annotated readOnly/idempotent, and a governance test plus golden tool registry pins this (internal/adapters/inbound/mcp/tools.go, governance_test.go)
- 35 fitness tests, zero layer violations per facts; separate API/MCP/A2A binaries with one Helm chart (charts/last-mile-delivery)
Concerns
- RecordAttempt mutates Route, PackageHistory, possibly a next DeliveryWave, and completes route and wave in ONE transaction (internal/application/usecases/routes.go execute, induct.go place), widening lock scope and contention on busy waves
- Cross-aggregate rules sit in the application layer: StartRoute checks the wave is DISPATCHED in the use case (usecases/routes.go:79), not in a domain service, while PlanRoute's equivalent rule lives in route.checkPlanning
- The Route domain type imports wave and partner aggregates and takes *wave.DeliveryWave in Planning (internal/domain/route/route.go:20-22,125), coupling aggregate packages instead of passing value snapshots
Clean code
Strengths
- Low complexity throughout: avg 9.9 lines and cyclo 2.7, none over cyclo 15, one function over 60 lines (facts); errors wrap with context (fmt.Errorf %w with ids and states) (internal/domain/route/route.go)
- Tests outweigh code (14.5k test LOC vs 11.1k prod), with 36 BDD scenarios, a shared repocontract suite, a 90% coverage gate and a 95% mutation gate (facts)
- Web remote is small and typed (0 explicit any) and centralises problem+json into a single ApiError shape (web/src/api.ts)
Concerns
- Optimistic locking relies on version arithmetic: Save inserts when Version==1 and updates WHERE version = $3 - 1 (internal/adapters/outbound/postgres/routes.go:114,160), so a create-then-mutate or two mutations before one save gives a false conflict
- Attempts persist by counting stored rows and inserting the tail (postgres/routes.go:121-131), an implicit append-only contract the domain type does not express
- route.go is 450 lines and wave.go 367, the largest domain files and candidates for splitting by lifecycle phase (internal/domain/route/route.go, internal/domain/wave/wave.go)
APIs and contracts
- Every write op references the IdempotencyKey parameter (9 in apis/openapi.yaml); state transitions use consistent custom methods (:close-induction, :dispatch, :cancel, :start); errors are problem+json slugs
- Missing: no ETag/If-Match despite versioned aggregates; GET /waves is not paginated (bounded by station+date, so low risk); no path/media-type versioning and the spec is 0.1.0 (apis/openapi.yaml)
- Event contract is broad and well named: 7 integration events + RoutePlanned on a separate analytics topic, typed com.retailnetwork.logistics.last-mile-delivery.<aggregate>.<Event> (apis/asyncapi.yaml)
- MCP tools mirror the REST read bodies in camelCase with jsonschema examples on inputs (internal/adapters/inbound/mcp/tools.go); REST/MCP are unauthenticated by fleet decision, which matters for :dispatch/:cancel
REST: 12 operations (3 read, 9 write, 9 of 9 writes require Idempotency-Key)
| POST | /waves | Schedule a delivery wave (ScheduleWave) |
| GET | /waves | List the waves of a station for a service date |
| GET | /waves/{waveId}/stops | List the stops of a wave (packages grouped by stopKey) |
| POST | /waves/{waveId}:close-induction | Close induction of a wave (CloseInduction) |
| POST | /waves/{waveId}:dispatch | Dispatch a wave (DispatchWave) |
| POST | /waves/{waveId}:cancel | Cancel a wave (CancelWave) |
| POST | /routes | Plan a DSP van route in a wave (PlanRoute) |
| GET | /routes/{routeId} | Get a route with its stops and attempts |
| POST | /routes/{routeId}:start | Start a route (StartRoute) |
| POST | /routes/{routeId}/attempts | Record a delivery attempt (RecordAttempt) |
| POST | /partners | Contract a delivery service partner (ContractPartner) |
| POST | /partners/{dspId}:deactivate | Deactivate a delivery service partner (DeactivatePartner) |
Events published: 8 types on retailnetwork.last-mile-delivery.analytics, retailnetwork.last-mile-delivery.events
- packageattempthistory.PackageInductionDeferred
- packageattempthistory.PackageReturnInitiated
- route.DeliveryAttempted
- route.PackageOutForDelivery
- route.RoutePlanned
- wave.DeliveryWaveCancelled
- wave.DeliveryWaveCapacityChanged
- wave.DeliveryWaveScheduled
Events consumed: 4 types from 3 topics
retailnetwork.linehaul-transportation.events, retailnetwork.node-topology.events, retailnetwork.shipping-and-tracking.events
- load.LoadArrived linehaul-transportation
- node.NodeRegistered node-topology
- servicearea.ServiceAreaAssigned node-topology
- label.LabelIssued shipping-and-tracking
MCP tools: 3 (3 read-only)
list_waves | read | List the delivery waves of one station for one service date, ordered by inductCutoffAt: state (OPEN, INDUCTION_CLOSED, DISPATCHED, COMPLETED or CANCELLED), the induct cutoff and delivery window, the stop capacity with as |
get_wave_stops | read | Read the stops of one wave: the packages inducted in it grouped by the opaque stopKey (the keyed hash of the normalized address; pkg:<trackingNumber> when no label data was received), in the order of each stop's first in |
get_route | read | Read one route of a delivery service partner: its state (PLANNED, OUT_FOR_DELIVERY or COMPLETED), its numbered stops with the trackingNumbers of each and the outcome derived from the per-package attempts (omitted until e |
A2A skills: 2
- List a station's delivery waves for a day
- Look up where one route stands
Recommended next steps
- Track LoadedVersion on aggregates (as shopping-cart does) and update WHERE version = loaded, instead of Version==1 / version-1 heuristics
- Split RecordAttempt: record the attempt and history in one tx, and run next-wave placement and route/wave completion as outbox-driven policies
- Expose aggregate versions as ETag with If-Match on wave/route transitions
Measured at origin/develop 6c71a6b (2026-10-30). Review sampled 8 files.
Architecture
Clean code
API design
Mature linehaul context with clear aggregates, a transactional (savepoint) Idempotency-Key middleware and 50 BDD scenarios; booking hot-spots, large cancel transactions and keyset-less paging are the gaps.
Supplies real trips and capacity that promises rely on, but decides neither the promise nor the shipping node.
- Production code
- 11,901 lines Go in 94 files, 32 packages
- Tests
- 16,725 lines, 404 test functions, 14 integration files, 50 BDD scenarios, 35 fitness tests
- Function size
- avg 10.5 lines (p95 27), 1 over 60 lines
- Complexity
- avg cyclomatic 2.9; highest Profile.Validate (14), DepartureRepo.List (14)
- Layering
- 0 infrastructure imports in domain/application; 6 domain packages
- Quality gates
- coverage 90%, mutation efficacy 90%, 17 CI jobs
- Persistence
- PostgreSQL, 1 migrations, 10 tables
- Deployables
- a2a, api, mcp
- Largest files
- none over 500 lines
- Console remote (web/)
- 1,269 lines TS/TSX, 6 test files
- Decisions
- 11 ADRs, 15 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 3 binaries (API+relay+consumers, read-only MCP, A2A) + MF web remote; Postgres + outbox to Kafka
Strengths
- Departure, Load, LaneSchedule and ExpectedVolume aggregates document their state machines and invariants in code and enforce them with typed errors (internal/domain/departure/departure.go, internal/domain/load/load.go)
- Transactional Idempotency-Key middleware: INSERT ON CONFLICT serialises same-key requests; handler runs in a SAVEPOINT via TxBinder so key, aggregates and outbox commit together (inbound/http/idempotency.go)
- All upstream knowledge (node-topology, order-sourcing, shipping-and-tracking) arrives via 13 consumed CloudEvents types into lane_views/node_views; no sync sibling calls (apis/asyncapi.yaml)
- Rebooking logic sits in one cohesive bookingSet that loads each departure once per transaction and saves after every change (internal/application/usecases/booking.go)
Concerns
- Capacity is a single booked counter on Departure, bumped and saved per package (departure.go Book), so a popular pickup departure becomes a hot row under FulfillmentLocked bursts
- Cancelling departures rebooks every volume booked on them inside one transaction (usecases/booking.go cancel/moveBookingsOff), so a big cancellation runs as one long, lock-heavy tx with no batching
- moveBookingsOff silently tolerates a counter/row disagreement ('the row and the departure disagree, and the booking is moved off anyway', usecases/booking.go:159) without a log, metric or repair path
Clean code
Strengths
- Avg 10.5 lines and cyclo 2.9 per function, none over cyclo 15, one over 60 lines (telemetry.Setup); test LOC 16.7k vs prod 11.9k (facts)
- 50 BDD scenarios across 5 features (the most in this batch), 14 integration-tagged files, repocontract suite, 90% coverage and mutation gates (facts)
- Error messages carry ids, states and instants (e.g. ErrDepartureFull with booked/capacity), making failures diagnosable (internal/domain/departure/departure.go)
Concerns
- Stale copied doc on the idempotency middleware: it cites routes 'POST /nodes', 'POST /nodes/{nodeId}:activate' and 'migration 0002' (internal/adapters/inbound/http/idempotency.go:38,44), but this repo has no node routes and one migration
- Domain type network.Profile carries json struct tags (internal/domain/network/profile.go:11-46), leaking a serialisation concern into the domain (flagged by the facts DomainStructTags check)
- Telemetry bootstrap is duplicated per binary (cmd/api/telemetry.go, cmd/mcp/telemetry.go, cmd/a2a/telemetry.go); DepartureRepo.List is 57 lines at cyclo 14 (internal/adapters/outbound/postgres/departure_repository.go)
APIs and contracts
- Every write references IdempotencyKey; transitions use consistent custom methods (:retire, :cancel, :change-capacity, :close, :dispatch, :receive); problem+json with 413/422 responses declared (apis/openapi.yaml)
- GET /departures takes limit (default 500, max 1000) but has no continuation cursor; callers must page by moving 'from', which can skip ties on cutoffAt (apis/openapi.yaml:109-153, mcp/tools.go list_departures)
- Replay header is Idempotency-Replayed here but Idempotent-Replayed in shopping-cart (internal/adapters/inbound/http/idempotency.go:23), a fleet-level inconsistency; no ETag/If-Match and spec stays 0.1.0
- Events split cleanly: 7 integration events vs 3 analytics events on a separate topic, typed by aggregate (departure/load); MCP tools have detailed jsonschema descriptions (apis/asyncapi.yaml)
REST: 11 operations (2 read, 9 write, 9 of 9 writes require Idempotency-Key)
| POST | /lane-schedules | Define the weekly schedule of a lane (DefineLaneSchedule) |
| POST | /lane-schedules/{laneId}:retire | Retire the schedule of a lane (RetireLaneSchedule) |
| GET | /departures | List departures by origin, destination and time window (ListDepartures) |
| GET | /departures/{departureId} | Get one departure |
| POST | /departures/{departureId}:cancel | Cancel a scheduled departure (CancelDeparture) |
| POST | /departures/{departureId}:change-capacity | Change the package capacity of a scheduled departure (ChangeDepartureCapacity) |
| POST | /loads | Open a load on a departure (OpenLoad) |
| POST | /loads/{loadId}/packages | Add a package to an open load (AddPackage) |
| POST | /loads/{loadId}:close | Close an open load (CloseLoad) |
| POST | /loads/{loadId}:dispatch | Dispatch a closed load (DispatchLoad) |
| POST | /loads/{loadId}:receive | Receive a load at its destination node (ReceiveLoad) |
Events published: 10 types on retailnetwork.linehaul-transportation.analytics, retailnetwork.linehaul-transportation.events
- departure.BookingFailed
- departure.BookingMoved
- departure.DepartureArrived
- departure.DepartureCancelled
- departure.DepartureCapacityChanged
- departure.DepartureDeparted
- departure.DepartureScheduled
- load.LoadArrived
- load.LoadClosed
- load.LoadDeparted
Events consumed: 13 types from 3 topics
retailnetwork.node-topology.events, retailnetwork.order-sourcing.events, retailnetwork.shipping-and-tracking.events
- assignment.FulfillmentCancelled order-sourcing
- assignment.FulfillmentLocked order-sourcing
- assignment.FulfillmentReassigned order-sourcing
- assignment.FulfillmentReleasedToNode order-sourcing
- lane.LaneClosed node-topology
- lane.LaneOpened node-topology
- node.NodeActivated node-topology
- node.NodeOperationalProfileDeclared node-topology
- node.NodeRegistered node-topology
- node.NodeRetired node-topology
- node.NodeSuspended node-topology
- label.LabelIssued shipping-and-tracking
- label.LabelVoided shipping-and-tracking
MCP tools: 2 (2 read-only)
list_departures | read | List departures of the horizon by cutoffAt (then departureId), a page at a time, optionally only those leaving one origin (origin), bound for one destination (destination) and/or whose cutoffAt falls in a window [from, t |
get_departure | read | Read one departure by id: its lane, kind (PICKUP, LINEHAUL or AIR), origin and destination nodes, cutoffAt (no booking after it), departsAt and arrivesAt, capacityPackages, bookedPackages, remainingPackages and its state |
A2A skills: 2
- Find departures and their remaining capacity
- Look up where one departure stands
Recommended next steps
- Add an opaque keyset cursor (cutoffAt, departureId) to GET /departures and list_departures
- Batch departure-cancellation rebooking through the outbox/policy loop and emit a metric when booked counters and booking rows disagree
- Fix the stale idempotency doc comment, move Profile JSON tags into the postgres adapter, and agree a fleet-wide replay header name
Measured at origin/develop 7308e19 (2026-10-30). Review sampled 7 files.
Architecture
Clean code
API design
Well-modelled seller/inbound context: GS1-validated aggregates, a carefully reasoned transactional idempotency middleware and outbox publishing; a large composition root and Postgres-coupled HTTP layer are rough edges.
Fleet classifies it Supporting: it enables supply with common receiving practice and decides no promise or route.
- Production code
- 11,772 lines Go in 84 files, 33 packages
- Tests
- 15,398 lines, 380 test functions, 12 integration files, 47 BDD scenarios, 31 fitness tests
- Function size
- avg 10.5 lines (p95 28), 1 over 60 lines
- Complexity
- avg cyclomatic 2.9; highest checkCombination (11), rejectNUL (10)
- Layering
- 0 infrastructure imports in domain/application; 7 domain packages
- Quality gates
- coverage 90%, mutation efficacy 99%, 17 CI jobs
- Persistence
- PostgreSQL, 2 migrations, 11 tables
- Deployables
- a2a, api, mcp
- Largest files
- cmd/api/main.go (543), internal/adapters/outbound/memory/store.go (535)
- Console remote (web/)
- 1,109 lines TS/TSX, 6 test files
- Decisions
- 9 ADRs, 13 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 3 binaries (API, MCP, A2A) + MF web remote; Postgres + outbox to Kafka (domain + analytics topics)
Strengths
- Four aggregates/models (seller, inboundplan, inboundshipment, scorecard) plus a pure gs1 value-object package (SSCC/GTIN parsing, check digits) in internal/domain/shared/gs1.
- Shipment.RecordReceipt (internal/domain/inboundshipment/receipt.go) is idempotent by design: first answer per carton is final, a closed shipment ignores redelivered receipts.
- Idempotency row, aggregate writes and outbox rows commit in one transaction via TxBinder (internal/adapters/inbound/http/idempotency.go), with a documented race-safety argument.
- Splits integration events (retailnetwork.seller-inbound.events) from analytics facts (...analytics), keeping the public contract narrow.
Concerns
- The HTTP inbound adapter owns SQL and a *pgxpool.Pool (RequireIdempotencyKey in internal/adapters/inbound/http/idempotency.go:55-103), so the REST adapter is bound to Postgres rather than to an idempotency port.
- cmd/api/main.go is 543 lines with 20 functions (relay, loops, readiness, shutdown); the composition root carries runtime logic that would be easier to test as a package.
- Write routes, the scorecard and SSCC label data are unauthenticated by fleet decision (MCP get_shipment_labels in internal/adapters/inbound/mcp/tools.go), so any caller can onboard or suspend sellers.
Clean code
Strengths
- 568 funcs, avg 10.5 lines, p95 28, max cyclomatic 11 (checkCombination in gs1/scan.go); receipt logic split into small helpers (apply, applyUnlisted, quantityDiscrepancies).
- Validation errors are precise and indexed (e.g. cartons[%d].items[%d] in receipt.go normaliseReceipt), which makes 422s actionable.
- Tests: 15.4k test LOC vs 11.8k prod, 47 BDD scenarios, 12 integration files, a fuzz test, mutants_test.go for surviving mutants, 31 fitness tests, 99% mutation gate.
Concerns
- Use cases are methods on one usecases.Service spread over plans.go, shipments.go, sellers.go, scorecard.go (shipments.go 336 lines) rather than one struct per use case as in sibling repos.
- Two files exceed 500 lines: cmd/api/main.go (543) and the test double internal/adapters/outbound/memory/store.go (535).
- Module path github.com/claudioed/seller-inbound (imports in internal/application/usecases/shipments.go) does not match the IQVO org name.
APIs and contracts
- 14 operations in apis/openapi.yaml with consistent custom-method verbs (:suspend, :reinstate, :confirm, :cancel, :label, :ship) mirroring the aggregate commands.
- Idempotency-Key is mandatory on every write, scoped per route, 24h TTL, with replay of cached 4xx/2xx and 422 idempotency-key-reused on a different body; problem+json error model.
- No list/search endpoints (e.g. plans by seller, shipments by plan) and therefore no pagination; consumers must know ids up front. No URI/media-type versioning.
- Events use com.retailnetwork.partner.seller-inbound.<aggregate>.<Type>; 3 integration + 6 analytics types published and 8 consumed types documented in apis/asyncapi.yaml.
REST: 14 operations (4 read, 10 write, 10 of 10 writes require Idempotency-Key)
| POST | /sellers | Onboard a seller (OnboardSeller) |
| POST | /sellers/{sellerId}:suspend | Suspend a seller (SuspendSeller) |
| POST | /sellers/{sellerId}:reinstate | Reinstate a seller (ReinstateSeller) |
| GET | /sellers/{sellerId}/scorecard | Get a seller's compliance scorecard (GetSellerScorecard) |
| POST | /inbound-plans | Create an inbound plan (CreateInboundPlan) |
| GET | /inbound-plans/{planId} | Get an inbound plan (GetInboundPlan) |
| POST | /inbound-plans/{planId}:confirm | Confirm an inbound plan (ConfirmInboundPlan) |
| POST | /inbound-plans/{planId}:cancel | Cancel an inbound plan (CancelInboundPlan) |
| POST | /inbound-plans/{planId}/shipments | Open an inbound shipment (CreateInboundShipment) |
| POST | /inbound-shipments/{shipmentId}/cartons | Add a carton (AddCarton) |
| POST | /inbound-shipments/{shipmentId}:label | Label an inbound shipment (LabelShipment) |
| GET | /inbound-shipments/{shipmentId}/labels | Get the label data (GetLabels) |
| POST | /inbound-shipments/{shipmentId}:ship | Ship an inbound shipment (ShipInboundShipment) |
| GET | /inbound-shipments/{shipmentId} | Get an inbound shipment (GetInboundShipment) |
Events published: 9 types on retailnetwork.seller-inbound.analytics, retailnetwork.seller-inbound.events
- inboundplan.InboundPlanConfirmed
- inboundshipment.InboundDiscrepancyRecorded
- inboundshipment.InboundShipmentLabelled
- inboundshipment.InboundShipmentReceived
- inboundshipment.InboundShipmentShipped
- seller.SellerComplianceViolationRecorded
- seller.SellerOnboarded
- seller.SellerReinstated
- seller.SellerSuspended
Events consumed: 8 types from 3 topics
retailnetwork.node-topology.events, retailnetwork.offer-availability.events, retailnetwork.vendor-connectivity.events
- catalogitem.CatalogItemPackLevelRetired offer-availability
- catalogitem.CatalogItemPackagingDeclared offer-availability
- node.NodeActivated node-topology
- node.NodeOperationalProfileDeclared node-topology
- node.NodeRegistered node-topology
- node.NodeRetired node-topology
- node.NodeSuspended node-topology
- inboundreceipt.InboundReceiptSubmitted vendor-connectivity
MCP tools: 4 (4 read-only)
get_seller_scorecard | read | Answer a seller's rolling-window compliance scorecard from the facts this service recorded (ADR 0005): shipments received in the window, cartons reported and how many were RECEIVED, receiptAccuracyRate (omitted when noth |
get_inbound_plan | read | Read one inbound plan: the seller, the destination node, the packing option (INDIVIDUAL or CASE_PACKED), the state (DRAFT, CONFIRMED or CANCELLED) and the declared lines in eaches (catalog item, GTIN, quantity), with the |
get_shipment_labels | read | Read the label data of a labelled inbound shipment, one entry per carton: the SSCC, the GS1-128 element string (00)<sscc>, the human readable line, the contents in eaches with lot and expiry when declared, the content su |
get_inbound_shipment | read | Read one inbound shipment: its plan, seller and destination node, the state (PLANNED, PACKING, LABELLED, SHIPPED or RECEIVED) and every carton packed so far (SSCC, optional parent SSCC, kind, contents in eaches, gross we |
A2A skills: 2
- Assess a seller's compliance
- Check where an inbound stands
Recommended next steps
- Move the idempotency store behind an outbound port/adapter so the HTTP adapter no longer embeds SQL.
- Extract relay/worker/shutdown logic from cmd/api/main.go into a tested internal runtime package.
- Add paginated list endpoints for plans and shipments per seller to support portal and agent use.
Measured at origin/develop 2a0e016 (2026-10-30). Review sampled 5 files.
Architecture
Clean code
API design
Mature partner-facing gateway: async 202 + transaction reconciliation, outbox, idempotent neighbour calls and a rich contract; it carries the most synchronous coupling and the largest composition root sampled.
Revenue-channel enabler; the contract must be right but the sourcing decisions that differentiate live elsewhere.
- Production code
- 14,560 lines Go in 89 files, 35 packages
- Tests
- 17,971 lines, 439 test functions, 11 integration files, 54 BDD scenarios, 32 fitness tests
- Function size
- avg 11.2 lines (p95 30), 2 over 60 lines
- Complexity
- avg cyclomatic 3.2; highest checkIdentity (15), normaliseReceiptCarton (15)
- Layering
- 0 infrastructure imports in domain/application; 6 domain packages
- Quality gates
- coverage 90%, mutation efficacy 99%, 17 CI jobs
- Persistence
- PostgreSQL, 2 migrations, 10 tables
- Deployables
- a2a, api, mcp
- Largest files
- cmd/api/main.go (634), internal/adapters/outbound/repocontract/contract.go (631)
- Console remote (web/)
- 1,828 lines TS/TSX, 8 test files
- Decisions
- 9 ADRs, 13 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD gateway/ACL context; 3 binaries (API, MCP, A2A); Postgres + outbox; 4 sync in-org REST clients + 4 consumed topics
Strengths
- Vendor writes are stored as Submissions and processed by a background loop (usecases/submissions.go ProcessSubmission); neighbour calls run outside the DB transaction and only the outcome commits with the outbox.
- Neighbour outages leave a submission PROCESSING with bounded attempts (SUBMISSION_MAX_ATTEMPTS), and calls carry the transaction id as Idempotency-Key so a retry never applies a feed twice (httpclient/clients.go:124).
- PurchaseOrder aggregate documents its full 8-state machine and model-named errors in internal/domain/purchaseorder/purchaseorder.go; node ownership comes from a local VendorNodeView fed by node-topology events.
- Composition root refuses misconfiguration before binding, and the process exits non-zero if any loop, consumer or relay stops (cmd/api/main.go header).
Concerns
- Four synchronous in-org dependencies (node-topology, offer-availability, shipping-and-tracking, node-performance in internal/adapters/outbound/httpclient/clients.go), 5s timeout, no circuit breaker; label and scorecard calls fail when a neighbour is down.
- RequestLabel calls shipping-and-tracking once per missing package in a loop on the request path (internal/application/usecases/orders.go:314-319), so latency grows with package count and partial failures return a subset.
- Vendor identity is a body/query vendorId with no authentication (apis/openapi.yaml:28-30, 'not security'); any caller can act as any vendor on this partner-facing API.
Clean code
Strengths
- Mutation gates at 99% efficacy and 99% coverage, the strictest sampled, plus 54 BDD scenarios, a fuzz test, golden CloudEvents tests and 32 fitness tests.
- 14.6k prod LOC with avg 11.2 lines/function and avg cyclomatic 3.2; use cases are short and named after model commands (RegisterVendorNode, SubmitInventory, ProcessSubmission).
- Neighbour errors are classified once (classify in usecases/submissions.go) into success, refusal-with-upstream-code, or retryable pending.
Concerns
- cmd/api/main.go is 634 lines and internal/adapters/outbound/repocontract/contract.go 631 lines, the only two files over 500 lines; the composition root would read better split by concern.
- Three functions sit exactly at the cyclomatic cap of 15 (purchaseorder.checkIdentity, inbound.normaliseReceiptCarton in internal/domain/inbound/receipt.go, repocontract.orderQueries).
- Simulation knobs (TX_FAILURE_RATE, PO_REDELIVERY_RATE) are evaluated in the production path (usecases/submissions.go:148); default 0, but test-harness behaviour lives in service code.
APIs and contracts
- Good: every async write returns 202 + transactionId reconciled via GET /vendor/transactions/{id}; every POST/PUT takes Idempotency-Key; 429 with Retry-After is part of the contract (apis/openapi.yaml:20-36).
- Good: poll endpoints use opaque nextToken continuation with documented at-least-once redelivery; RFC 9457 errors with one slug per model error; AIP custom methods :suspend/:reinstate.
- Missing: no path/media-type versioning despite info.version 1.0.0, and no ETag/If-Match on PUT /vendor/nodes/{nodeId}/profile; vendorId as a body field is not a sustainable identity model.
- Events: 10 integration + 1 analytics CloudEvents types under com.retailnetwork.partner.vendor-connectivity.*; MCP exposes 9 read tools including get_transaction for async follow-up.
REST: 19 operations (9 read, 10 write, 10 of 10 writes require Idempotency-Key)
| GET | /vendor/purchase-orders | Poll purchase orders (PollPurchaseOrders) |
| GET | /vendor/purchase-orders/{poNumber} | Get one purchase order (GetPurchaseOrder) |
| POST | /vendor/acknowledgements | Acknowledge a purchase order in full (SubmitAcknowledgement) |
| POST | /vendor/inventory | Submit an inventory feed for one node (SubmitInventory) |
| GET | /vendor/nodes | List the vendor's nodes (ListVendorNodes) |
| POST | /vendor/nodes | Register a vendor node (RegisterVendorNode) |
| GET | /vendor/nodes/{nodeId} | Get one of the vendor's nodes (GetNode) |
| PUT | /vendor/nodes/{nodeId}/profile | Declare the node's operational profile (DeclareNodeProfile) |
| GET | /vendor/nodes/{nodeId}/scorecard | Get the node's measured scorecard (GetScorecard) |
| POST | /vendor/shipping-labels | Request labels for an accepted purchase order (RequestLabel) |
| POST | /vendor/shipment-confirmations | Confirm that a purchase order shipped (SubmitShipmentConfirmation) |
| GET | /vendor/inbound-shipments | Poll inbound shipments (PollInboundShipments) |
| GET | /vendor/inbound-shipments/{shipmentId} | Get one inbound shipment (GetInboundShipment) |
| POST | /vendor/inbound-receipts | Report an inbound receipt (SubmitInboundReceipt) |
| GET | /vendor/transactions/{transactionId} | Get the outcome of an asynchronous write (GetTransaction) |
| POST | /vendors | Onboard a vendor (OnboardVendor) |
| GET | /vendors/{vendorId} | Get a vendor account (GetVendor) |
| POST | /vendors/{vendorId}:suspend | Suspend a vendor (SuspendVendor) |
| POST | /vendors/{vendorId}:reinstate | Reinstate a vendor (ReinstateVendor) |
Events published: 11 types on retailnetwork.vendor-connectivity.analytics, retailnetwork.vendor-connectivity.events
- inboundreceipt.InboundReceiptSubmitted
- purchaseorder.PurchaseOrderAccepted
- purchaseorder.PurchaseOrderCancelled
- purchaseorder.PurchaseOrderExpired
- purchaseorder.PurchaseOrderIssued
- purchaseorder.PurchaseOrderRejected
- purchaseorder.VendorShipmentConfirmed
- submission.SubmissionProcessed
- vendoraccount.VendorOnboarded
- vendoraccount.VendorReinstated
- vendoraccount.VendorSuspended
Events consumed: 13 types from 4 topics
retailnetwork.node-topology.events, retailnetwork.offer-availability.events, retailnetwork.order-sourcing.events, retailnetwork.seller-inbound.events
- catalogitem.CatalogItemPackLevelRetired offer-availability
- catalogitem.CatalogItemPackagingDeclared offer-availability
- listing.ListingCreated offer-availability
- assignment.FulfillmentCancelled order-sourcing
- assignment.FulfillmentReleasedToNode order-sourcing
- node.NodeActivated node-topology
- node.NodeOperationalProfileDeclared node-topology
- node.NodeRegistered node-topology
- node.NodeRetired node-topology
- node.NodeSuspended node-topology
- inboundshipment.InboundShipmentLabelled seller-inbound
- inboundshipment.InboundShipmentReceived seller-inbound
- inboundshipment.InboundShipmentShipped seller-inbound
MCP tools: 9 (9 read-only)
poll_purchase_orders | read | Page through the purchase orders released to one vendor, oldest first: poNumber, nodeId, state (ISSUED, ACK_PROCESSING, ACCEPTED, REJECTED, EXPIRED, SHIPMENT_PROCESSING, SHIPPED or CANCELLED), issuedAt, requiredShipBy, a |
get_purchase_order | read | Read one purchase order by poNumber as the vendor sees it: state and windows (issuedAt, requiredShipBy, ackBy), the lines, the acknowledgement once its transaction succeeded, the shipping labels and tracking numbers, and |
poll_inbound_shipments | read | Page through the inbound shipments bound for one vendor's nodes, oldest shipment first: shipmentId, sellerId, nodeId, shippedAt, status (SHIPPED or RECEIVED) and the pallet-and-carton tree (pallet SSCC, carton SSCC and p |
get_inbound_shipment | read | Read one inbound shipment by shipmentId: the pallets with the cartons stacked on them, the top-level cartons, and every item line in eaches (gtin, sku, qtyEaches, lot, expiry) |
list_vendor_nodes | read | List the fulfilment nodes the network has registered for one vendor, sorted by nodeId: type and subtype, status (PROPOSED, ACTIVE, SUSPENDED or RETIRED), region, timezone, handling time and profile revision |
get_vendor_node | read | Read one fulfilment node of a vendor: type, subtype, status, region, timezone, handling time minutes and profile revision |
get_node_scorecard | read | Read a vendor node's rolling scorecards, relayed live from the node-performance context: per window (7d, 30d, 90d) the grade, on-time handover rate, late acknowledgement rate, reject rate, expiry rate, promise-kept rate |
get_transaction | read | Follow one asynchronous write of a vendor by the transactionId its 202 answer returned: kind (ACKNOWLEDGEMENT, INVENTORY, NODE_REGISTRATION, NODE_PROFILE or SHIPMENT_CONFIRMATION), status (PROCESSING, SUCCESS or FAILURE) |
get_vendor | read | Read a vendor account: name, acknowledgement window in minutes (how long after issuedAt an acknowledgement is accepted) and state (ACTIVE or SUSPENDED) |
A2A skills: 2
- Check where one purchase order stands
- Read how one vendor node is performing
Recommended next steps
- Put a circuit breaker and bulkhead around the four httpclient neighbours, and issue labels for all packages in one batched call or async submission.
- Split cmd/api/main.go into config, adapter wiring and loop supervision files.
- Move simulation knobs behind a separate simulator adapter or build tag so the production path has no chaos branches.
Measured at origin/develop ac5f2ac (2026-10-30). Review sampled 7 files.
Architecture
Clean code
API design
Disciplined hexagonal context with encapsulated aggregates, outbox + inbox idempotency and strong contract hygiene; main weakness is a synchronous write-path call to customer-ordering.
Labels and tracking are expected of any parcel business and win no customers; a candidate to buy behind an ACL.
- Production code
- 10,608 lines Go in 85 files, 33 packages
- Tests
- 14,652 lines, 366 test functions, 12 integration files, 39 BDD scenarios, 38 fitness tests
- Function size
- avg 9.9 lines (p95 27), 1 over 60 lines
- Complexity
- avg cyclomatic 2.7; highest replay (12), checkSnapshot (12)
- Layering
- 0 infrastructure imports in domain/application; 3 domain packages
- Quality gates
- coverage 90%, mutation efficacy 90%, 17 CI jobs
- Persistence
- PostgreSQL, 1 migrations, 8 tables
- Deployables
- a2a, api, mcp
- Largest files
- none over 500 lines
- Console remote (web/)
- 1,149 lines TS/TSX, 7 test files
- Decisions
- 9 ADRs, 12 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 3 binaries (API, MCP, A2A); Postgres + transactional outbox to Kafka; 4 consumed topics with DLQ
Strengths
- ShippingLabel aggregate (internal/domain/label/label.go) keeps all fields private, validates on Issue and on Restore (checkSnapshot), and emits events; no infra imports, no time.Now/uuid in domain.
- Writes run in a unit of work that saves aggregates and outbox rows together (usecases/labels.go create/VoidLabel), with optimistic concurrency via version-guarded UPDATE in postgres/labels.go Save.
- Consumers are idempotent via a processed_events inbox keyed by consumer + event id, with dead-letter and shutdown handling guarded by fitness tests (internal/architecture/kafka_dlq_shutdown_fitness_test.go).
- Ship-to PII is never on the aggregate: sealed snapshot behind a port, purged 30 days after close (postgres/labels.go PurgeClosedBefore), per ADR 0002 A9.
Concerns
- IssueLabel makes a synchronous REST call to customer-ordering on the write path (internal/adapters/outbound/customerordering/gateway.go, usecases/labels.go:73); it has a timeout but no circuit breaker, so a customer-ordering outage blocks issuance (503).
- Contract drift with last-mile-delivery is tolerated in code: two CloudEvents types are accepted for PackageReturnInitiated (internal/adapters/inbound/kafka/handlers.go:36-37), so the producer catalogue is not the single source of truth.
- REST and MCP endpoints are unauthenticated (fleet decision, stated in apis/openapi.yaml info.description), while POST /labels is an in-org route that mints labels and reads PII.
Clean code
Strengths
- Small functions: avg 9.9 lines, p95 27, avg cyclomatic 2.7, zero functions over cyclo 15, no file over 500 lines across 10.6k prod LOC.
- Test LOC (14.6k) exceeds prod LOC; 39 BDD scenarios, 12 integration-tagged files with testcontainers, 38 fitness tests and 90% coverage/mutation gates in CI.
- Doc comments tie code to ADR clauses (e.g. 'ADR 0002 A2' on the tracking-number retry in usecases/labels.go:99), and constraint-name to domain-error mapping is explicit (postgres/labels.go mapLabelInsertError).
Concerns
- Field bounds are repeated across layers: inbound/http/handlers.go redefines maxFieldLen, maxReasonLen and maxInt32 that already exist as label.MaxReason / label.MaxPackageNo in internal/domain/label/label.go.
- IssueLabelCmd.validate runs label.Issue with placeholder ref, tracking number and stopKey just to reuse validation (internal/application/usecases/labels.go:36-49); it works but is indirect and couples the command to aggregate internals.
- internal/adapters/inbound/kafka/handlers.go (348 lines) holds payload DTOs and mapping for four producers in one file; splitting per producer would ease review.
APIs and contracts
- Good: every POST requires an Idempotency-Key with 24h replay (apis/openapi.yaml components.parameters.IdempotencyKey); errors are RFC 9457 problem+json with one slug per domain error and documented 409/422/503 cases.
- Good: resource model is small and clear (/labels, /journeys/{trackingNumber}/scans) with an AIP-style custom method POST /labels/{labelRef}:void that is documented as idempotent on repeat.
- Missing: no URL or media-type versioning (spec 0.1.0, unprefixed paths) and no ETag/If-Match, so clients cannot do conditional updates; concurrent-update 409 is server-side only.
- Events: 8 CloudEvents types named com.retailnetwork.logistics.shipping-and-tracking.<entity>.<Event> with versioned dataschema URNs (:v1) and required envelope fields in apis/asyncapi.yaml; MCP get_journey is annotated read-only.
REST: 4 operations (1 read, 3 write, 3 of 3 writes require Idempotency-Key)
| POST | /labels | Issue a shipping label for one package (IssueLabel) |
| POST | /labels/{labelRef}:void | Void an issued label (VoidLabel) |
| GET | /journeys/{trackingNumber} | Get the journey of one package (GetJourney) |
| POST | /journeys/{trackingNumber}/scans | Record one scan on a package journey (RecordScan) |
Events published: 8 types on retailnetwork.shipping-and-tracking.events
- journey.PackageDelivered
- journey.PackageExceptionRaised
- journey.PackageHandedOver
- journey.PackageLost
- journey.PackageReturned
- journey.PackageScanned
- label.LabelIssued
- label.LabelVoided
Events consumed: 7 types from 4 topics
retailnetwork.last-mile-delivery.events, retailnetwork.linehaul-transportation.events, retailnetwork.offer-availability.events, retailnetwork.vendor-connectivity.events
- catalogitem.CatalogItemCreated offer-availability
- packageattempthistory.PackageReturnInitiated last-mile-delivery
- route.DeliveryAttempted last-mile-delivery
- route.PackageOutForDelivery last-mile-delivery
- load.LoadArrived linehaul-transportation
- load.LoadDeparted linehaul-transportation
- purchaseorder.VendorShipmentConfirmed vendor-connectivity
MCP tools: 1 (1 read-only)
get_journey | read | Read the customer-visible journey of one package by tracking number: the state (LABELLED, HANDED_OVER, IN_TRANSIT, AT_STATION, OUT_FOR_DELIVERY, DELIVERED, RETURNED, LOST or VOIDED), the poNumber, assignmentId, orderId a |
A2A skills: 1
Recommended next steps
- Add a circuit breaker (or a cached ship-to read model fed by customer-ordering events) in front of GetShipTo so label issuance degrades gracefully.
- Agree one PackageReturnInitiated type with last-mile-delivery and drop the alias in inbound/kafka/handlers.go.
- Expose domain bounds as the single source for HTTP validation and introduce a /v1 prefix or versioned media type before external consumers grow.
Measured at origin/develop b6cd04d (2026-10-30). Review sampled 8 files.
Architecture
Clean code
API design
Rich, well-guarded sourcing aggregate fed entirely by 30+ consumed event types; main risks are full-table world loads per search and a thin, unpaginated REST surface.
Fleet classifies it Core: it sets cost-to-serve and protects the speed promise, with rules specific to this network.
- Production code
- 11,131 lines Go in 85 files, 29 packages
- Tests
- 14,275 lines, 352 test functions, 7 integration files, 45 BDD scenarios, 33 fitness tests
- Function size
- avg 10.3 lines (p95 30), 2 over 60 lines
- Complexity
- avg cyclomatic 2.8; highest WorldReader.Load (15), checkCommitted (14)
- Layering
- 0 infrastructure imports in domain/application; 4 domain packages
- Quality gates
- coverage 90%, mutation efficacy 95%, 17 CI jobs
- Persistence
- PostgreSQL, 1 migrations, 14 tables
- Deployables
- a2a, api, mcp
- Largest files
- none over 500 lines
- Console remote (web/)
- 1,467 lines TS/TSX, 6 test files
- Decisions
- 9 ADRs, 13 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 3 binaries (API, MCP, A2A); Postgres + outbox; 10 read models projected from 8 upstream topics
Strengths
- Assignment aggregate (internal/domain/assignment/assignment.go) validates promise, lines and candidates (excluded node, eta <= deliverByLatest); search is a pure domain package (internal/domain/sourcing).
- Sourcing decisions read only local rm_* projections (internal/adapters/outbound/postgres/world.go), so placing an order never calls node-topology, linehaul or offer-availability synchronously.
- QueueAssignment claims the event in the inbox and commits all groups in one transaction; a replayed CustomerOrderPlaced is a no-op (internal/application/usecases/queue.go execute/claim).
- Custom OTel metrics for sourcing outcomes exist (internal/adapters/outbound/telemetry/sourcing_metrics.go) alongside tracing.
Concerns
- WorldReader.Load reads whole rm_nodes, rm_lanes, departures, scorecards and pressure tables for every group search, inside the write transaction (postgres/world.go:39-48); cost grows with network size and order fan-out.
- The world loads run sequentially (postgres/world.go:49-53) on one transaction; with 8 queries per group, a multi-group order holds its transaction for 8xN round trips.
- Endpoints are unauthenticated by fleet decision; POST /assignments/{id}:reoptimise changes which vendor node fulfils an order (apis/openapi.yaml).
Clean code
Strengths
- 11.1k prod LOC, avg 10.3 lines/function, p95 30, avg cyclomatic 2.8, no function over the cyclo cap; mutation efficacy gate is 95%, the highest sampled.
- Golden tests pin the CloudEvents encoding (internal/adapters/outbound/kafka/golden_test.go) and a repository contract suite runs against memory and Postgres.
- 45 BDD scenarios and 33 fitness tests; use cases follow one Execute -> execute -> recordOutcome pattern consistently (usecases/queue.go).
Concerns
- releaseNow discards the error of sourcing.ResolveLines (`lines, _ :=` in internal/application/usecases/queue.go:100), relying on a comment that the search only returns nodes that ship every line.
- The Assignment root carries 21 fields spanning queueing, release, shipping and delivery (internal/domain/assignment/assignment.go:12-35); lifecycle phases could be value objects.
- Handlers.NodeTopology in internal/adapters/inbound/kafka/handlers.go is 64 lines, one of two functions over 60 lines.
APIs and contracts
- Good: errors are problem+json with model slugs; POST /assignments/{id}:reoptimise takes an Idempotency-Key with 24h replay and is allowed only while QUEUED (apis/openapi.yaml lines 101-181).
- Missing: GET /assignments has only limit (max 500) and no cursor/after, so clients cannot page past the first 500 matches (apis/openapi.yaml lines 32-66).
- Missing: no ETag/If-Match and no API versioning (0.1.0); the REST surface is read-mostly with one command, since assignments are created from events.
- Events: 8 integration + 2 analytics CloudEvents types under com.retailnetwork.commerce.order-sourcing.assignment.*; consumed type aliases are tested (inbound/kafka/aliases_test.go).
REST: 3 operations (2 read, 1 write, 1 of 1 writes require Idempotency-Key)
| GET | /assignments | List fulfillment assignments (ListAssignments) |
| GET | /assignments/{assignmentId} | Get one fulfillment assignment (GetAssignment) |
| POST | /assignments/{assignmentId}:reoptimise | Re-optimise a queued assignment now (ReoptimiseAssignment) |
Events published: 10 types on retailnetwork.order-sourcing.analytics, retailnetwork.order-sourcing.events
- assignment.FulfillmentCancelRefused
- assignment.FulfillmentCancelled
- assignment.FulfillmentConstraintRevised
- assignment.FulfillmentDelivered
- assignment.FulfillmentLocked
- assignment.FulfillmentQueued
- assignment.FulfillmentReassigned
- assignment.FulfillmentReleasedToNode
- assignment.FulfillmentShipped
- assignment.FulfillmentUnsourceable
Events consumed: 32 types from 9 topics
retailnetwork.customer-ordering.events, retailnetwork.delivery-promise.events, retailnetwork.last-mile-delivery.events, retailnetwork.linehaul-transportation.events, retailnetwork.node-performance.events, retailnetwork.node-topology.events, retailnetwork.offer-availability.events, retailnetwork.shipping-and-tracking.events, retailnetwork.vendor-connectivity.events
- customerorder.CustomerOrderCancelled customer-ordering
- customerorder.CustomerOrderPlaced customer-ordering
- promise.PromiseRevised delivery-promise
- promisebook.PromiseBookExhausted delivery-promise
- catalogitem.CatalogItemDiscontinued offer-availability
- listing.ListingAvailabilityChanged offer-availability
- listing.ListingCreated offer-availability
- listing.ListingRestored offer-availability
- listing.ListingSuppressed offer-availability
- wave.DeliveryWaveCancelled last-mile-delivery
- wave.DeliveryWaveCapacityChanged last-mile-delivery
- wave.DeliveryWaveScheduled last-mile-delivery
- departure.BookingFailed linehaul-transportation
- departure.BookingMoved linehaul-transportation
- departure.DepartureCancelled linehaul-transportation
- departure.DepartureCapacityChanged linehaul-transportation
- departure.DepartureScheduled linehaul-transportation
- lane.LaneClosed node-topology
- lane.LaneOpened node-topology
- node.NodeActivated node-topology
- node.NodeOperationalProfileDeclared node-topology
- node.NodeRegistered node-topology
- node.NodeRetired node-topology
- node.NodeSuspended node-topology
- region.RegionDefined node-topology
- servicearea.ServiceAreaAssigned node-topology
- journey.PackageDelivered shipping-and-tracking
- scorecard.NodeScorecardUpdated node-performance
- purchaseorder.PurchaseOrderAccepted vendor-connectivity
- purchaseorder.PurchaseOrderExpired vendor-connectivity
- purchaseorder.PurchaseOrderRejected vendor-connectivity
- purchaseorder.VendorShipmentConfirmed vendor-connectivity
MCP tools: 2 (2 read-only)
list_assignments | read | List fulfillment assignments, ordered by assignmentId ascending: which vendor node and path will fulfil each shipment group of a customer order, in which state (QUEUED, RELEASED, LOCKED, SHIPPED, DELIVERED, UNSOURCEABLE, |
get_assignment | read | Read one fulfillment assignment in full by id: the promise constraint it must keep (tier, deliverByLatest, witness node), its lines, the current candidate node and path with the cost in cost points, the VirtualQueue rele |
A2A skills: 2
- Explain one fulfillment assignment
- Find fulfillment assignments
Recommended next steps
- Scope WorldReader.Load to the destination region/lanes and load once per order (not per group), or cache static topology outside the transaction.
- Add keyset pagination (after/nextCursor) to GET /assignments, matching the offer-availability pattern.
- Handle the ResolveLines error explicitly in usecases/queue.go releaseNow instead of discarding it.
Measured at origin/develop affe65a (2026-10-30). Review sampled 5 files.
Architecture
Clean code
API design
Well-structured catalogue/listing context with rich, self-validating aggregates, per-node feed serialization and keyset-paged reads; contract naming and large single-transaction feeds are the main watch points.
Fleet classifies it Supporting: necessary and specific, but a well-understood listings-per-node shape.
- Production code
- 12,275 lines Go in 95 files, 32 packages
- Tests
- 15,973 lines, 415 test functions, 9 integration files, 64 BDD scenarios, 35 fitness tests
- Function size
- avg 10.0 lines (p95 27), 1 over 60 lines
- Complexity
- avg cyclomatic 2.8; highest checkOutcome (15), checkSnapshot (13)
- Layering
- 0 infrastructure imports in domain/application; 6 domain packages
- Quality gates
- coverage 90%, mutation efficacy 90%, 17 CI jobs
- Persistence
- PostgreSQL, 2 migrations, 9 tables
- Deployables
- a2a, api, mcp
- Largest files
- none over 500 lines
- Console remote (web/)
- 1,523 lines TS/TSX, 8 test files
- Decisions
- 10 ADRs, 14 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 4 aggregates; 3 binaries (API, MCP, A2A); Postgres + outbox to Kafka; node-topology events into a local view
Strengths
- Listing aggregate (internal/domain/listing/listing.go) encodes state machine, stale-asOf and negative-qty invariants with model-named errors, and Restore re-validates every persisted snapshot.
- Node sellability comes from a local NodeStatusView fed by node-topology events (internal/adapters/inbound/kafka/node_consumer.go), not a synchronous call, so listing writes have no runtime sibling dependency.
- ApplyInventoryFeed serializes feeds per node with SELECT ... FOR UPDATE on node_feed_marks (postgres/feed_repository.go Lock) and writes listings, mark, feed and outbox in one unit of work.
- Outbox relay claims rows with FOR UPDATE SKIP LOCKED (postgres/outbox_repository.go Drain); every UPDATE is version-guarded for optimistic concurrency.
Concerns
- A full feed loads every listing of the node plus all line listings and saves them in one transaction under the node lock (usecases/feeds.go loadListings, postgres/listing_repository.go SaveMany); large nodes mean long-held locks and big outbox bursts.
- A FAILED feed is committed but surfaced as an error alongside a view (usecases/feeds.go outcome.failure), a dual-return convention the HTTP adapter must special-case (inbound/http/handlers.go applyInventoryFeed keepWrites).
- Endpoints are unauthenticated by fleet decision (apis/openapi.yaml info.description) although POST /inventory-feeds changes sellable stock network-wide.
Clean code
Strengths
- 12.3k prod LOC with avg 10 lines/function, p95 27, avg cyclomatic 2.8 and no function over cyclo 15; no file over 500 lines.
- Tests outweigh code (16k test LOC, 415 test funcs, a fuzz test, 64 BDD scenarios, 35 fitness tests) with 90% coverage and mutation gates.
- Use cases read as a narrative of small steps (attempt, receive, settle, commit in usecases/feeds.go), each documented against ADR 0002 clauses.
- GS1 GTIN/SSCC check-digit logic is isolated in its own domain package (internal/domain/shared/gs1) with dedicated tests.
Concerns
- checkOutcome in internal/domain/feed/feed.go sits exactly at the cyclomatic cap (15); further rules will push it over.
- Validation is split between handler and command: applyInventoryFeed checks FullUpdate/Lines for nil in internal/adapters/inbound/http/handlers.go:172 while the rest happens in feed.NewSubmission.
APIs and contracts
- Good: all writes are wrapped by an Idempotency-Key middleware (s.keyed in inbound/http/handlers.go), errors are RFC 9457 with one slug per model error, and AIP-style custom methods (:discontinue, :retire) model transitions.
- Good: collection reads use keyset pagination (limit/after) on GET /catalog and GET /listings; PUT on /packaging/{level} is a natural idempotent upsert with immutability rules documented.
- Inconsistent: writes live under /catalog-items but reads under /catalog/{catalogItemId}; one resource has two URL roots. No path/media-type versioning (0.1.0) and no ETag/If-Match.
- Events: 9 CloudEvents types under com.retailnetwork.commerce.offer-availability.<entity>.<Event>; MCP tools are read-only lookups (browse_catalog, list_listings, get_inventory_feed).
REST: 10 operations (4 read, 6 write, 6 of 6 writes require Idempotency-Key)
| POST | /catalog-items | Create a catalogue item (CreateCatalogItem) |
| POST | /catalog-items/{catalogItemId}:discontinue | Discontinue a catalogue item (DiscontinueItem) |
| PUT | /catalog-items/{catalogItemId}/packaging/{level} | Declare a pack level of a catalogue item (DeclarePackLevel) |
| POST | /catalog-items/{catalogItemId}/packaging/{level}:retire | Retire the active pack level of a catalogue item (RetirePackLevel) |
| GET | /catalog | Browse the catalogue (BrowseCatalog) |
| GET | /catalog/{catalogItemId} | Get one catalogue item (BrowseCatalog) |
| POST | /listings | Create a listing (CreateListing) |
| GET | /listings | List listings by node and/or catalogue item |
| POST | /inventory-feeds | Apply an inventory feed for one node (ApplyInventoryFeed) |
| GET | /inventory-feeds/{feedId} | Get one inventory feed and its outcome |
Events published: 9 types on retailnetwork.offer-availability.events
- catalogitem.CatalogItemCreated
- catalogitem.CatalogItemDiscontinued
- catalogitem.CatalogItemPackLevelRetired
- catalogitem.CatalogItemPackagingDeclared
- inventoryfeed.InventoryFeedApplied
- listing.ListingAvailabilityChanged
- listing.ListingCreated
- listing.ListingRestored
- listing.ListingSuppressed
Events consumed: 4 types from 1 topics
retailnetwork.node-topology.events
- node.NodeActivated node-topology
- node.NodeRegistered node-topology
- node.NodeRetired node-topology
- node.NodeSuspended node-topology
MCP tools: 4 (4 read-only)
browse_catalog | read | Browse the catalogue of sellable items, one keyset page at a time (catalogItemId ascending): each item's title, dimensions in mm (lengthMm, widthMm, heightMm), weightG, its hazmat and fragile flags and its state (ACTIVE, |
get_catalog_item | read | Read one catalogue item by id: title, dimensions in mm (lengthMm, widthMm, heightMm), weightG, the hazmat and fragile flags, its state (ACTIVE, or DISCONTINUED), the GS1 identifiers it carries (identifiers.gtin) when it |
list_listings | read | List which nodes sell what, one keyset page at a time (listingId ascending), optionally narrowed to one node (nodeId) and/or one catalogue item (catalogItemId) |
get_inventory_feed | read | Read one vendor inventory feed and its outcome by id: the node it was sent for (nodeId), whether it was a fullUpdate, its asOf, and its state APPLIED, SUPERSEDED or FAILED with the counters (lineCount, appliedCount, stal |
A2A skills: 2
- Check where an item is sold and how much is available
- Read the outcome of one vendor inventory feed
Recommended next steps
- Unify catalogue item URLs (GET /catalog-items/{id} alongside the storefront /catalog browse alias) and introduce a version prefix before external adoption.
- Chunk or cap full-feed application (or stream zeroing) so per-node lock time and outbox batch size stay bounded.
- Replace the view-plus-error return for FAILED feeds with an explicit result type to remove the HTTP special case.
Measured at origin/develop 22137e9 (2026-10-30). Review sampled 7 files.
Architecture
Clean code
API design
The fleet's most intricate context, well executed: rich Promise state machine, capacity books, idempotent APIs and sweeper-backed recovery; its breadth (37 consumed event types) and a 75% mutation gate are watch points.
Fleet-network docs classify it Core: the date every shopper sees, built on the network's own nodes, cutoffs and capacity.
- Production code
- 14,369 lines Go in 92 files, 33 packages
- Tests
- 16,075 lines, 374 test functions, 10 integration files, 42 BDD scenarios, 31 fitness tests
- Function size
- avg 10.1 lines (p95 29), 2 over 60 lines
- Complexity
- avg cyclomatic 2.9; highest Service.ReviseAtRisk (15), Service.makePromise (15)
- Layering
- 0 infrastructure imports in domain/application; 7 domain packages
- Quality gates
- coverage 90%, mutation efficacy 75%, 17 CI jobs
- Persistence
- PostgreSQL, 2 migrations, 20 tables
- Deployables
- a2a, api, mcp
- Largest files
- internal/domain/promise/promise.go (670), internal/application/usecases/projections.go (531)
- Console remote (web/)
- 1,596 lines TS/TSX, 8 test files
- Decisions
- 11 ADRs, 15 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 3 binaries (API+consumer+sweeper, MCP, A2A) + MF web remote; Postgres + outbox; 15 local read models
Strengths
- Promise aggregate documents its 7-state transition table and five named invariants in the package header (internal/domain/promise/promise.go:1-44).
- MakePromise consumes the offer, holds book capacity and appends events to the outbox in one transaction; the multi-aggregate write is an explicit, documented exception (G22) in usecases/make_promise.go:33-36.
- Self-healing: post-commit re-promises that fail are left to a clock-driven sweeper (RepriceAtRisk, ExpireOffers, ReleaseExpiredHolds, CloseBooks in cmd/api/workers.go), each pass isolated from the others' failures.
- Inbox-deduplicated consumers (Service.consume in usecases/projections.go:23-39) build local read models (rm_* tables) instead of calling siblings synchronously at quote time.
Concerns
- Very wide upstream coupling: 37 consumed event types across 8 topics feed 15 rm_* tables (apis/asyncapi.yaml, usecases/projections.go at 531 lines); any producer contract change lands here.
- MakePromise writes offer, PromiseBook and promise in one transaction (make_promise.go:101-110); a popular node/departure book becomes a hot row under checkout bursts, surfacing as 409 concurrent-update.
- Quote, promise and policy routes are unauthenticated by fleet decision, so anyone can publish a new promise policy via POST /promise-policies (apis/openapi.yaml).
Clean code
Strengths
- 788 funcs, avg 10.1 lines, p95 29, none over cyclomatic 15; error sentinels named after the model's invariants with their HTTP status in comments (promise.go:29-44).
- Use-case flow in makePromise reads top to bottom (load, replay check, consume, revalidate, hold, make, save) with the save sequence as a small slice of closures.
- Tests: 16k test LOC vs 14.4k prod, 42 BDD scenarios incl. sweeper steps, 10 integration files, repocontract suite, 31 fitness tests.
Concerns
- Mutation efficacy gate is 75% (.gremlins.yaml:41, weakest package search at 77.8%) versus 95-99% in sibling contexts.
- Two files exceed 500 lines: internal/domain/promise/promise.go (669) and internal/application/usecases/projections.go (530); three functions sit at the cyclomatic cap of 15 (ReviseAtRisk, makePromise, validateQuote).
- All use cases hang off one usecases.Service type (make_promise.go, risk.go, projections.go), which widens its dependency set and test fixtures.
APIs and contracts
- POST /promises requires Idempotency-Key, returns 201 + Location on create and 200 on replay, and enumerates every problem type per status (apis/openapi.yaml:84-127).
- Lifecycle commands are clear custom methods (/delivery-offers:quote, /promises/{id}:confirm, :cancel); terminal promises stay readable and offers carry expiresAt.
- List endpoints (GET /promises?orderId, /promise-books?nodeId&date) are unpaginated; acceptable for bounded per-order data but not for node books. Spec is 0.2.0 with no URI versioning.
- Events split integration (6 types on ...delivery-promise.events) from analytics (6 types on ...analytics), with consistent com.retailnetwork.commerce.delivery-promise.<aggregate>.<Type> naming.
REST: 10 operations (5 read, 5 write, 5 of 5 writes require Idempotency-Key)
| POST | /delivery-offers:quote | Quote delivery offers per tier for a destination and a set of lines |
| GET | /delivery-offers/{offerId} | Get one delivery offer |
| POST | /promises | Make a provisional promise for one shipment group from a quoted offer |
| GET | /promises | List the promises of one customer order |
| GET | /promises/{promiseId} | Get one promise with its terms, witness path, revisions and judgement |
| GET | /promise-books | List the promise books of one node for one date |
| POST | /promises/{promiseId}:confirm | Confirm a provisional promise for a placed order (ConfirmPromise) |
| POST | /promises/{promiseId}:cancel | Cancel a confirmed promise on request (CancelPromise) |
| POST | /promise-policies | Publish a new promise policy version (PublishPromisePolicy) |
| GET | /promise-policies/current | Get the current promise policy |
Events published: 12 types on retailnetwork.delivery-promise.analytics, retailnetwork.delivery-promise.events
- deliveryoffer.DeliveryOfferQuoted
- promise.PromiseAtRisk
- promise.PromiseBroken
- promise.PromiseCancelled
- promise.PromiseConfirmed
- promise.PromiseKept
- promise.PromiseMade
- promise.PromiseReleased
- promise.PromiseRevised
- promise.PromiseUnkeepable
- promisebook.PromiseBookExhausted
- promisepolicy.PromisePolicyPublished
Events consumed: 34 types from 8 topics
retailnetwork.customer-ordering.events, retailnetwork.last-mile-delivery.events, retailnetwork.linehaul-transportation.events, retailnetwork.node-performance.events, retailnetwork.node-topology.events, retailnetwork.offer-availability.events, retailnetwork.order-sourcing.events, retailnetwork.shipping-and-tracking.events
- customerorder.CustomerOrderCancelled customer-ordering
- customerorder.CustomerOrderPlaced customer-ordering
- catalogitem.CatalogItemCreated offer-availability
- catalogitem.CatalogItemDiscontinued offer-availability
- listing.ListingAvailabilityChanged offer-availability
- listing.ListingCreated offer-availability
- listing.ListingRestored offer-availability
- listing.ListingSuppressed offer-availability
- assignment.FulfillmentLocked order-sourcing
- assignment.FulfillmentShipped order-sourcing
- assignment.FulfillmentUnsourceable order-sourcing
- packageattempthistory.PackageInductionDeferred last-mile-delivery
- wave.DeliveryWaveCancelled last-mile-delivery
- wave.DeliveryWaveCapacityChanged last-mile-delivery
- wave.DeliveryWaveScheduled last-mile-delivery
- departure.BookingFailed linehaul-transportation
- departure.BookingMoved linehaul-transportation
- departure.DepartureCancelled linehaul-transportation
- departure.DepartureCapacityChanged linehaul-transportation
- departure.DepartureScheduled linehaul-transportation
- lane.LaneClosed node-topology
- lane.LaneOpened node-topology
- node.NodeActivated node-topology
- node.NodeOperationalProfileDeclared node-topology
- node.NodeRegistered node-topology
- node.NodeRetired node-topology
- node.NodeSuspended node-topology
- region.RegionDefined node-topology
- servicearea.ServiceAreaAssigned node-topology
- journey.PackageDelivered shipping-and-tracking
- journey.PackageExceptionRaised shipping-and-tracking
- journey.PackageLost shipping-and-tracking
- journey.PackageReturned shipping-and-tracking
- scorecard.NodeScorecardUpdated node-performance
MCP tools: 5 (5 read-only)
get_delivery_offer | read | Read one delivery offer in any state (QUOTED, EXPIRED or CONSUMED): its tier, groupNo, destination postal prefix, lines, delivery window (earliest, latest and the delivery station's IANA timeZone, the local calendar of i |
get_promise | read | Read one promise in any state (PROVISIONAL, CONFIRMED, AT_RISK, KEPT, BROKEN, RELEASED or CANCELLED): its terms (tier, shipBy, deliverByEarliest, deliverByLatest, timeZone, basis, policyVersion), the witness path, holdEx |
list_promises_by_order | read | List the promises of one customer order, one per shipment group, ordered by groupNo: each with its state, terms, witness path and judgement (the same shape as get_promise) |
list_promise_books | read | List the capacity ledger books of one fulfillment node whose pickup cutoff falls on one date (YYYY-MM-DD in the node's own time zone), ordered by cutoffAt: one book per cutoff (bookId is nodeId:pickupDepartureId), its OP |
get_current_policy | read | Read the current promise policy: policyVersion (v0 is the built-in default when nothing was published), offerTtlMinutes and holdTtlMinutes, packagesPerOrder, capacitySharePercent and the per-tier order deadlines (localTi |
A2A skills: 2
- Promise book capacity of a node on a date
- Status of the delivery promises of an order
Recommended next steps
- Raise the mutation efficacy gate toward the fleet's 95% by strengthening assertions in the search package first.
- Load-test MakePromise on a single hot PromiseBook and consider sharded or counter-based capacity holds if 409 rates climb.
- Split projections.go per upstream topic and add consumer-driven contract tests for the 8 upstream event streams.
Measured at origin/develop 439c7b0 (2026-10-30). Review sampled 6 files.
Digital Storefront 9 applications
Architecture
Clean code
API design
Compact, disciplined purchase-saga context: explicit state machine, keyed idempotency on every hop and an outbox, but it orchestrates five sibling contexts synchronously with no circuit breaker.
Classified Supporting, custom-built: it conducts the purchase, while price, payment and order live in neighbours.
- Production code
- 9,540 lines Go in 97 files, 36 packages
- Tests
- 10,336 lines, 291 test functions, 8 integration files, 34 BDD scenarios, 31 fitness tests
- Function size
- avg 9.7 lines (p95 27), 1 over 60 lines
- Complexity
- avg cyclomatic 2.7; highest checkStateFields (12), checkRequired (11)
- Layering
- 0 infrastructure imports in domain/application; 2 domain packages
- Quality gates
- coverage 90%, mutation efficacy 95%, 15 CI jobs
- Persistence
- PostgreSQL, 1 migrations, 3 tables
- Deployables
- a2a, api, mcp
- Largest files
- none over 500 lines
- Decisions
- 8 ADRs, 10 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD saga orchestrator; 3 binaries (API, MCP, A2A); Postgres + outbox to Kafka; scheduler for stuck/in-doubt recovery
Strengths
- CheckoutSession aggregate encodes the saga as guarded transitions (require(...) in internal/domain/checkoutsession/transitions.go) with PLACING as a semantic lock and an authorization-mismatch void path.
- Every outbound call carries a deterministic Idempotency-Key (<sessionId>:auth:<attempt> in internal/application/usecases/confirm_session.go), so stuck authorizations and in-doubt placements replay safely.
- Unknown outcomes are first-class: the session stays AUTHORIZING/PLACING, the API answers 202, and a scheduler adapter (internal/adapters/inbound/scheduler/scheduler.go) resolves with backoff and 20h/22h alert/give-up.
- Domain free of infrastructure (no layer violations, no time.Now/uuid in domain per facts); 31 fitness tests incl. runtime_no_memory and DLQ-shutdown checks.
Concerns
- OpenSession and ConfirmSession call shopping-cart, delivery-promise, pricing, customer-payments and customer-ordering synchronously; internal/adapters/outbound/httpx/httpx.go has only a 5s timeout, no circuit breaker or bulkhead.
- Consumes no events (AsyncAPI consumed is empty), so cart/price/offer changes after OpenSession are only detected by re-reading siblings at confirm time.
- REST/MCP are unauthenticated by fleet decision, which matters most here: POST /checkout-sessions/{id}:confirm triggers payment authorization (apis/openapi.yaml).
Clean code
Strengths
- Small, focused code: 9.5k prod LOC, average function 9.7 lines, p95 27, average cyclo 2.7, only 1 function over 60 lines and no file over 500 lines (facts).
- Use cases read as the saga narrative: ConfirmSession.execute -> authorize -> recordAuthorization -> place (internal/application/usecases/confirm_session.go) with short, well-named helpers.
- Repository contract suite (internal/adapters/outbound/repocontract/) runs the same behavioural tests against memory and Postgres adapters; 34 BDD scenarios, 90% coverage and 95% mutation-efficacy gates.
Concerns
- Restore validation concentrates the highest complexity (checkStateFields cyclo 12, checkRequired cyclo 11 in internal/domain/checkoutsession/restore.go); a table-driven check would read better.
- recordAuthorization uses a captured mismatch flag mutated inside a closure (internal/application/usecases/confirm_session.go:86-110), a subtle control-flow pattern worth a dedicated return type.
APIs and contracts
- Good: Idempotency-Key declared as a shared parameter on every write, RFC 9457 problem types with stable slugs (not-found, illegal-transition, concurrent-update, validation-failed) and 202 for unknown outcomes.
- Good: AIP-style custom method POST /checkout-sessions/{sessionId}:confirm models the intent cleanly; the session view exposes version and quoteExpiresAt.
- Gap: optimistic concurrency is internal only (no ETag/If-Match in apis/openapi.yaml); spec version is 0.1.0 with no path or media-type versioning; no list/search endpoint.
- Events: AsyncAPI 3.0 with one integration event (CheckoutCompleted) separated from six analytics events; CloudEvents types com.retailnetwork.storefront.checkout.checkoutsession.*.
REST: 3 operations (1 read, 2 write, 2 of 2 writes require Idempotency-Key)
| POST | /checkout-sessions | Open a checkout session for a cart |
| GET | /checkout-sessions/{sessionId} | Get a checkout session |
| POST | /checkout-sessions/{sessionId}:confirm | Confirm the session with a payment method token |
Events published: 7 types on retailnetwork.checkout.analytics, retailnetwork.checkout.events
- checkoutsession.CheckoutCompleted
- checkoutsession.CheckoutDeclined
- checkoutsession.CheckoutFailed
- checkoutsession.CheckoutOpened
- checkoutsession.CheckoutPlacementInDoubt
- checkoutsession.CheckoutRequoteRequired
- checkoutsession.CheckoutSessionExpired
MCP tools: 1 (1 read-only)
get_checkout_session | read | Read a checkout session by id: its state (OPEN, AUTHORIZING, DECLINED, PLACING, REQUOTE_REQUIRED, COMPLETED, EXPIRED or FAILED), the cart and shopper references, the numbered lines and shipment groups (groupNo, offerId, |
A2A skills: 1
- Where does a checkout session stand
Recommended next steps
- Add a circuit breaker and per-sibling bulkhead in internal/adapters/outbound/httpx so one slow sibling cannot exhaust checkout capacity.
- Expose session version as an ETag and accept If-Match on :confirm to make client-side concurrency explicit.
- Consider consuming pricing/cart change events to invalidate open sessions early instead of failing at confirm.
Measured at origin/develop e95e5ea (2026-10-30). Review sampled 5 files.
Architecture
Clean code
API design
A mature order aggregate with explicit invariants, outbox publishing, idempotent checkout and saga-style promise compensation; the main risk is best-effort compensation and an unauthenticated PII route.
Classified Generic, commodity: cart-to-order is common commerce, kept thin; it also confines shopper PII.
- Production code
- 12,620 lines Go in 90 files, 33 packages
- Tests
- 16,139 lines, 404 test functions, 12 integration files, 59 BDD scenarios, 34 fitness tests
- Function size
- avg 11.3 lines (p95 29), 2 over 60 lines
- Complexity
- avg cyclomatic 3.1; highest testListByShopper (15), checkGroupSnapshot (14)
- Layering
- 0 infrastructure imports in domain/application; 4 domain packages
- Quality gates
- coverage 90%, mutation efficacy 98%, 17 CI jobs
- Persistence
- PostgreSQL, 4 migrations, 11 tables
- Deployables
- a2a, api, mcp
- Largest files
- none over 500 lines
- Console remote (web/)
- 1,441 lines TS/TSX, 7 test files
- Decisions
- 9 ADRs, 13 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 3 binaries (API, MCP, A2A) + MF web remote; Postgres + outbox to Kafka; sync calls to delivery-promise
Strengths
- CustomerOrder aggregate documents and enforces named invariants (ErrLineWithoutPromise, ErrPromiseDestinationMismatch, ErrCancelAfterLock, ErrStatusRegression) in internal/domain/customerorder/order.go.
- PlaceOrder saves the order and CustomerOrderPlaced in one unit of work via the outbox (usecases/checkout.go transact + publish); relay in adapters/outbound/outbox/relay.go.
- Checkout is a careful two-phase promise: make all, validate against the aggregate, then confirm; failed confirms trigger compensating cancels detached from request cancellation (checkout.go:200-259).
- Downstream calls carry derived Idempotency-Keys (<orderId>:<groupNo>[:confirm|:cancel]) and a 5s timeout (adapters/outbound/deliverypromise/gateway.go), so checkout retries reuse promises.
Concerns
- Compensation is best effort: a failed CancelPromise is only logged and the capacity hold stays at delivery-promise (usecases/checkout.go:251-254); no durable retry or outbox entry for it.
- Checkout is synchronously coupled to delivery-promise with sequential per-group make/confirm calls (checkout.go:202-219); with MaxGroups=50 and a 5s timeout per call, latency is unbounded in practice.
- GET /orders/{orderId}/ship-to and MCP get_ship_to return the delivery address (PII) while REST/MCP are unauthenticated by fleet decision (internal/adapters/inbound/mcp/tools.go:283).
Clean code
Strengths
- 598 funcs, avg 11.3 lines, p95 29, none over cyclomatic 15; PlaceOrder.execute reads as a linear pipeline of small named steps (checkAddressChoice, replay, preflight, promiseGroups).
- Comments trace rules to ADR ids (ADR 0002 A13/A14/A25, NG1), keeping code and decisions aligned.
- Strong test portfolio: test LOC 16.1k vs prod 12.6k, 59 BDD scenarios in 8 features, 12 integration files, 34 fitness tests, 98% mutation gate, shared repocontract suite.
Concerns
- Go module path is github.com/claudioed/customer-ordering (internal/application/usecases/checkout.go imports) while the repo lives in the IQVO org; inconsistent with sibling repos such as product-discovery.
- preflight builds a throw-away order with placeholder 'pending' promises to reuse Place validation (usecases/checkout.go:145-159); clever but couples validation to construction and is easy to misread.
- Web remote (web/, 1.4k LOC) has 7 test files and no e2e specs, much thinner than the Go side.
APIs and contracts
- 12 operations in apis/openapi.yaml with Idempotency-Key on POST /checkout, :cancel and address writes, documented idempotency-key-required / idempotency-key-reused problem types (RFC 9457).
- Order history uses keyset pagination (limit default 20, max 100, opaque after); 409 cancel-after-lock / status-regression / concurrent-update make concurrency outcomes explicit.
- Mixed resource style: RPC-ish POST /checkout and Google-style custom method /orders/{orderId}:cancel alongside plain resources; spec version 0.1.0 and no URI/media-type versioning.
- Events follow com.retailnetwork.commerce.customer-ordering.customerorder.<Type>; publishes 2 types and consumes 17 across 3 topics, all declared in apis/asyncapi.yaml.
REST: 12 operations (8 read, 4 write, 4 of 4 writes require Idempotency-Key)
| POST | /checkout | Place a customer order, promising and confirming every shipment group |
| GET | /orders | List a shopper's order history, newest first |
| GET | /orders/{orderId} | Get a customer order with its status and the promise per group |
| GET | /orders/{orderId}/tracking | Get the order's tracking view per shipment group and package |
| POST | /orders/{orderId}:cancel | Request the cancellation of every group that is not yet locked |
| GET | /orders/{orderId}/ship-to | Get the ship-to address of an order (restricted, label printing only) |
| GET | /shoppers | Find a shopper by e-mail |
| POST | /shoppers | Register a synthetic shopper |
| GET | /shoppers/{shopperId} | Get a shopper profile with its saved addresses |
| POST | /shoppers/{shopperId}/addresses | Save an address on a shopper |
| GET | /healthz | Liveness probe |
| GET | /readyz | Readiness probe |
Events published: 2 types on retailnetwork.customer-ordering.events
- customerorder.CustomerOrderCancelled
- customerorder.CustomerOrderPlaced
Events consumed: 17 types from 3 topics
retailnetwork.delivery-promise.events, retailnetwork.order-sourcing.events, retailnetwork.shipping-and-tracking.events
- promise.PromiseAtRisk delivery-promise
- promise.PromiseBroken delivery-promise
- promise.PromiseKept delivery-promise
- promise.PromiseRevised delivery-promise
- promise.PromiseUnkeepable delivery-promise
- assignment.FulfillmentCancelRefused order-sourcing
- assignment.FulfillmentCancelled order-sourcing
- assignment.FulfillmentLocked order-sourcing
- assignment.FulfillmentShipped order-sourcing
- assignment.FulfillmentUnsourceable order-sourcing
- journey.PackageDelivered shipping-and-tracking
- journey.PackageExceptionRaised shipping-and-tracking
- journey.PackageLost shipping-and-tracking
- journey.PackageReturned shipping-and-tracking
- journey.PackageScanned shipping-and-tracking
- label.LabelIssued shipping-and-tracking
- label.LabelVoided shipping-and-tracking
MCP tools: 3 (3 read-only)
get_order | read | Read a placed customer order by id: its status (PLACED, IN_FULFILLMENT, PARTIALLY_SHIPPED, SHIPPED, PARTIALLY_DELIVERED, DELIVERED, LOST, RETURNED or CANCELLED), the shopper, the destination postal prefix and when it was |
get_order_tracking | read | Read how one order is travelling: for every shipment group its promise window (deliverByEarliest, deliverByLatest), its status (PROMISED, LOCKED, SHIPPED, DELIVERED, LOST, RETURNED, CANCELLATION_REQUESTED or CANCELLED), |
get_ship_to | read | Read the ship-to delivery address of one order (name, line1, line2, city, region, postalCode, countryCode, phone) |
A2A skills: 2
- Follow an order's delivery
- Look up a placed order
Recommended next steps
- Make promise compensation durable: enqueue failed CancelPromise calls in the outbox or a retry table instead of log-and-skip.
- Parallelise or batch per-group make/confirm calls to delivery-promise and set an overall checkout deadline.
- Restrict the ship-to PII route/tool at the gateway or network policy until authentication returns.
Measured at origin/develop db4bee5 (2026-10-30). Review sampled 5 files.
Architecture
Clean code
API design
Well-modelled payments context: allocation-level capture/release invariants, inbox-claimed event consumption with parking of early facts, keyed provider calls; an unauthenticated 'ops only' refund route is the key risk.
Classified Generic, commodity: fleet docs say buy a PSP. Money rules stay local; the provider sits behind a port.
- Production code
- 11,135 lines Go in 98 files, 33 packages
- Tests
- 11,362 lines, 316 test functions, 9 integration files, 13 BDD scenarios, 32 fitness tests
- Function size
- avg 10.3 lines (p95 28), 1 over 60 lines
- Complexity
- avg cyclomatic 2.8; highest testParked (13), AuthorizationRepository.Save (11)
- Layering
- 0 infrastructure imports in domain/application; 3 domain packages
- Quality gates
- coverage 90%, mutation efficacy 85%, 15 CI jobs
- Persistence
- PostgreSQL, 1 migrations, 7 tables
- Deployables
- a2a, api, mcp
- Largest files
- none over 500 lines
- Decisions
- 5 ADRs, 7 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 3 binaries (API, MCP, A2A); Postgres + outbox to Kafka; ACL to payment provider; event-driven capture/refund
Strengths
- PaymentAuthorization enforces per-allocation invariants (no over-capture, no capture after expiry, no release of captured) with idempotent no-op repeats (internal/domain/paymentauthorization/commands.go).
- Capture, release and refunds are driven by consumed events (FulfillmentShipped, PackageLost) not sync calls; each claims the CloudEvents id in the same unit of work (internal/application/usecases/consume.go:104).
- Out-of-order facts are parked and replayed on bind, dead-lettered with an alert after 24h and purged after 30d (internal/application/parked/parked.go; internal/application/usecases/consume.go:73-101).
- Payment provider sits behind an ACL with deterministic Idempotency-Keys and a 10s timeout (internal/adapters/outbound/paymentprovider/client.go).
Concerns
- POST /refunds is documented as 'ops only' (apis/openapi.yaml:163) yet the fleet has no authentication, so any network caller can request a manual refund; this needs at least network-level isolation.
- No circuit breaker on the provider ACL (internal/adapters/outbound/paymentprovider/client.go); a degraded PSP holds request goroutines for the full 10s timeout.
- Single migration holds all seven tables (facts: 1 migration), so schema evolution history starts now; future changes need disciplined additive migrations alongside the outbox and inbox tables.
Clean code
Strengths
- Compact and consistent: 11.1k prod LOC, average function 10 lines, p95 28, average cyclo 2.8, no file over 500 lines (facts).
- Domain commands read as the ubiquitous language (Capture, Release, Void, Expire, Reauthorize) with sentinel errors and small helpers like illegal() and releaseAt().
- Repository contract suite (internal/adapters/outbound/repocontract/) shared by memory and Postgres adapters; 32 fitness tests and 9 integration-tagged files.
Concerns
- Mutation gate is lower than siblings at 85% efficacy/coverage (facts) versus 95-98% in checkout and storefront-bff, for the context that moves money.
- Only 13 BDD scenarios in 3 feature files; none covers reauthorization or hold expiry (features/authorization.feature, capture_release.feature, refunds.feature), the paths most likely to lose money.
- Version increments are scattered across command methods (p.version++ in commands.go; Void relies on releaseAt), which is easy to miss when adding a command.
APIs and contracts
- Good: Idempotency-Key on every write, RFC 9457 problem types with a specific payment-provider-unavailable 503 that tells callers to retry with the same key (apis/openapi.yaml:77).
- Good: AIP-style :void custom method; resources (payment-authorizations, refunds) map cleanly to the two aggregates.
- Gap: list endpoints (GET /payment-authorizations, GET /refunds) have no pagination parameters; no ETag/If-Match despite versioned aggregates; spec version 0.1.0 with no versioning scheme.
- Events: AsyncAPI 3.0 with 8 produced events on one topic, CloudEvents types com.retailnetwork.storefront.customer-payments.<aggregate>.<Event>; consumed contracts from checkout, order-sourcing and shipping documented.
REST: 6 operations (3 read, 3 write, 3 of 3 writes require Idempotency-Key)
| POST | /payment-authorizations | Authorize the quote total of a checkout session |
| GET | /payment-authorizations | List authorizations by order or checkout session |
| GET | /payment-authorizations/{authorizationId} | Get one authorization with its allocations |
| POST | /payment-authorizations/{authorizationId}:void | Void an uncaptured authorization |
| POST | /refunds | Request a manual refund (ops only) |
| GET | /refunds | List refunds of an order |
Events published: 8 types on retailnetwork.customer-payments.events
- paymentauthorization.PaymentAuthorizationExpired
- paymentauthorization.PaymentAuthorized
- paymentauthorization.PaymentCaptured
- paymentauthorization.PaymentDeclined
- paymentauthorization.PaymentReauthorized
- paymentauthorization.PaymentReleased
- refund.RefundFailed
- refund.RefundIssued
Events consumed: 6 types from 3 topics
retailnetwork.checkout.events, retailnetwork.order-sourcing.events, retailnetwork.shipping-and-tracking.events
- assignment.FulfillmentCancelled order-sourcing
- assignment.FulfillmentShipped order-sourcing
- assignment.FulfillmentUnsourceable order-sourcing
- journey.PackageLost shipping-and-tracking
- journey.PackageReturned shipping-and-tracking
- checkoutsession.CheckoutCompleted checkout
MCP tools: 4 (4 read-only)
get_payment_authorization | read | Read one payment authorization by id: its state (AUTHORIZED, PARTIALLY_CAPTURED, CAPTURED, RELEASED, VOIDED, EXPIRED or DECLINED), the checkout session and order it belongs to, the currency and total in minor units, ever |
list_payment_authorizations | read | List the payment authorizations of one order (orderId) or of one checkout session (checkoutSessionId, declined attempts included) |
get_refund | read | Read one refund by id: its state (REQUESTED, SUCCEEDED or FAILED), reason (LOST, RETURNED_TO_SENDER or MANUAL), order, group, amount in minor units, how many provider attempts were made and the last failure code |
list_refunds | read | List the refunds of one order, oldest first |
A2A skills: 2
- How did a refund go
- Where does a payment stand
Recommended next steps
- Isolate or remove POST /refunds from the public surface until authorization exists, and audit-log every manual refund.
- Raise the mutation gate to the fleet norm (>=95%) and add BDD scenarios for reauthorization and hold expiry.
- Add a circuit breaker on the provider ACL and pagination on the list endpoints.
Measured at origin/develop 5974ba6 (2026-10-30). Review sampled 5 files.
Architecture
Clean code
API design
Solid pricing context: immutable, versioned PriceQuote aggregate with explicit arithmetic rules, outbox events for every price/policy change and cursor paging; debts are N+1 price lookups and a cyclo hotspot.
Cost is the top abandonment reason and the tier charge is where the delivery promise becomes revenue.
- Production code
- 10,014 lines Go in 83 files, 29 packages
- Tests
- 11,570 lines, 281 test functions, 9 integration files, 26 BDD scenarios, 34 fitness tests
- Function size
- avg 10.6 lines (p95 30), 1 over 60 lines
- Complexity
- avg cyclomatic 2.9; highest checkSnapshot (15), chargeGroups (14)
- Layering
- 0 infrastructure imports in domain/application; 5 domain packages
- Quality gates
- coverage 90%, mutation efficacy 85%, 15 CI jobs
- Persistence
- PostgreSQL, 1 migrations, 13 tables
- Deployables
- a2a, api
- Largest files
- none over 500 lines
- Decisions
- 7 ADRs, 9 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 2 binaries (API, A2A); Postgres + outbox to Kafka; consumes offer-availability catalogue events
Strengths
- PriceQuote is a binding, immutable snapshot recording the price, schedule and tax-table versions it used, with explicit invariants (ErrItemNotPriced, ErrEmptyQuote, currency) in internal/domain/quote/quote.go.
- Five small aggregates/policies (itemprice, quote, schedule, tax, shared money) keep tax and delivery-charge rules out of the quote use case (internal/domain/).
- Catalogue lifecycle arrives by events (CatalogItemCreated/Discontinued) and price changes leave by outbox events, so checkout and offer-availability are not called synchronously.
- Quote issue runs in one unit of work with retry on concurrency (transact(..., commandAttempts) in internal/application/usecases/quote.go:50); expiry skips concurrent writers safely.
Concerns
- priceLines does one ItemPrices.Get per line inside the issue transaction (internal/application/usecases/quote.go:87-105); with MaxLines=100 a quote can mean 100 round trips on the checkout path.
- No MCP adapter while siblings expose one (facts: binaries api, a2a only), so agents can read prices only via A2A; a deliberate choice should be recorded in an ADR.
- Write endpoints (set list price, publish tax tables) are unauthenticated by fleet decision (apis/openapi.yaml:20), so any caller can change prices.
Clean code
Strengths
- Small functions throughout: 10k prod LOC, average 10.6 lines, p95 30, average cyclo 2.9, no file over 500 lines (facts).
- Package docs state the model precisely (states, invariants, arithmetic with ADR refs) at the top of internal/domain/quote/quote.go, and bounds are named constants (MaxLines, MaxGroups, MaxQuantity).
- Test depth: 281 test funcs, 26 BDD scenarios, 34 fitness tests and a shared repository contract suite (internal/adapters/outbound/repocontract/).
Concerns
- checkSnapshot sits exactly at the cyclop cap (cyclo 15, internal/domain/quote/restore.go) and chargeGroups at 14 (internal/domain/quote/quote.go); the next rule change will breach the lint gate.
- Mutation efficacy gate is 85% (facts), below checkout's 95%, for code whose correctness is arithmetic.
- Expiry error handling lists three sentinel errors inline (internal/application/usecases/quote.go:134); a named 'skippable' predicate would document the intent.
APIs and contracts
- Good: Idempotency-Key declared on every write, RFC 9457 problem slugs per domain error (item-not-priced, no-tax-table), and cursor pagination (after/limit) on GET /item-prices.
- Good: AIP-style custom methods (:set-list-price, :withdraw, sales/{saleId}:cancel) and singleton 'current' sub-resources for schedules and tax tables.
- Gap: no ETag/If-Match on item-price updates despite versioned aggregates; versioning is info.version 1.0.0 only.
- Events: AsyncAPI 3.0, 4 integration events on retailnetwork.pricing.events and PriceQuoteIssued on a separate analytics topic; quote expiry deliberately emits no event.
REST: 13 operations (5 read, 8 write, 8 of 8 writes require Idempotency-Key)
| POST | /item-prices | Create the price record of a catalogue item |
| GET | /item-prices | List item prices, paged (projection bootstrap) |
| GET | /item-prices/{catalogItemId} | Get the price record of one catalogue item |
| POST | /item-prices/{catalogItemId}:set-list-price | Set the list price of a catalogue item |
| POST | /item-prices/{catalogItemId}:withdraw | Withdraw the price of a catalogue item |
| POST | /item-prices/{catalogItemId}/sales | Schedule a sale window for a catalogue item |
| POST | /item-prices/{catalogItemId}/sales/{saleId}:cancel | Cancel a scheduled sale window |
| POST | /delivery-charge-schedules | Publish a new delivery charge schedule |
| GET | /delivery-charge-schedules/current | Get the current delivery charge schedule |
| POST | /tax-tables | Publish a new tax table |
| GET | /tax-tables/current | Get the current tax table |
| POST | /price-quotes | Issue a binding price quote for a checkout |
| GET | /price-quotes/{quoteId} | Get a price quote |
Events published: 5 types on retailnetwork.pricing.analytics, retailnetwork.pricing.events
- deliverychargeschedule.DeliveryChargeScheduleChanged
- itemprice.ItemPriceChanged
- itemprice.ItemPriceWithdrawn
- pricequote.PriceQuoteIssued
- taxtable.TaxTableChanged
Events consumed: 2 types from 1 topics
retailnetwork.offer-availability.events
- catalogitem.CatalogItemCreated offer-availability
- catalogitem.CatalogItemDiscontinued offer-availability
A2A skills: 2
- Current price of a catalogue item
- Status and breakdown of an issued price quote
Recommended next steps
- Batch item-price lookups in IssuePriceQuote (one GetMany query) to keep quote latency flat as carts grow.
- Split checkSnapshot/chargeGroups into smaller validators before the next rule change hits the cyclop 15 cap.
- Expose aggregate version as ETag and require If-Match on :set-list-price and :withdraw.
Measured at origin/develop 368d7ed (2026-10-30). Review sampled 4 files.
Architecture
Clean code
API design
Clean hexagonal content/category context with tight aggregates, outbox, versioned events and paged reads; main design risk is the single-row CategoryTree aggregate that republishes the whole tree on every edit.
Commodity content management: the docs say buy a PIM in production; shoppers choose on price and delivery, not on this.
- Production code
- 8,388 lines Go in 71 files, 28 packages
- Tests
- 10,357 lines, 271 test functions, 8 integration files, 13 BDD scenarios, 31 fitness tests
- Function size
- avg 10.7 lines (p95 28), 2 over 60 lines
- Complexity
- avg cyclomatic 2.9; highest checkFields (13), checkLifecycle (13)
- Layering
- 0 infrastructure imports in domain/application; 3 domain packages
- Quality gates
- coverage 90%, mutation efficacy 95%, 15 CI jobs
- Persistence
- PostgreSQL, 1 migrations, 6 tables
- Deployables
- a2a, api
- Largest files
- none over 500 lines
- Decisions
- 6 ADRs, 9 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 2 binaries (API+relay+consumer, read-only A2A); Postgres + outbox to Kafka; local CatalogItemView
Strengths
- Two aggregates with private state and validated Restore: ProductContent (DRAFT/PUBLISHED/RETIRED, revisions) and CategoryTree with cycle, depth, sibling-name and size invariants (internal/domain/category/category.go)
- Domain stays pure: sibling facts (item known/discontinued, category exists) are handed in as plain values or the small Categories interface (internal/domain/content/content.go); no layer violations per facts
- Optimistic concurrency on both aggregates (UPDATE ... WHERE version = loaded, FOR UPDATE in a UoW) and an outbox drained with FOR UPDATE SKIP LOCKED (internal/adapters/outbound/postgres/outbox.go)
- Discontinued items retire content through a consumed-event policy, not a sync call; offer-availability is the only upstream, mirrored locally (ADR 0003)
Concerns
- CategoryTree is one live row (tree_id 'main', up to 5000 nodes): every create/move/rename serialises on it and emits the WHOLE tree as CategoryTreePublished (internal/domain/category/category.go publish, apis/asyncapi.yaml)
- Tree operations are linear scans: index() is O(n), and recompute() rebuilds every path on each edit, recursive height() included, so cost is quadratic in tree size near MaxCategories (internal/domain/category/category.go)
Clean code
Strengths
- Small, readable functions: avg 10.7 lines, avg cyclomatic 2.9, none above cyclo 15, only two over 60 lines (a repocontract helper and telemetry.Setup) (facts)
- Domain errors map one-to-one to problem slugs, and doc comments cite the ADR or model decision behind each rule (internal/domain/content/content.go, internal/adapters/inbound/http/errors.go)
- Strong test economy: test LOC 10.4k vs prod 8.4k, shared repository contract suite (outbound/repocontract), 13 BDD scenarios, mutation gate at 95% efficacy/coverage (facts)
Concerns
- Create/Move/RenameCategory use cases repeat the same load-tree, mutate, saveTree, map-view block three times (internal/application/usecases/category.go); shopping-cart factors this into a single mutate helper
- Domain validation hotspots checkFields, checkLifecycle and checkSnapshot all sit at cyclo 13, close to the cap of 15 (internal/domain/content/commands.go, internal/domain/content/restore.go)
APIs and contracts
- Good: every write takes Idempotency-Key; errors are problem+json with documented slugs per status; GET /product-contents is cursor-paged (after/limit, next) (apis/openapi.yaml, internal/adapters/inbound/http/handlers.go)
- Lifecycle verbs are custom-method POSTs (:revise, :publish, :retire, :discard); :revise replaces the whole body, which suits PUT; a second create returns a generic 409 concurrent-update, not an already-exists problem (usecases/content.go)
- Missing: no ETag/If-Match, so clients cannot do conditional updates on content they edited; no path or media-type version, and the spec is 0.1.0 (apis/openapi.yaml)
- Event contract is careful: per-item revision ordering on the catalogItemId key, tree version for replace-if-newer, v1 dataschema URNs and no PII/prices in payloads (apis/asyncapi.yaml)
REST: 12 operations (3 read, 9 write, 9 of 9 writes require Idempotency-Key)
| POST | /product-contents | Create the draft content of a catalogue item |
| GET | /product-contents | List product contents, paged (projection bootstrap) |
| GET | /product-contents/{catalogItemId} | Get the content of one catalogue item |
| POST | /product-contents/{catalogItemId}:revise | Revise the content of a catalogue item |
| POST | /product-contents/{catalogItemId}:publish | Publish the content of a catalogue item |
| POST | /product-contents/{catalogItemId}:retire | Retire the published content of a catalogue item |
| POST | /product-contents/{catalogItemId}:discard | Discard the draft content of a catalogue item |
| POST | /categories | Create a category in the live tree |
| GET | /categories | Get the category tree |
| POST | /categories:publish | Publish the category tree again |
| POST | /categories/{categoryId}:move | Move a category under a new parent |
| POST | /categories/{categoryId}:rename | Rename a category |
Events published: 3 types on retailnetwork.product-content.events
- categorytree.CategoryTreePublished
- productcontent.ProductContentPublished
- productcontent.ProductContentRetired
Events consumed: 2 types from 1 topics
retailnetwork.offer-availability.events
- catalogitem.CatalogItemCreated offer-availability
- catalogitem.CatalogItemDiscontinued offer-availability
A2A skills: 2
- Product content of a catalogue item
- The category tree
Recommended next steps
- Plan for tree growth: index categories by id in the aggregate and consider per-subtree events or a size budget for CategoryTreePublished
- Expose aggregate version as ETag and honour If-Match on :revise/:publish so editors get lost-update protection
- Factor the duplicated category command template into one helper and return a distinct already-exists problem on duplicate create
Measured at origin/develop 3975278 (2026-10-30). Review sampled 12 files.
Architecture
Clean code
API design
A disciplined, read-only CQRS projection service: pure fold logic, inbox-deduplicated consumers, bounded retries + DLQ and strong fitness/mutation gates; the API is small but lacks caching and versioning.
Supporting today, a Core candidate at scale: the search engine is generic, the purchasable join is the storefront's own.
- Production code
- 8,524 lines Go in 81 files, 25 packages
- Tests
- 10,519 lines, 265 test functions, 8 integration files, 18 BDD scenarios, 33 fitness tests
- Function size
- avg 11.6 lines (p95 29), 1 over 60 lines
- Complexity
- avg cyclomatic 3.2; highest searchHitData (15), filters (14)
- Layering
- 0 infrastructure imports in domain/application; 4 domain packages
- Quality gates
- coverage 90%, mutation efficacy 99%, 15 CI jobs
- Persistence
- PostgreSQL, 1 migrations, 4 tables
- Deployables
- a2a, api, rebuild
- Largest files
- none over 500 lines
- Decisions
- 7 ADRs, 10 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal read-side projection; 3 binaries (API+consumers, A2A, rebuild job); Postgres FTS/pg_trgm; consumes 3 Kafka topics
Strengths
- Domain is pure fold logic (internal/domain/productview fold_*.go) returning Outcome values; use cases in internal/application/usecases only orchestrate load-fold-save.
- Exactly-once apply: Consumer.handle claims the event in an inbox and folds in the same unit of work, retrying up to 5 times on ErrConcurrentUpdate (usecases/consume.go).
- Transient consumer failures get capped-backoff retries then go to <topic>.dlq with x-dlq-* headers instead of blocking the partition (adapters/inbound/kafka/deadletter.go).
- Layering is executable: arch-go TestHexagonalArchitecture plus 33 fitness tests (internal/architecture/), and search sits behind a port so an engine swap is an adapter change.
Concerns
- Deterministic poison messages (bad CloudEvent, unknown type, malformed payload) are committed past rather than dead-lettered (adapters/inbound/kafka/deadletter.go header comment), so dropped facts leave only a log line.
- Projection recovery depends on the cmd/rebuild job calling producers' snapshot routes (internal/adapters/outbound/sources/); drift between event stream and snapshots has no automated reconciliation check.
- Endpoints are unauthenticated by fleet decision; acceptable for a public catalogue read, but the A2A surface (cmd/a2a/main.go) is equally open.
Clean code
Strengths
- Small functions: 388 funcs, avg 11.6 lines, p95 29, zero over cyclomatic 15; the largest is telemetry Setup at 66 lines.
- Readable, intention-revealing names and doc comments tied to ADRs (e.g. ApplyListingStateChanged citing ADR 0002 A1 in usecases/consume_offer.go).
- Test LOC (10.5k) exceeds prod LOC (8.5k): unit, 18 BDD scenarios, 8 testcontainers integration files, a shared repocontract suite run against memory and postgres, 99% mutation gate.
Concerns
- Template fitness tests that do not apply here remain (internal/architecture/outbox_relay_cap_fitness_test.go, mcp_optional_inputs_test.go) in a service with no outbox and no MCP; they pass vacuously and add noise.
- Domain cursor type carries JSON struct tags and encoding (internal/domain/search/cursor.go), mixing wire format into the domain package.
- Near-cap complexity in search filtering duplicated across adapters: searchHitData (cyclo 15, repocontract/searching_cases.go) and filters (cyclo 14, memory/search.go).
APIs and contracts
- Three clean read resources (GET /products, /products/{catalogItemId}, /categories) with RFC 9457 problem+json errors (404, 422 validation-failed) declared in apis/openapi.yaml.
- Opaque base64url keyset cursor via ?after= with limit 1-100, encoding sort, match mode and tiebreak id so FTS-to-trigram fallback stays stable across pages.
- No HTTP caching semantics (no ETag/Cache-Control in adapters/inbound/http) and no URI or media-type versioning, despite being a high-read storefront surface.
- AsyncAPI documents only the consumed fields of 11 producer event types with tolerant decoding; nothing is published, which is consistent with publishes: [] in the model.
REST: 3 operations (3 read, 0 write)
| GET | /products | Search and filter purchasable products |
| GET | /products/{catalogItemId} | Get one product view |
| GET | /categories | Get the category tree with purchasable counts |
Events consumed: 11 types from 3 topics
retailnetwork.offer-availability.events, retailnetwork.pricing.events, retailnetwork.product-content.events
- catalogitem.CatalogItemCreated offer-availability
- catalogitem.CatalogItemDiscontinued offer-availability
- listing.ListingAvailabilityChanged offer-availability
- listing.ListingCreated offer-availability
- listing.ListingRestored offer-availability
- listing.ListingSuppressed offer-availability
- itemprice.ItemPriceChanged pricing
- itemprice.ItemPriceWithdrawn pricing
- categorytree.CategoryTreePublished product-content
- productcontent.ProductContentPublished product-content
- productcontent.ProductContentRetired product-content
A2A skills: 2
- Read one product page view
- Search the product catalogue
Recommended next steps
- Add ETag/Cache-Control (or a CDN-friendly max-age) to product and category reads.
- Dead-letter or count deterministic poison messages with a metric/alert instead of silently committing past them.
- Remove or gate template-only fitness tests (outbox relay cap, MCP inputs) that cannot apply to this read-only service.
Measured at origin/develop 7ce7578 (2026-10-30). Review sampled 8 files.
Architecture
Clean code
API design
Disciplined hexagonal Cart context with a well-encapsulated aggregate, outbox, inbox and blanket Idempotency-Key replay; issues are minor: a stale doc comment, POST-only verbs, and no client-visible concurrency control.
Supporting conversion capability: holds intent without breaking the total-cost-up-front rule; prices and promises come from others.
- Production code
- 9,761 lines Go in 89 files, 30 packages
- Tests
- 11,697 lines, 305 test functions, 8 integration files, 38 BDD scenarios, 31 fitness tests
- Function size
- avg 11.0 lines (p95 30), 1 over 60 lines
- Complexity
- avg cyclomatic 3.1; highest Gateway.toQuote (14), testItems (14)
- Layering
- 0 infrastructure imports in domain/application; 3 domain packages
- Quality gates
- coverage 90%, mutation efficacy 85%, 15 CI jobs
- Persistence
- PostgreSQL, 1 migrations, 7 tables
- Deployables
- a2a, api
- Largest files
- none over 500 lines
- Decisions
- 7 ADRs, 9 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal DDD context; 2 binaries (API+relay+consumers, read-only A2A); Postgres + outbox to Kafka; local read models
Strengths
- Cart aggregate keeps all state private behind methods and imports only domain/shared and stdlib (internal/domain/cart/cart.go); lifecycle and terminal states are enforced in the domain
- Optimistic concurrency done properly: Save updates WHERE version = loaded version and maps 0 rows to ErrConcurrentUpdate, plus FOR UPDATE inside a unit of work (internal/adapters/outbound/postgres/carts.go)
- Sibling data comes from consumed events into local read models (ADR 0003); delivery-promise is the only sync call, made outside the transaction and re-validated against the cart version (usecases/quote_delivery.go)
- Layering enforced by arch-go fitness tests (31 fitness tests per facts) and the facts script found zero layer-import violations; outbox relay is batched with an attempt cap (outbound/outbox/relay.go)
Concerns
- Quoting depends synchronously on delivery-promise with only a 5s client timeout and no circuit breaker or fallback (internal/adapters/outbound/deliverypromise/gateway.go DefaultTimeout); an outage surfaces as 503 on every quote
- Open-state and destination preconditions are re-checked in the application layer before the remote call (internal/application/usecases/quote_delivery.go attempt), so the rule lives in both use case and aggregate
Clean code
Strengths
- Small, uniform functions: avg 11 lines, avg cyclomatic 3.1, no function over cyclo 15, only one over 60 lines (facts); generic command[B] helper removes handler boilerplate (inbound/http/handlers.go)
- Use cases share one load-change-persist template (Deps.mutate in usecases/cart_commands.go), so each command is a few lines of intent
- Error mapping is a single ordered catalogue from typed domain/port errors to problem slugs (inbound/http/errors.go)
- Test LOC (11.7k) exceeds prod LOC (9.8k); 38 BDD scenarios, repository contract suite shared by memory and Postgres (outbound/repocontract), golden CloudEvents files, 90% coverage and 85% mutation gates
Concerns
- Stale copy-pasted doc on RequireIdempotencyKey: it says 'the three POST routes' and 'the order id is derived from the key, cancel is a no-op' (internal/adapters/inbound/http/idempotency.go:26-33), but the router wraps nine cart routes and there are no orders
- Hotspots near the lint cap: Gateway.toQuote is 51 lines at cyclo 14 (internal/adapters/outbound/deliverypromise/mapping.go) and telemetry.Setup is 66 lines (internal/adapters/outbound/telemetry/telemetry.go)
APIs and contracts
- Good: every write requires Idempotency-Key (middleware: request-hash mismatch -> 422, 24h replay, Idempotent-Replayed header; inbound/http/idempotency.go); errors are RFC 9457 problem+json with typed slugs
- Commands are custom-method POSTs (:set-quantity, :remove, :merge-into), so line removal is not a DELETE, and /carts/{cartId}/delivery/requoted breaks the custom-method convention the other routes use (apis/openapi.yaml)
- Missing: no ETag/If-Match, so concurrency stays server-side only; GET /carts has no pagination; no version in the path, and the spec is 0.1.0 with only a localhost server (apis/openapi.yaml)
- Event contract is strong: 4 analytics-only CloudEvents with full type names, a v1 dataschema URN, a .v2-on-break rule, golden payload files, and consumed messages listing only the fields used (apis/asyncapi.yaml)
REST: 11 operations (2 read, 9 write, 9 of 9 writes require Idempotency-Key)
| POST | /carts | Create a cart |
| GET | /carts | List carts of a shopper |
| GET | /carts/{cartId} | Get a cart with its quote, selections and estimate |
| POST | /carts/{cartId}/lines | Add a line to the cart (merges into an existing line of the item) |
| POST | /carts/{cartId}/lines/{catalogItemId}:set-quantity | Set the quantity of a cart line |
| POST | /carts/{cartId}/lines/{catalogItemId}:remove | Remove a cart line |
| POST | /carts/{cartId}:set-destination | Set the destination postal prefix |
| POST | /carts/{cartId}:quote-delivery | Quote delivery offers for the cart |
| POST | /carts/{cartId}:select-delivery | Select a delivery offer for a shipment group |
| POST | /carts/{cartId}:merge-into | Merge this cart into another OPEN cart of the same shopper |
| POST | /carts/{cartId}/delivery/requoted | Write the offers of a checkout requote into the cart |
Events published: 4 types on retailnetwork.shopping-cart.analytics
- cart.CartAbandoned
- cart.CartCheckedOut
- cart.CartDeliveryQuoted
- cart.CartLineAdded
Events consumed: 7 types from 3 topics
retailnetwork.checkout.events, retailnetwork.offer-availability.events, retailnetwork.pricing.events
- catalogitem.CatalogItemCreated offer-availability
- catalogitem.CatalogItemDiscontinued offer-availability
- checkoutsession.CheckoutCompleted checkout
- deliverychargeschedule.DeliveryChargeScheduleChanged pricing
- itemprice.ItemPriceChanged pricing
- itemprice.ItemPriceWithdrawn pricing
- taxtable.TaxTableChanged pricing
A2A skills: 2
- List a shopper's carts
- Look up one cart
Recommended next steps
- Fix the stale RequireIdempotencyKey doc comment and add a fleet-drift check for copied comments that mention foreign aggregates
- Add a circuit breaker (or short-lived cached last quote) around the delivery-promise gateway and expose its state on /readyz
- Expose cart version as ETag and accept If-Match on commands; add cursor pagination to GET /carts
Measured at origin/develop f8fb50b (2026-10-30). Review sampled 13 files.
Architecture
Clean code
API design
Small, well-guarded BFF: per-route time budgets, deterministic idempotency keys and edge refusal of card data; weak spots are no breaker/retry, unused Kafka scaffolding and zero BDD scenarios.
README labels it Generic; fleet docs say it carries no domain model and is not a bounded context.
- Production code
- 2,313 lines Go in 31 files, 11 packages
- Tests
- 6,299 lines, 161 test functions, 4 integration files, 0 BDD scenarios, 35 fitness tests
- Function size
- avg 12.0 lines (p95 34), 1 over 60 lines
- Complexity
- avg cyclomatic 3.3; highest ValidID (14), validPostalPrefix (12)
- Layering
- 0 infrastructure imports in domain/application; 1 domain packages
- Quality gates
- coverage 90%, mutation efficacy 98%, 15 CI jobs
- Persistence
- no database of its own
- Deployables
- api
- Largest files
- none over 500 lines
- Decisions
- 5 ADRs, 7 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Stateless backend-for-frontend; 1 binary (API); composes 5 storefront contexts + delivery-promise over REST; no database
Strengths
- Clear BFF scope: no domain model, no DB; routes are thin relays over an allowlisted upstream set (internal/domain/composition/allowlist.go), and upstream problem details are relayed unchanged.
- Per-route time budgets (2s queries, 5s commands, 15s confirm) are the only clock (internal/domain/composition/budget.go; internal/adapters/outbound/rest/client.go:31), answering 504 and never retrying.
- Edge safety policies are enforced and fitness-tested: card-shaped fields refused (internal/application/usecases/checkout.go:79-93), bff_no_card_data and bff_no_body_logging fitness tests.
- otelhttp transport propagates traceparent so one trace spans the BFF hop (internal/adapters/outbound/rest/client.go:42-52).
Concerns
- No circuit breaker, bulkhead or retry on upstream calls (internal/adapters/outbound/rest/client.go); a slow upstream holds connections for the full route budget.
- internal/adapters/outbound/kafka/writer.go and internal/adapters/kafka/cloudevents/ are only referenced by tests, contradicting the spec's 'no Kafka' (apis/openapi.yaml:12): dead template scaffolding.
- No authentication (fleet decision): sf_state cookie identifies cart/shopper as plain state (apis/openapi.yaml:18), so any caller can read another shopper's orders by id.
Clean code
Strengths
- Very small and readable: 2.3k prod LOC, average function 12 lines, average cyclo 3.3, no file over 500 lines, no panics (facts).
- Test-heavy: 6.3k test LOC vs 2.3k prod, contract and journey integration tests (cmd/api/integration_contract_test.go), 35 fitness tests, 98% mutation-efficacy gate.
- MintKey (internal/domain/composition/idempotency.go) is a compact, documented derivation with field separators and a client action-id override.
Concerns
- Zero BDD feature files despite a bdd CI job (facts: 0 scenarios), so shopper journeys are covered only by Go integration tests.
- Fitness tests copied from the service template check features this repo lacks (internal/architecture/outbox_relay_cap_fitness_test.go, mcp_optional_inputs_test.go), adding noise.
- ValidID is the most complex function at cyclo 14 for 13 lines (internal/domain/composition/state.go); a regexp or table would be clearer.
APIs and contracts
- Good: 24 operations with page-oriented resources (carts, checkout, orders, me) and AIP-style custom methods (:confirm, :cancel, delivery:quote, delivery:select); cursor pagination via after/limit (max 100).
- Good: idempotency is handled for the browser by minting deterministic keys per action, overridable by X-Action-Id, documented in the spec description.
- Gap: problem types are relayed verbatim from upstreams, so the BFF error vocabulary is the union of five services' slugs rather than a curated edge contract.
- Gap: version 0.1.0 with no versioning scheme for a public edge; no event contract (no AsyncAPI), consistent with being a pure relay.
REST: 23 operations (9 read, 14 write, 0 of 14 writes require Idempotency-Key)
| GET | /products | Search products |
| GET | /categories | Get the category tree for department navigation |
| GET | /products/{id} | Get one product view |
| POST | /products/{id}:delivery-dates | Delivery dates and charges for one unit of a product |
| POST | /carts | Create a cart |
| GET | /carts | List carts of a shopper |
| GET | /carts/{id} | Get a cart |
| POST | /carts/{id}/lines | Add a line to the cart |
| PATCH | /carts/{id}/lines/{item} | Change the quantity of a cart line |
| DELETE | /carts/{id}/lines/{item} | Remove a cart line |
| POST | /carts/{id}/destination | Set the destination postal prefix |
| POST | /carts/{id}/delivery:quote | Quote delivery offers for the cart |
| POST | /carts/{id}/delivery:select | Select a delivery offer for a shipment group |
| POST | /checkout | Open a checkout session for the cart |
| GET | /checkout/{id} | Get a checkout session |
| POST | /checkout/{id}:confirm | Confirm the session with a payment method token |
| GET | /orders | List the shopper's orders |
| GET | /orders/{id} | Get an order with tracking and checkout totals |
| POST | /orders/{id}:cancel | Request the cancellation of an order |
| POST | /shoppers | Register a shopper |
| POST | /sessions | Start a session by e-mail lookup |
| GET | /me | Get the cookie's shopper |
| POST | /me/addresses | Save an address for the cookie's shopper |
Recommended next steps
- Add a per-upstream circuit breaker in internal/adapters/outbound/rest so one failing context fails fast instead of consuming the route budget.
- Delete the unused Kafka/CloudEvents adapters and the template fitness tests that do not apply, or document why they exist.
- Add a handful of BDD journeys (browse, cart, checkout confirm, in-doubt polling) to make edge behaviour reviewable.
Measured at origin/develop 2324afd (2026-10-30). Review sampled 4 files.
Architecture
Clean code
API design
A tidy, security-conscious React Router 7 SSR storefront with a single BFF dependency, strict CSP and good CI sensors; types are hand-mirrored and test depth (no mutation, thin e2e) trails the Go services.
A UI with no DDD classification; the fleet lists it as an experience component without a domain model.
- Production code
- 3,777 lines TS/TSX in 55 files
- Tests
- 25 test files (1,763 lines), 4 end-to-end specs
- Stack
- react 19.3.1, @react-router/dev 7.18.4, vite 8.3.5, typescript 5.9.3, vitest 5.0.5, @playwright/test 1.64.1
- Explicit any
- 0
- Largest files
- none over 400 lines
- Decisions
- 6 ADRs, 7 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Architecture
React 19 + React Router 7 framework-mode SSR on Node; one backend (storefront-bff via /api/storefront); stub BFF for CI; Helm chart
Strengths
- Single-backend rule enforced: the browser only knows API_BASE=/api/storefront (app/lib/api.ts) and BFF_URL lives in a *.server.ts module, proven by the no-network-url-in-bundle CI job.
- Clean separation: routes in app/routes, pure helpers in app/lib (money, dates, destination, order-status), presentational components in app/components.
- Double-submit safety: useActionId/useRenewedActionId (app/lib/action-id.ts) keep one X-Action-Id per user action so the BFF's Idempotency-Key dedupes retries.
- In-memory stub BFF (server/stub*.ts) enforces upstream contract rules, letting e2e and Lighthouse budget jobs run without a cluster.
Concerns
- N+1 fan-out: the checkout clientLoader issues one getProduct call per cart line via Promise.all (app/routes/checkout.tsx:39); a batch product read on the BFF would cut latency.
- No request timeout in the shared client: callRaw passes only an optional caller signal (app/lib/api.ts:48-61), so a hung BFF call stalls a client loader indefinitely.
- Shopper/session flows ride an unauthenticated BFF by fleet decision; the web keeps only a BFF-minted shopper id (README.md), so identity is spoofable end to end.
Clean code
Strengths
- TypeScript strict with zero explicit any across 55 prod files (3.8k LOC); no file over 400 lines.
- Typed RFC 9457 error path: ApiError carries the parsed Problem and a slug accessor, surfaced via a shared ProblemAlert component (app/lib/api.ts, app/components/ProblemAlert.tsx).
- Coverage thresholds enforced in vitest.config.ts (lines 90, functions 85, branches 70) plus 4 Playwright specs incl. a security spec and a live-purchase journey.
Concerns
- BFF response shapes are hand-written (app/lib/types.ts, 235 lines) rather than generated from storefront-bff's OpenAPI, so contract drift is caught only by e2e.
- Silent error swallowing in loaders: getCart(...).catch(() => null) and getProduct(...).catch(() => null) in app/routes/checkout.tsx:35-39 hide BFF failures as empty data.
- README.md says Vite 7 and 5 ADRs while package.json pins vite 8.3.5 and docs/adr holds 6; branch coverage gate is only 70% and there is no mutation testing (no Stryker).
APIs and contracts
- Consumer, not provider: exposes no REST spec of its own; it relays the BFF contract and handles problem+json uniformly in callRaw (app/lib/api.ts).
- Path ids are always encodeURIComponent'd (seg) and query strings drop empty params (query), avoiding route injection and noisy URLs.
- Idempotency is delegated cleanly via X-Action-Id per user action; there is no client-side concurrency (ETag/If-Match) handling for cart or checkout updates.
- No generated client or contract test against storefront-bff/apis/openapi.yaml; consistency relies on the stub BFF mirroring upstream rules by hand.
Consumes: /api/storefront (through the edge gateway). Exposes no API of its own.
Recommended next steps
- Generate app/lib/types.ts (or a typed client) from storefront-bff's OpenAPI and fail CI on drift.
- Add a default timeout (AbortSignal.timeout) in callRaw and stop swallowing loader errors as null.
- Ask the BFF for a batched product read to remove per-line getProduct fan-out at checkout and cart.
Measured at origin/develop 2db89c4 (2026-10-30). Review sampled 7 files.
Experience & Operations 3 applications
Architecture
Clean code
API design
Clean React/Module Federation shell with honest degradation states and zero 'any'; remote registration is hand-duplicated across four files and guarded by regex-on-source tests rather than one registry.
Shell with no domain model: a composition root hosting context screens plus cross-cutting views.
- Production code
- 6,810 lines TS/TSX in 52 files
- Tests
- 26 test files (3,803 lines), 0 end-to-end specs
- Stack
- react 19.3.0, vite 8.2.2, typescript 6.0.2, @module-federation/vite 1.21.0, vitest 5.0.0
- Explicit any
- 0
- Largest files
- none over 400 lines
- Decisions
- 1 ADRs, 13 docs pages
- Security scanning
- 1 open code-scanning, 1 open Dependabot alerts
Architecture
React 19 SPA shell; Module Federation host for 29 remotes; nginx behind web gateway; reads console-bff and per-context /reports via Kong
Strengths
- Clear shell/remote split (ADR-0001): the shell owns only cross-cutting screens (Floor, Order Lifecycle, WMS/WES dashboards, Contexts), everything else is lazy-loaded remotes (src/App.tsx).
- Remotes are wrapped in RemoteBoundary and lazy() is hoisted to module scope to avoid remounts (src/App.tsx:67-131, src/shell/RemoteBoundary.tsx).
- Degradation is explicit: ContextReportScreen separates whole-request error, loading and freshness-unknown, never showing fabricated numbers (src/features/context-reports/ContextReportScreen.tsx).
Concerns
- Each remote is registered in four places by hand: vite.config.ts remotes, two lists in src/App.tsx (lazy imports + REMOTE_PREFIXES + Route blocks) and scripts/verify-all-routes.cjs; no single manifest drives them.
- @warehouse/ui-kit is a file:../warehouse-ui-kit path dependency (package.json:20), so builds depend on a sibling checkout rather than a versioned package.
- Remote modules are untyped (dts: false, every import is @ts-expect-error in src/App.tsx), so shell/remote contract breaks surface only at runtime.
Clean code
Strengths
- Strict typing: 0 explicit any across 6.8k TS LOC and no file over 400 lines (facts); per-context report configs isolate DTO mapping (src/features/context-reports/*.config.tsx).
- Behavioural tests with Testing Library + msw and a config test per report screen (26 test files, 3.8k test LOC); lint (oxlint), typecheck and build run in CI.
- Comments explain why (e.g. module-scope lazy, router Link provider in src/App.tsx), not just what.
Concerns
- src/remotes-registration.test.ts (661 lines) asserts regexes against vite.config.ts/App.tsx source text, which is brittle and a symptom of the duplicated registration.
- src/App.tsx repeats ~29 near-identical <Route><RemoteBoundary/> blocks; a data-driven route table would remove ~200 lines of duplication.
- No coverage threshold, mutation testing or e2e specs in CI (facts: coverage_threshold null, e2e_specs 0); inline style objects throughout (src/features/context-reports/ContextReportScreen.tsx).
APIs and contracts
- Consumer only: no OpenAPI/AsyncAPI of its own; it reads console-bff envelopes (GET /console/reports/{wms,wes}) and each context's /reports/... and /reports/.../freshness directly (README.md).
- Report DTO types are hand-copied from each service's reports_handler.go (README.md; src/features/context-reports/types.ts) rather than generated from the services' OpenAPI, so drift is caught only by review.
- Freshness has two wire generations ({lagSeconds} vs {as_of, lag_seconds}) handled ad hoc in src/features/context-reports/ContextReportScreen.tsx:37-41, showing an unharmonised contract across contexts.
Consumes: /api/facility-layout, /api/fulfillment-execution, /api/inbound-receiving, /api/inventory-storage, /api/labor-performance, /api/network-fulfillment, /api/network-inventory-planning, /api/order-management, /api/pick-face-replenishment, /api/process-path-management, /api/product-master, /api/slotting-optimization, /api/task-interleaving, /api/warehouse-ops-agent, /api/warehouse-planning, /api/wes-work-planning, /api/workforce-management (through the edge gateway). Exposes no API of its own.
Recommended next steps
- Introduce one remotes manifest (name, path, port, label) that generates vite remotes, routes, nav prefixes and verify-routes; drop the regex source tests.
- Generate report DTO types from each service's openapi-reports.yaml and converge the freshness payload on one shape.
- Publish @warehouse/ui-kit as a versioned package and add a coverage gate plus a smoke e2e in CI.
Measured at origin/develop 88411b8 (2026-10-30). Review sampled 6 files.
Architecture
Clean code
API design
Thoughtful offline-first PWA: a persisted command outbox with stable Idempotency-Keys and FIFO replay, let down by hand-copied API types, no coverage gate and e2e scripts that never run in CI.
A client, not a bounded context: no aggregates or events, it conforms to each owning service's API.
- Production code
- 4,419 lines TS/TSX in 51 files
- Tests
- 13 test files (2,205 lines), 0 end-to-end specs
- Stack
- react 19.3.0, vite 8.2.2, typescript 6.0.2, vitest 5.0.0
- Explicit any
- 1
- Largest files
- none over 400 lines
- Decisions
- 0 ADRs, 7 docs pages
- Security scanning
- 0 open code-scanning, 0 open Dependabot alerts
Architecture
React 19 + Vite PWA; screens -> StationProvider -> typed API builders -> CommandRunner + localStorage outbox; same-origin /api via Kong
Strengths
- Single write path: screens never fetch for writes; CommandRunner mints the Idempotency-Key, persists before sending, and classifies results as done/problem/queued/unsent (src/lib/commands.ts)
- Outbox persists before memory and rejects corrupt entries via the isEntry guard; FIFO replay stops at the first undeliverable entry so order is kept (src/lib/outbox.ts, CommandRunner.doFlush)
- Outcomes are applied in one place whether direct or replayed, including lost-answer cases such as task-already-completed and the extra claim after a replay (src/features/station/StationProvider.tsx apply)
- Dependencies injected through ServicesProvider (store, runner, clock, fetchFn), so the runner and screens are testable without globals (src/app/ServicesProvider.tsx)
Concerns
- A plain 500 is treated as definitive: only 429/502/503/504 are retryable (src/lib/commands.ts:51), so a transient server error drops a queued scan/complete from the outbox, though resending with the same key would be safe
- Strict FIFO means one entry stuck behind a retryable status blocks every later command for the station (src/lib/commands.ts drainBefore); there is no per-entry max attempts or dead-letter view for the operator
- CI builds against warehouse-ui-kit at ref develop via file:../warehouse-ui-kit (.github/workflows/ci.yml, package.json), so builds are not reproducible and a kit change can break this app silently
Clean code
Strengths
- Strict TypeScript with only 1 explicit any and no file over 400 lines (facts); discriminated-union Outcome type keeps result handling exhaustive (src/lib/commands.ts)
- Domain helpers are small, pure and unit-tested: GS1 parsing/check digits, Code128 encoding against a reference table (src/lib/gs1/, src/lib/barcode/, src/test/code128Reference.ts)
- Comments explain the why (key reuse vs 422, persist-before-send, lease renewal not queued) next to the code they justify (src/api/fulfillmentExecution.ts, src/lib/commands.ts)
Concerns
- Thin test gate: 13 test files / 2.2k LOC for 51 prod files / 4.4k LOC, no coverage threshold or mutation testing (facts); e2e:station and e2e:receiving exist (scripts/e2e-*.mjs) but no CI job runs them (.github/workflows/ci.yml)
- StationProvider.apply is a growing string switch on command kind that mixes problem handling and success reduction, and casts payloads unchecked (outcome.data as Station) (src/features/station/StationProvider.tsx)
- Largest screens carry layout and flow logic together: ReceivingScreen.tsx 373 lines, TaskScreen.tsx 359 lines (src/features/receiving/ReceivingScreen.tsx, src/features/task/TaskScreen.tsx)
APIs and contracts
- Client side of the contract behaves well: Idempotency-Key on every write, reused only for an unchanged body (avoids 422 idempotency-key-reused), problem+json mapped to operator copy (src/lib/commands.ts, src/api/problemMessages.ts)
- Types are hand-copied from producer OpenAPI (docs/api-contract.md) and already drift: the comment says BREAK_CASE is not in AnyTaskType, but the server spec now lists it; Task.type is string, not TaskType (src/api/fulfillmentExecution.ts)
- No generated client or contract test against the producers' specs; the stub API is hand-written (scripts/stub-api.mjs), so a server-side rename would surface only at runtime
- No auth by fleet decision (docs/architecture.md): any device on the network path can register stations and complete tasks, a risk for a floor app
Consumes: /api/fulfillment-execution, /api/inbound-receiving (through the edge gateway). Exposes no API of its own.
Recommended next steps
- Treat 500 (and network aborts after send) as retryable with a per-entry attempt cap, and surface stuck outbox entries to the operator
- Generate TS types from the producers' OpenAPI in CI (openapi-typescript) and fail on drift; run the e2e scripts against stub-api in CI
- Add a vitest coverage threshold and pin @warehouse/ui-kit to a tagged ref instead of develop
Measured at origin/develop 4930c6d (2026-10-30). Review sampled 10 files.
Architecture
Clean code
API design
Carefully governed read-mostly LLM ops agent: deterministic policy core, 12 read-only MCP tools, AST-enforced zero-write rule and a token-gated single write; large files and process-local approval state limit it.
Fleet map files it as Supporting: owns no aggregate or state, only decision policy over other contexts' facts.
- Production code
- 19,883 lines Go in 139 files, 19 packages
- Tests
- 25,336 lines, 704 test functions, 2 integration files, 103 BDD scenarios, 33 fitness tests
- Function size
- avg 14.0 lines (p95 42), 10 over 60 lines
- Complexity
- avg cyclomatic 2.9; highest FlowBalanceAdvisory.Execute (14), Signer.Verify (13)
- Layering
- 0 infrastructure imports in domain/application; 2 domain packages
- Quality gates
- coverage 90%, mutation efficacy 80%, 16 CI jobs
- Persistence
- no database of its own
- Deployables
- agent
- Largest files
- internal/adapters/inbound/http/router.go (943), internal/adapters/inbound/mcp/network_outlook.go (678), internal/config/config.go (587)
- Decisions
- 29 ADRs, 58 docs pages
- Security scanning
- 1 open code-scanning, 1 open Dependabot alerts
Transactional outboxCloudEvents 1.0Idempotency-KeyOptimistic concurrencyDead-letter queueCircuit breakerRetry with backoffRFC 9457 problem+jsonOpenTelemetry tracingMetricsGraceful shutdownAnalytics stream
Architecture
Hexagonal Go agent; 1 binary (REST console + MCP server); MCP/REST/A2A clients to ~15 contexts; Anthropic reasoner behind a port; stateless
Strengths
- Correlation logic is a deterministic domain policy (internal/domain/policy) fed by ports; the LLM reasoner is optional, LLMMode off keeps pre-ADR behaviour byte-for-byte (usecases/flow_balance_advisory.go:77-83).
- Upstream failures degrade to partial, conservative decisions with MissingSignals instead of failing, backed by circuit breakers and deadlines (internal/resilience/breaker.go, deadline.go).
- The only write (release_next_work) is a propose/approve flow with an HMAC-signed, single-use, TTL-bound token, delegated via A2A and never exposed to MCP or the LLM (usecases/release_work.go:17-31, domain/approval).
- Zero-write guarantee is an executable fitness test: an AST scan fails on any mutating HTTP method in outbound clients or a non-read-only MCP tool (internal/architecture/zerowrite/zerowrite_test.go).
Concerns
- Token replay protection is a process-local nonce map and the default signer key is ephemeral (usecases/release_work.go:213-231, approval.go NewEphemeralSigner), pinning the agent to one replica.
- The human-confirmation gate is not tied to an identity: POST /act/release-next-work/proposals and /approvals (internal/adapters/inbound/http/router.go:140-141) are unauthenticated, so any caller can propose and approve.
- By design every brief is a synchronous fan-out to many upstream MCP/REST endpoints (usecases/network_outlook.go, flow_balance_advisory.go), so latency and availability track the slowest dependency despite breakers.
Clean code
Strengths
- 25.3k test LOC vs 19.9k prod LOC; 704 test funcs, 103 godog scenarios, 33 fitness tests, evals-tests CI job; average function 14 lines, nothing above cyclo 15.
- Constructors fail fast on missing collaborators ('a half-wired act slice must fail at construction', release_work.go:128-134) and optional ones use functional options.
- Use-case and port names state intent and upstream source explicitly (flow_balance_advisory.go wesSource/wfmSource/feSource constants).
Concerns
- Four files exceed 500 lines: internal/adapters/inbound/http/router.go (943, routes + ~20 DTO mappers), internal/config/config.go (587), mcp/network_outlook.go (678), llm/anthropic/reasoner.go (575).
- Only 2 integration-tagged test files for an agent whose value is ~15 outbound integrations, and the mutation efficacy gate is 80%, the lowest in this sample (facts: gates.mutation_efficacy).
- Domain falls back to time.Now when no clock is injected (internal/domain/approval/approval.go:81-83); the same pattern repeats in release_work.go:138-140.
APIs and contracts
- MCP surface: 12 tools, all ReadOnly, consistent verb_noun names (get_daily_brief, triage_stuck_transfers, find_master_data_gaps), each description stating sources, bounds and that it never writes (internal/adapters/inbound/mcp/tools.go).
- Partial results are explicit: sections carry an omitted reason and complete flag ('an omitted section is NOT nothing to report'), with 5,000-record scan bounds and nextCursor resumption.
- Weakness: the ~15-route REST console (router.go:125-141) has no OpenAPI spec and returns ad-hoc {"error": ...} bodies instead of problem+json, often echoing err.Error() from upstreams (router.go:199,230).
- No A2A server skills and no events; recommendations such as detect_stranded_reservation are advisory and never call upstream write tools, matching the governance note.
MCP tools: 12 (12 read-only)
get_daily_brief | read | Return the full synthesized daily operational brief: every monitored site's paths with their backlog, staffing, queue, and stuck-task facts, plus the correlated open exceptions across all paths, ranked critical-first. |
list_open_exceptions | read | List the daily brief's correlated open exceptions, optionally filtered to a minimum severity (info, warning, or critical) |
get_flow_balance_exception | read | Correlate wes-work-planning's rebalance recommendation, workforce-management's staffing gap, and fulfillment-execution's stuck-task diagnostic for one process path into a single ranked FlowBalanceException recommendation |
explain_travel_factor | read | Estimate the real travel distance facility-layout computes between two caller-supplied location codes and classify whether that distance is a materially significant contributor to a slow path, or negligible |
detect_stranded_reservation | read | Correlate fulfillment-execution's expired/expiring task leases with inventory-storage's usable-stock shortfall for one SKU into a ranked StrandedReservationException recommendation (revoke_reservation or hold) |
find_master_data_gaps | read | List product-master products whose master data is missing or contradictory: unclassified (no handling classification, so hazmat/fragile/temperature handling is unknown downstream) and dimension-discrepancy (product-maste |
get_inbound_outlook | read | Report the inbound dock side's near-term picture from inbound-receiving: ASNs awaiting arrival (state Registered; overdue when their own expected arrival has passed), dock appointments in the next 24 hours (Booked or Che |
get_network_order_outlook | read | Assemble one customer order's retail-network picture across the wired read-only clients: the placed order with its lines and shipment groups (customer-ordering get_order), how each group is travelling with its packages a |
get_network_node_outlook | read | Assemble one fulfilment node's retail-network picture across the wired read-only clients: the node with its operational profile (node-topology get_node), the directed lanes into and out of it (list_lanes by destination/o |
triage_stuck_transfers | read | List inter-warehouse transfers (from network-inventory-planning) whose state has not changed for longer than the caller-supplied number of minutes, stalest first, each classified by where the saga is waiting (inventory r |
get_transfer_status | read | Read one inter-warehouse transfer from network-inventory-planning with its full audit trail (every state transition) and an advisory reading of where it is waiting |
explain_network_imbalance | read | Explain network-inventory-planning's advisory simulation: which sites are short of capacity over the plan window, which have headroom and may originate a transfer, and what an operator can check next |
Recommended next steps
- Move consumed-nonce state and the signing key to shared storage/secret so the agent can scale past one replica, and bind approvals to an operator identity.
- Publish an OpenAPI spec for the REST console and switch its errors to problem+json without leaking upstream error text.
- Split router.go into per-feature handler/DTO files and add integration tests against recorded upstream MCP responses.
Measured at origin/develop d1c5529 (2026-10-30). Review sampled 6 files.