Skip to content
TRUMANUS EDIZIONI ↗Andrea Lagomarsini’s personal space
Andrea LagomarsiniAuthor · Principal AI / GenAI Architect
← All articles

Author’s archive

LangGraph for Tactical Command & Control — Part 2

In the first article we defined the graph: state, nodes, checkpoints, OODA architecture.

Andrea Lagomarsini nella copertina dell’articolo «LangGraph per Command & Control tattico — Parte 2»
Article illustration · Andrea Lagomarsini archive

Multi-agent and human-in-the-loop orchestration

Technical series · Article 2 of 3

In the first article we defined the graph: state, nodes, checkpoints, OODA architecture.

Now the operational question: who does what inside each node?

In a tactical C2 there is no "super-agent" who knows everything. There are separate competencies — sensor correlation, threat assessment, ROE compliance, resource allocation — that must coordinate without losing control.

LangGraph supports three patterns that I use in production:

  1. Subgraph — nested graphs for isolated domains
  2. Supervisor — a node that delegates to specialized agents
  3. Human-in-the-loop — interrupt, timeout, escalation

Pattern supervisor: a digital TOC

flowchart LR
    subgraph SUP["Supervisor Node"]
        SV[Router LLM + policy]
    end

    subgraph AGENTS["Agenti specializzati"]
        A1[Sensor Fusion Agent]
        A2[Threat Assessment Agent]
        A3[ROE Compliance Agent]
        A4[Asset Tasking Agent]
    end

    EVT[Evento significativo] --> SV
    SV -->|fusion_needed| A1
    SV -->|threat_unclear| A2
    SV -->|roe_check| A3
    SV -->|ready_to_task| A4

    A1 --> ST[(C2State)]
    A2 --> ST
    A3 --> ST
    A4 --> ST

The supervisor does not decide the final action. Decides which skill to activate based on the current state. It's the difference between "AI that leads" and "AI that supports the decision cycle".


Implementation: supervisor with deterministic routing + LLM

In high reliability environments I don't rely on the LLM alone for critical routing. I use a hybrid:

def supervisor_router(state: C2State) -> str:
    # Regole deterministiche — sempre prima
    if state["roe_status"] == "NON_COMPLIANT":
        return "roe_compliance"  # forza revisione
    if state["human_approval"] == "PENDING":
        return "human_gate"
    if not state["tracks"]:
        return END

    # LLM solo per ambiguità
    if state["threat_level"] == "MEDIUM" and has_conflicting_sources(state):
        return "threat_assessment"

    return "asset_tasking"

The LLM enters node threat_assessment to synthesize contradictory sources, not to bypass ROEs.


Threat Assessment Agent: structured output

from langchain_core.messages import SystemMessage
from pydantic import BaseModel, Field

class ThreatAssessment(BaseModel):
    threat_level: Literal["LOW", "MEDIUM", "HIGH", "CRITICAL"]
    confidence: float = Field(ge=0.0, le=1.0)
    key_indicators: list[str]
    uncertainty_factors: list[str]
    recommended_posture: Literal["MONITOR", "ELEVATE", "ENGAGE_REQUEST"]

def threat_assessment_node(state: C2State) -> dict:
    model = chat_model.with_structured_output(ThreatAssessment)

    assessment = model.invoke([
        SystemMessage(content=THREAT_ASSESSMENT_PROMPT),
        *state["messages"],
    ])

    return {
        "threat_level": assessment.threat_level,
        "messages": [("ai", assessment.model_dump_json())],
        "audit_trail": [{
            "node": "threat_assessment",
            "output": assessment.model_dump(),
            "tracks_count": len(state["tracks"]),
        }],
    }

Structured output (Pydantic) eliminates fragile parsing. In C2, a malformed threat_level is not a cosmetic bug — it's an operational risk.


Subgraph for Sensor Fusion

Multi-sensor fusion has its own internal loop. I isolate it in a subgraph:

flowchart TB
    START2([START]) --> INGEST2[Normalizza feed]
    INGEST2 --> DEDUP[Deduplica track]
    DEDUP --> CORR[Correlazione spazio-temporale]
    CORR --> CONF{Confidence > soglia?}
    CONF -->|No| ENRICH[Arricchimento LLM]
    ENRICH --> CORR
    CONF -->|Sì| OUT2([Return tracks])
def build_fusion_subgraph():
    sg = StateGraph(FusionState)
    sg.add_node("normalize", normalize_feeds)
    sg.add_node("dedup", deduplicate_tracks)
    sg.add_node("correlate", spatiotemporal_correlation)
    sg.add_node("enrich", llm_enrich_low_confidence)
    # ... edges ...
    return sg.compile()

# Nel grafo principale
fusion_app = build_fusion_subgraph()
graph.add_node("sensor_fusion", fusion_app)

Advantages:

  • Unit test of subgraph without mocking all C2
  • Independent deployment — I update the merge without touching tasking
  • Reuse — same subgraph in practice and in production with different checkpointer

Human-in-the-loop: the most critical node

