AI-Narrative-Drafting Tasks: Use Cases
This guide covers the Tasks that draft a narrative, an explanation or a summary from the engine's data. For each built-in use case it says whether the use case runs through an existing mechanism or has a Task of its own, and how each Task is wired to its prompt asset, its peer queries and the sign-off store.
Use cases that need no extra wiring
-
Point-of-use SOP lookup (
engine/playbook_answer.py) is already fully working. -
SPC/deviation alert explainer and non-conformance disposition drafting are both already fully working, and both are routed through the same generic mechanism:
engine/deviation_flagging.py's threshold check fires a"deviation"-typedTriggerQueueEntry.CaseTriageinengine/case_triage.pyaggregates it and drafts a summary through one shared prompt asset,engine/prompts/case_summary_drafting.md.
Both use cases currently draw from that single prompt asset. They are differentiated only by trigger data, not wording. Watch for output that reads too similar across the two.
Tasks added
Six Tasks cover the remaining use cases. Reconciliation is folded into the shift-handoff Task (Task 6) rather than being a standalone Task.
| # | Task | Module |
|---|---|---|
| 1 | First Article Inspection | engine/first_article_inspection.py |
| 2 | Order-trail/genealogy narrative | engine/order_narrative.py |
| 3 | Order status query | engine/order_status_query.py |
| 4 | Costing Milestone variance explainer | engine/costing_variance.py |
| 5 | Inventory shortage/at-risk-order explainer | engine/inventory_shortage.py |
| 6 | Shift-handoff summary drafting | engine/shift_handoff.py |
1. First Article Inspection — engine/first_article_inspection.py
from engine.first_article_inspection import FirstArticleInspectionTask
from engine.identity_resolution import EntityType, IdentityObservation
task = FirstArticleInspectionTask(store, activity_log, "MES", "mes-line-3")
check = task.run(
IdentityObservation(entity_type=EntityType.QUALIFICATION, reference_id="VENDOR-A:PART-100")
)
# check.outcome: CLEAN_MATCH (proceeds silently) or FLAGGED_FIRST_ARTICLE (IdentityStatus.PENDING)
This is thin Trigger/Task wiring on top of Identity Resolution's explicit and inferred matching. A new vendor lot or first-time product is a Qualification Identity observation, the third of EntityType's own three entity types.
It reuses Identity Resolution's pieces but not its policy. The Task uses IdentityStore, attribute_overlap_matcher and IdentityStatus.PENDING directly, but does not call IdentityResolver.resolve(), because First Article Inspection inverts the resolver's terminal-outcome policy:
IdentityResolver (Order, Material) | First Article Inspection (Qualification) | |
|---|---|---|
| Explicit-branch miss | Resolves as NEW/RESOLVED silently. A first appearance is normal and not flag-worthy. |
Flagged IdentityStatus.PENDING. "No prior history" is the flag-worthy case. |
| Clean explicit match against an already-qualified prior record | Resolved | The only case that proceeds silently. |
| Inferred candidate | Handled by the resolver | Attached to the flag as a lead, not a reason to skip flagging. |
EntityType.ORDER and EntityType.MATERIAL keep behaving exactly as before. Nothing here changes IdentityResolver's generic policy.
2. Order-trail/genealogy narrative — engine/order_narrative.py
from engine.order_narrative import OrderNarrativeTask
task = OrderNarrativeTask(inference_client, narrative_prompt, activity_log, "MES", "mes-line-3")
narrative = task.narrate(trail) # OrderTrail or Genealogy, unchanged
engine/order_trail.py and engine/traceability.py do pure deterministic assembly, with no InferenceClient call in either file. OrderNarrativeTask.narrate is the second, separate step that turns the assembled graph into a narrative. It drafts through its own prompt asset, engine/prompts/order_trail_narrative_drafting.md, and is never merged into one call with assembly, per the AI Boundary.
The chronological history is not model-written
For an OrderTrail, the prompt (v0.5.0, ORDER_NARRATIVE_PROMPT_VERSION in engine/node_main.py) asks for three named sections. It tells the model to put the single line [[CHRONOLOGY]] at the end of the "Order Trail & Processing History" prose.
OrderNarrativeTask then replaces that line with one bullet per OrderTrail.entries row, in the order assembly produced them. Each bullet has the entry's time in UTC and a plain sentence for what it records.
- Where the sentences come from.
engine/activity_plain_text.pyholds a table keyed on the entry's task type, trigger and outcome. An entry it has no sentence for shows its raw fields instead, never a guessed description. - What the list covers. The Activity Log entries for that order as they stood when the call started. The call's own entry is written after the list is built, so it appears in later trails, not this one.
- If the model leaves the marker out. The same list is added at the end of the section whose heading names "order trail", or under its own heading if there is none.
- Genealogy. A
Genealogygets no list. - Why code writes it. Size as well as accuracy. The output cap is the configured
reserved_output_tokens(a few hundred tokens in the example configs), and a narrative already uses most of it. A model-written list would be cut off mid-way with nothing to say so. - Inference-disabled mode is unchanged, because its fact listing already lists every entry.
An incomplete trail says so
An OrderTrail built with peers (see section 4 of order-trail-assembly.md) can lack a Node's part. The payload then carries four extra fields:
completethis_node_completemissing: each Node Type that did not contribute, and the fetch outcomerecord_disagreements: the Node Types whose identity records differ, and whether in "status" or "attributes"
The prompt tells the model to say the account is partial and not to describe what a missing Node did. These four fields are built from this Node's own config and the outcome, so no address and no failure detail reaches the model.
A peer's entries are another matter. They are in the trail on purpose and carry the peer's own task_type, outcome and reference_ids, which reach the model and the timeline unchanged.
The model's own words are not what makes the trail's state visible. Code writes the sections, in the drafted narrative and in the inference-disabled fact listing:
- An "Incomplete Trail" section ahead of the model's first section, naming each missing Node Type and why.
- A "Records Differ" section naming the Node Types whose identity records differ.
A complete trail whose records agree has neither section. A cached narrative is never reused for a trail that differs in completeness, because the cache is keyed on the payload.
An incomplete genealogy is told the same way
A genealogy that is INCOMPLETE gains these payload fields:
causes: why, asIncompleteCausevaluesmissing: the Node Type and outcome of each declared peer that did not contributethis_node_completematerials_not_looked_up: a count
Code writes an "Incomplete Genealogy" section ahead of the model's prose, and in the inference-disabled fact listing, saying each cause and each missing Node Type. That covers every cause of an incomplete genealogy, including the four that predate peers: no link data, a link its source flagged, a malformed link, and an unresolved material. A complete genealogy has no such section. The ids in a peer's links reach the model unchanged, as a trail's entries do.
3. Order status query — engine/order_status_query.py
from engine.order_status_query import OrderStatusQueryTask
task = OrderStatusQueryTask(
peer_client, inference_client, reasoning_prompt, activity_log, "ERP", "erp-1"
)
result = task.query("MO-1001", "MES")
# result.reasoning is None for a plain in-progress/completed status - no AI call made at all.
# blocked/flagged/at-risk (or no status reported) routes through a second call that appends
# result.reasoning, drafted through engine/prompts/order_status_abnormal_reasoning.md.
This Task runs on demand, not on a schedule. It live-queries a peer through the Communication Interface's PeerClient.
A RULE-mode Gate makes the normal-versus-abnormal split. A missing or unrecognized status is treated as abnormal, not silently normal. This fails safe on the unknown, the same stance engine/deviation_flagging.py takes with NaN.
4. Costing Milestone variance explainer — engine/costing_variance.py
from engine.costing_variance import build_variance_data_point
point = build_variance_data_point(
peer_client,
data_point_id=...,
order_id="MO-1001",
milestone_type="final",
actual_cost=130.0,
data_source="costing_milestone_variance",
node_instance_id="mes-line-3",
)
# point.values: {"actual_cost": 130.0, "standard_cost": <live ERP figure>, "variance_pct": ...}
# feeds straight into DeviationFlagging.check/check_batch, completely unchanged.
Detection and narrative already existed generically (Deviation Flagging, then Case Triage). The one real gap was the live standard-cost figure feeding DeviationRule's DataPoint. This module fills only that gap.
- ERP's
CostingMilestoneevent type (node-types/erp/node_type.json) deliberately carries no standard or budgeted cost field. - The module queries the figure live through
PeerClient, under theevent_fieldsconvention{"query": "standard_cost", "milestone_type": ...}out and{"standard_cost": <figure>}back. - A non-positive or missing standard cost fails closed (
CostingVarianceError) rather than producing a meaningless variance. - The detection Gate and Case Triage's narrative step are untouched. Only the data source is new.
5. Inventory shortage/at-risk-order explainer — engine/inventory_shortage.py
from engine.inventory_shortage import InventoryShortageExplainerTask, MaterialShortage
task = InventoryShortageExplainerTask(
peer_client, inference_client, explainer_prompt, activity_log, "ERP", "erp-1"
)
explanation = task.explain(MaterialShortage(material_id="LOT-1", shortage_quantity=50))
This is a genuine new cross-node correlation Task, not a threshold check. It queries MES's current in-progress WIP for the shortage material ({"query": "in_progress_wip_for_material"} out, {"in_progress_orders": [...]} back). It then drafts a prioritized explanation through its own prompt asset, engine/prompts/inventory_shortage_explanation_drafting.md.
It is reactive against current WIP only and does not depend on Production Scheduling forecasts.
6. Shift-handoff summary drafting, covering the Reconciliation explainer — engine/shift_handoff.py
from engine.shift_handoff import ShiftHandoffTask
from engine.node_runtime import ScheduledTask
task = ShiftHandoffTask(
inference_client, summary_prompt, signoff_store, activity_log, "MES", "mes-line-3"
)
scheduled = ScheduledTask(name="shift-handoff", interval_seconds=28800, run=task.run_scheduled)
One roll-up narrates both
ReconciliationTask in engine/identity_resolution.py matches and merges deterministically, with no inference call. "What changed and why" is therefore drafted by the same scheduled roll-up as the shift handoff, not by a competing Task.
ShiftHandoffTask.run(window_start, window_end) aggregates two things within the window:
- this node's own Activity Log entries;
- still-pending drafted entries (
SignoffStore.list_pending).
It explicitly calls out any entries whose task_type is TASK_TYPE_RECONCILE ("Reconciliation") rather than folding them in silently.
run_scheduled() is the zero-argument entrypoint shaped for ScheduledTask.run. It summarizes since its own last scheduled call. For the very first call, the start is bootstrapped to shift_duration before construction time.
Sign-off
The summary is submitted to SignoffStore as record_type="shift_handoff_summary" and submitted_by="ai-draft". This is the same Mandatory-Human Status convention engine/case_triage.py's drafts follow: AI-drafted content does not become canonical without a human sign-off pass.
No new data source
Everything this module reads is already collected for other Tasks. Both window filters run at the SQL WHERE-clause level, through ActivityLog.query's and SignoffStore.list_pending's own start/end filters.
The drafting call is shared with TimeRangedActivityNarrativeTask through draft_narrative in engine/narrative_drafting.py. See time-ranged-activity-narrative.md for the generalization.
Alerts in the shift handoff
A Node that raises instruction conformance alerts passes ShiftHandoffTask an alert_source (the acknowledgement store, through node_main). Each summary then opens with the alerts that had no acknowledgement when its window ended. The task only ever reads the source, through unacknowledged_as_of(window_end, limit=20).
-
Which alerts. Finished alerts raised before the window's end, however long before, that either have no acknowledgement or were acknowledged at or after that moment. So:
- an alert from an earlier shift that nobody answered is listed again;
- an alert acknowledged inside the window is not;
- an on-demand
run()over a past window gives the answer it would have given then.
-
Code writes the lines, from the table. They come oldest first, behind the coverage notice when there is one and in front of whatever else the summary says, on every path (drafted, inference off, unlicensed, degraded):
Alerts waiting for acknowledgement: N., then one line per alert: raised, binding, limit crossed, measured value and limit with the unit, product and operation, repeats, alert id.- The repeat count is the count when the handoff was drafted, not as of the window's end, because the table keeps a count and the time of the last repeat, not a time for each.
- At most
MAX_ALERT_LINES(20) are listed. The count is the whole one, followed by "and N more not listed". - None waiting reads "No alerts waiting for acknowledgement."
-
The model never sees them.
- The payload's
countsgainsunacknowledged_alerts, a number, and the stated-count check rejects a draft that states a different number of unacknowledged alerts. - The lines, the labels and the measured values are not in the prompt.
- An alert's own entry and an acknowledgement's entry are kept out of the activity list the model reads and out of
activity_count, as a coverage gap is, because each carries those labels and values. - For the same reason, the drafted explanation of an alert (a pending
case_summaryrecord that names the alert in itsalert_id) is kept out ofpending_drafted_entries, the precedent query andpending_case_count. It is reviewed as its own record.
- The payload's
-
The record gains three fields. Records stored before these existed do not have them.
unacknowledged_alert_count: a number, ornullfor no source or an unreadable one.unacknowledged_alerts: the listed alerts' id, time, binding and limit.alerts_unavailable:not_upgraded,unreadableornull.
-
When the alerts cannot be read.
Situation What the handoff says No alert_source, or no alerts table at allNo alert section. The alerts table exists but the acknowledgements table does not "could not be listed: this Node has not yet upgraded its alert tables" Any other database error "could not be read". The log line names the error's type only. In every case the handoff is still drafted, and it never reads as "no alerts".
Cross-node event_fields conventions
CrossTypeEnvelope's own schema (engine/envelope.py) does not enforce any of these, because event_fields is deliberately free-form, scoped per event type. They are conventions that a peer's cross-node dialogue answer callable needs to honor. They are documented here so they don't silently drift.
Query (event_fields) | Response (event_fields) | Used by |
|---|---|---|
{"query": "standard_cost", "milestone_type": ...} |
{"standard_cost": <float>} |
Costing Milestone variance |
{"query": "in_progress_wip_for_material"} |
{"in_progress_orders": [...]} |
Inventory shortage explainer |
{"query": "activity_log_entries", ...} |
{"entries": [...], "next_cursor": ...} |
Order trail and genealogy across Nodes |
{"query": "identity_record", "entity_type": ..., "reference_id": ...} |
{"record": {...} | null} |
Order trail and genealogy across Nodes |
The table is not exhaustive:
- Production Scheduling's answerer also serves
current_shift(engine/production_scheduling_answering.py). - ERP serves
material_held_for_orders(engine/erp_main.py) andreport(engine/erp_reporting_wiring.py). - The
activity_log_entriesandidentity_recordrows are described, with their request and answer fields, incommunication-interface.md.
Order status query has no query-side convention of its own. It reads status directly off the envelope's reserved field (the Status literal in engine/envelope.py), not a custom event_fields key.
Pitfalls
- First Article Inspection never auto-resolves a flagged record back to
RESOLVED. That transition is the Mandatory-Human Sign-off Mechanism's job, out of band. This module only ever sets the flag. OrderNarrativeTask,InventoryShortageExplainerTaskandbuild_variance_data_pointeach spend a real inference or peer-query call per invocation.InventoryShortageExplainerTaskandbuild_variance_data_pointdon't cache or dedupe repeated calls for the same material within a short window, so a caller invoking one in a tight loop pays every time.OrderNarrativeTaskhas an opt-incache(outcomenarrated_cachedon a hit); seeorder-narrative-result-caching.md. Without a cache wired in, it behaves the same way.ShiftHandoffTaskonly ever sees still-pending drafted entries. An already approved or rejected case from earlier in the shift won't appear in the roll-up. This is a deliberate scope choice (a handoff cares about "what's still awaiting review", not a full historical record), but it matters if a reviewer expects otherwise.ShiftHandoffTask's window filtering runs at the SQL level, throughActivityLog.query's andSignoffStore.list_pending'sstart/endfilters. It is not an in-memory Python filter over every entry for this node.- Order status query's abnormal-versus-normal Gate treats a missing
statusas abnormal. A peer that answers with nostatusset at all (legal, sinceCrossTypeEnvelope.statusisStatus | None) always triggers the AI reasoning call, even if the omission was benign on the peer's side.
Release: v0.11.0