Cross-node query and narrative wiring
This guide covers how engine/node_main.py and engine/erp_main.py wire three Tasks into a running node process:
- Order status query (
engine/order_status_query.py) - Inventory shortage/at-risk-order explainer (
engine/inventory_shortage.py) - Order-trail/genealogy narrative (
engine/order_narrative.py)
See ai-narrative-drafting-task-wiring.md for the Tasks themselves. Nothing in ERP or MES runtime startup depends on this wiring.
Which side queries, which side answers
Neither OrderStatusQueryTask nor InventoryShortageExplainerTask cares which Node Type instantiates it. Both take a peer_client and peer_node_type at construction or call time and work in either direction. The direction for each follows which Node Type's own local data answers the question.
| Query | Answered by | Queried by |
|---|---|---|
order_status_query |
MES (_answer_order_status, engine/node_main.py) |
ERP (order_status_query_task, engine/erp_main.py) |
in_progress_wip_for_material |
MES (_in_progress_orders_for_material, engine/node_main.py) |
ERP (inventory_shortage_task, engine/erp_main.py) |
| Order-trail/genealogy narrative | MES (order_narrative_task) |
No peer query. Local only. |
Why each direction
order_status_query. An order's current floor status (in-progress,blocked,completed,flaggedorat-risk) is what MES's ownOrderReleaseandOrderCompletioningestion already resolves onto the order'sIdentityRecord.attributes["status"]. That happens iningest_and_enqueueinengine/ingestion_pipeline.py, and Reconciliation'smerge_attributeskeeps it current. MES already knows this without a live poll of anything.in_progress_wip_for_material. This matches the module docstring ofengine/inventory_shortage.py: the shortage is "correlated against a peer node's current in-progress work-in-process".InventoryShortageExplainerTask'speer_node_typedefault is already"MES". The query itself is described inai-narrative-drafting-task-wiring.md, and MES is its live answering side.- Order-trail/genealogy narrative.
OrderNarrativeTasknever queries a peer. It takes an already-assembledOrderTrailorGenealogyas its input.assemble_order_trail(engine/order_trail.py) reads this Node's own Activity Log and IdentityStore. Given apeersclient, it asks each declared peer for its own entries and record over the Communication Interface (see section 4 oforder-trail-assembly.md).assemble_genealogy(engine/traceability.py) does the same withpeers(see section 4 oftraceability.md).- The Task is built on MES because MES already carries
store,activity_logandinference_client.
engine/node_main.py
MES answers peer queries
MES builds a PeerListener, so order status and in-progress-WIP queries can be asked at MES, as erp_main.py's listener answers ERP's.
_build_mes_answer dispatches on the shape of the incoming envelope, not just on event_fields["query"] the way erp_main.py's _build_answer does:
| Incoming envelope | Answered by |
|---|---|
event_fields["query"] == IN_PROGRESS_WIP_QUERY (the convention in engine/inventory_shortage.py) |
_in_progress_orders_for_material |
A bare order_id identity key with no event_fields at all |
The order status answer. OrderStatusQueryTask's outgoing envelope (engine/order_status_query.py) never sets a query marker of its own. This is the one shape no other query this Node instance answers can produce, so it is dispatched on directly. That avoids adding a marker field to an already built, already tested Task module. |
event_fields["query"] == "activity_log_entries" or "identity_record" |
This Node's own Activity Log entries, or its own identity record for one (entity_type, reference_id). Both are answered from its own stores only (see communication-interface.md). Every Node Type answers both. |
| Anything else | Empty event_fields: the same fail-safe-and-report stance erp_main.py's _build_answer takes. |
Where _in_progress_orders_for_material reads from
It reads two already-existing local stores, not a fresh live poll. MES's own OPC-UA ingestion is subscription-shaped (see the module docstring of engine/node_runtime.py). There is no per-order "read this one live" query like the RestPollingConnector.poll(path=...) override behind ERP's live standard_cost answer.
Instead, it works in three steps:
- Every
material_id-linked order comes from the Genealogy Link entries inengine/traceability.py(activity_log.query(reference_id=material_id), filtered toTASK_TYPE_GENEALOGY_LINK). - Each linked order is cross-referenced against its current
IdentityRecord.attributes["status"]. - It reports every order still reading
"in-progress", not just the first found. A shared material genealogy-linked to more than one order is not schema-prevented.
MesRuntime and order_narrative_task
MesRuntime carries store: IdentityStore. A caller needs it to assemble an OrderTrail or Genealogy before handing it to order_narrative_task.narrate(), and _answer_order_status needs it to look up an order's current status.
order_narrative_task is built whenever inference is configured. That is the same existing config fragment CaseTriage already requires, so no new Configuration Schema property is needed. It runs on demand: it is not scheduled and not wired to any TriggerHandler. This follows the "request/response shape, not a scheduled roll-up" precedent that time-ranged-activity-narrative.md established for TimeRangedActivityNarrativeTask. A caller assembles the trail or genealogy itself and calls .narrate(...) directly:
from engine.order_trail import assemble_order_trail
trail = assemble_order_trail(
runtime.store, runtime.activity_log, order_id, peers=runtime.peer_client
)
narrative = runtime.order_narrative_task.narrate(trail)
A caller outside the process asks for the same narrative over HTTP. The Node can serve it behind a correlation token (see order-narrative-route.md), and the route is off until its port is set.
runtime.peer_client is None unless the site configures the Communication Interface. The trail then holds this Node's entries alone, and it says so: it is not complete, and its narrative opens with an "Incomplete Trail" section stating that no peers were asked. A caller that knows the site is a single Node passes single_node=True instead of peers, and the trail is complete when its own parts are.
The listener and the outgoing pair
The listener and the outgoing peer_registry and peer_client pair are built together, whenever communication_interface is configured at all. This is the same "optional at the top level" convention every other fragment follows.
The pair is not tied to the costing_variance branch. shift_handoff's optional live "current shift" peer query (see shift-handoff-live-license-gating.md) is a second, independent consumer, and it must not require costing_variance to also be configured.
engine/erp_main.py
Configuration
ERP has an inference config fragment and an outgoing PeerRegistry and PeerClient pair. erp_main.py's PeerListener is purely an answering collaborator, and the pair is what lets build_erp_runtime query a peer. node-types/erp/node_type.json declares:
"dependentRequired": {
"inference": ["communication_interface"]
}
inference's schema fragment is a byte-for-byte copy of MES's (node-types/mes/node_type.json). InferenceClient is ERP's only consumer, for order_status_query_task and inventory_shortage_task below. The dependentRequired rule mirrors the config-time-enforced ordering that shift_handoff's own dependentRequired applies for MES.
What build_erp_runtime builds
Whenever inference is configured, build_erp_runtime builds:
- an
InferenceClient; - an outgoing
PeerRegistryandPeerClientpair, mirroring the costing-variance-poller pair inengine/node_main.py, including a"peer-rescan"ScheduledTaskon the samePEER_RESCAN_INTERVAL_SECONDScadence; - the two on-demand Tasks themselves,
OrderStatusQueryTaskandInventoryShortageExplainerTask, both querying"MES"as their peer.
Neither Task is scheduled or registered on handlers. A caller invokes .query() or .explain() directly:
result = runtime.order_status_query_task.query(order_id, "MES")
explanation = runtime.inventory_shortage_task.explain(
MaterialShortage(material_id=material_id, shortage_quantity=160.0, unit="each")
)
node-types/erp/example_node_config.json
"inference": {
"endpoint": "http://ollama.example.local:11434",
"model": "example-llm",
"context_window_tokens": 32768,
"reserved_output_tokens": 2048,
"reasoning_effort": "none",
"backend_trust": "local"
}
This matches the inference fragment of MES's example config exactly (same endpoint, model and limits). The example configs share one inference target across all Node Types, not one scoped per Node Type.
Testing without a live simulator
- MES's answering side is proved directly in
tests/test_node_main.py. A rawPeerClientstands in for ERP, the same "stand in for the other side" precedent the costing-variance tests establish in reverse. It queries a real loopbackPeerListenerseeded with realIdentityStoreandActivityLogstate. - ERP's querying side is proved in
tests/test_erp_main.pyagainst a real MES peer._build_minimal_mes_peerbuilds a genuineengine.node_main.build_mes_runtimeinstance, with bareopcuaandcommunication_interfaceconfig and nothing else (the rest of the MES runtime is covered elsewhere), and points ERP'scommunication_interface.peersat its real bound loopback port. These tests run against a running MES+ERP pair, not a stand-in on either side, for bothorder_status_query_taskandinventory_shortage_task. - A shared table.
activity_log(tests/conftest.py) is the one real production table shared across every test in the suite. It is not isolated per test the way thestoreandqueuefixtures are (IdentityStoreandTriggerQueueboth take atable_name=override;ActivityLogdoesn't). Both integration tests therefore use auuid.uuid4()-suffixedmaterial_idrather than a fixed literal (already reused by several other tests intests/test_erp_main.py), soactivity_log.query(reference_id=...)can't pick up an unrelated test's entries.
Pitfalls
_answer_order_statusvalidates the stored status againstengine.envelope.Status's literal set (engine.envelope.is_status) before putting it on the wire. A misconfiguredfield_mapcan resolve some other string, or a value that is not a string at all (a list, an object), intoattributes["status"]. That answersstatus=None, the same fail-safe-on-the-unknown stance thatOrderStatusQueryTask's ABNORMAL branch expects. The alternative would be handing aCrossTypeEnvelopea value its ownStatusfield would reject._in_progress_orders_for_materialonly finds orders if something upstream has written Genealogy Link entries. It walks the entries that genealogy-link a material to orders, a mechanism Traceability builds for a different purpose. It never queries the shortage-observing order's own material.engine/node_main.py's optionalmaterial_consumptionconfig fragment is that something.engine.node_runtime.OpcuaMaterialConsumptionPollerpolls a configured OPC UA node for amaterial_idreading and callsGenealogyLinkTask.runagainst this Node instance's configuredorder_idwhenever it changes. This is the same "integrator addresses the gap at the source" framing the module docstring ofengine/traceability.pydocuments for genealogy data generally.- A simulator's
consume_materialcommand is one such source. material_consumptionis optional, notdependentRequiredon anything. A Node instance that never configures it answers this query[].
- ERP's
build_erp_runtimehas no close-on-partial-failure safety net, unlike MES's_build_optional_mes_collaboratorsand_close_mes_collaboratorspair. IfInferenceClientsucceeds but a later collaborator in the sameif "inference" in config:block raises (a missing prompt asset file, say),inference_client's eagerly openedhttpx.Clientleaks. The same gap exists forconnectorandproducerin that function. order_narrative_taskshares MES's singleinference_clientwithCaseTriage. Both are built in the sameif "inference" in config:branch, andShiftHandoffTaskshares it too. A real deployment's inference endpoint sees all of these Tasks' calls.
Release: v0.11.0