sequenceDiagram
    participant G as LangGraph
    participant CP as Checkpointer
    participant UI as Console operatore
    participant T as Timeout worker

    G->>CP: Salva stato (human_approval=PENDING)
    G-->>UI: Notifica proposta azione
    Note over G: interrupt_before human_gate

    alt Operatore approva entro 15 min
        UI->>G: update_state(APPROVED)
        G->>G: Resume → execute
    else Timeout
        T->>G: update_state(TIMEOUT)
        G->>G: Resume → escalation branch
    else Operatore rifiuta
        UI->>G: update_state(REJECTED)
        G->>G: Resume → feedback
    end
def human_approval_gate(state: C2State) -> dict:
  """Nodo pass-through: la decisione arriva da update_state esterno."""
  return {
      "audit_trail": [{
          "node": "human_gate",
          "status": state.get("human_approval", "PENDING"),
          "proposed_actions": state["proposed_actions"],
      }]
  }

def route_after_approval(state: C2State) -> str:
    approval = state.get("human_approval")
    if approval == "APPROVED":
        return "approved"
    if approval == "REJECTED":
        return "rejected"
    if approval == "TIMEOUT":
        return "escalate"
    return "pending"

# Compile con interrupt
app = graph.compile(
    checkpointer=checkpointer,
    interrupt_before=["human_gate"],
)

Operator console API

@app.post("/missions/{thread_id}/approve")
async def approve_action(thread_id: str, payload: ApprovalRequest):
    config = {"configurable": {"thread_id": thread_id}}

    # Verifica che il grafo sia effettivamente in pausa al gate
    snapshot = app.get_state(config)
    if snapshot.next != ("human_gate",):
        raise HTTPException(409, "Mission not awaiting approval")

    app.update_state(config, {
        "human_approval": payload.decision,
        "audit_trail": [{
            "node": "operator_console",
            "operator_id": payload.operator_id,
            "decision": payload.decision,
            "timestamp": utcnow().isoformat(),
        }],
    })

    # Riprende in background
    background_tasks.add_task(app.invoke, None, config)
    return {"status": "resumed"}

get_state().next is crucial: it prevents out-of-context or duplicate approvals.


Parallelization: fan-out / fan-in

When a CRITICAL event arrives, correlation and threat assessment can start in parallel:

flowchart TB
    C[classify] --> P[Parallel node]
    P --> F[sensor_fusion]
    P --> T[threat_assessment]
    F --> M[merge_results]
    T --> M
    M --> R[validate_roe]
from langgraph.graph import StateGraph

graph.add_node("parallel_analysis", parallel_analysis_node)

def parallel_analysis_node(state: C2State):
    # LangGraph supporta Send API per fan-out dinamico
    return [
        Send("sensor_fusion", state),
        Send("threat_assessment", state),
    ]

graph.add_node("merge_results", merge_parallel_outputs)

The merge_results node uses a state reducer to fuse output without race conditions.


Guardrail: what NOT to delegate to the LLM

DecisionWho takes itWhy
Geometric classification trackDeterministic codeRepeatability, latency
ROE validation hard rulesRule engineCompliance, audit
Summary of the situational pictureLLM + structured outputNatural language understanding
Constrained asset allocationAlgorithm + LLM explanationOptimization with constraints
HIGH/CRITICAL action approvalHuman operatorAccountability

The most common mistake: "let's put one agent who does everything". In C2, governance is architectural, not a "be safe" prompt.


Streaming to the console

For TOC you need real-time feedback, not just the final result:

async for event in app.astream(
    initial_state,
    config,
    stream_mode=["updates", "custom"],
):
    if "classify" in event:
        await websocket.send_json({
            "type": "threat_update",
            "data": event["classify"],
        })
    if "human_gate" in event:
        await websocket.send_json({
            "type": "approval_required",
            "actions": event["human_gate"]["proposed_actions"],
        })

astream with stream_mode="updates" allows the UI to show step reasoning, not a black box.


Graph test: CRITICAL scenario with blocking ROE

def test_critical_event_blocked_by_roe():
    app = build_c2_graph().compile(checkpointer=MemorySaver())
    config = {"configurable": {"thread_id": "test-001"}}

    state = app.invoke({
        "tracks": [mock_track(confidence=0.95)],
        "threat_level": "CRITICAL",
        "roe_status": "PENDING",
        "messages": [],
        "audit_trail": [],
    }, config)

    # Deve fermarsi al gate, non eseguire
    snapshot = app.get_state(config)
    assert snapshot.next == ("human_gate",)
    assert state["roe_status"] in ("COMPLIANT", "ESCALATED")
    assert len(state["proposed_actions"]) > 0

Test the graph like you test a state machine — not like you test a chatbot.


🔥 Takeaway

Multi-agent orchestration in LangGraph for Tactical C2 works when:

  • The supervisor routes, does not command
  • The agents are specialized with structured outputs
  • The human gate is a first-class node, not a input() in the code
  • The hard rules remain deterministic

In the next article — the last one in the series — we bring everything into production: deployment edge, observability, resilience, audit trail for compliance and lessons learned in the field.

From the author’s archive. Publication date not specified.
← All articles