version: 2
title: NetScaler CVE Detection with LLM-Augmented Streams
contributor: https://github.com/neewamp
summary: Graph-owned exploit-chain detections over NetScaler telemetry, with LLMs extracting unstructured streams at ingest and writing incident briefs at output.
description: >
  Sequel to the thatDot CVE-2026-88779 detection post. The detections are unchanged graph
  predicates: timing (auth within 60 s of a crash), repetition (3 crashes in a trailing 15
  minutes, promotion at 2+ crashes and 2+ requests estate-wide), and shape (egress to a host
  no healthy appliance ever contacted). The LLM procedures sit at the edges only. At ingest,
  llm.decide scores how payload-shaped each auth username is (an evidence flag; it gates
  nothing), and llm.prompt extracts structure from helpdesk tickets. At output, when the
  kill-chain detection assembles an Incident, llm.decide gates severity and llm.prompt writes
  a human-readable brief from the evidence the graph collected. A vendor advisory arrives
  later, appended to data/live.ndjson; llm.prompt extracts its IOCs onto the same IP nodes
  the graph already built.

  Model endpoints come from system config under quine.llm: completion = Claude on Amazon
  Bedrock (anthropic-messages against the Bedrock compatibility endpoint, api-key auth),
  decision = hosted Jev.

ingestStreams:
  # ---- SAML auth log. Builds (IP)-[:SENT]->(AuthEvent)-[:TO]->(Appliance) and asks the
  # decision model for one calibrated judgment per record. The score is evidence for an
  # analyst and for the brief; no detection reads it.
  - name: saml-auth
    source:
      type: File
      path: data/auth.ndjson
      format:
        type: JsonL
    parallelism: 8
    query: |
      MATCH (ip), (auth), (app)
        WHERE id(ip)   = idFrom('ip', $that.src_ip)
          AND id(auth) = idFrom('auth', $that.event_id)
          AND id(app)  = idFrom('appliance', $that.appliance)
      CALL llm.decide(
        {username: $that.username},
        {payload: {type: "yes-no",
                   instructions: "Is this authentication username a machine-generated or injection-style string rather than a name a person would sign in with?"}}
      ) YIELD answers
      SET ip.ip = $that.src_ip, ip: IP,
          auth.username = $that.username,
          auth.endpoint = $that.endpoint,
          auth.ts = $that.ts,
          auth.epoch = $that.epoch,
          auth.suspicionScore = answers.payload.probability,
          auth.payloadShaped = answers.payload.probability >= 0.8,
          auth: AuthEvent,
          app.host = $that.appliance, app: Appliance
      CREATE (ip)-[:SENT]->(auth)-[:TO]->(app)

  # ---- HTTP access log. Structure only; costs no model call.
  - name: http-access
    source:
      type: File
      path: data/http.ndjson
      format:
        type: JsonL
    query: |
      MATCH (ip), (req), (app)
        WHERE id(ip)  = idFrom('ip', $that.src_ip)
          AND id(req) = idFrom('http', $that.request_id)
          AND id(app) = idFrom('appliance', $that.appliance)
      SET ip.ip = $that.src_ip, ip: IP,
          req.method = $that.method, req.uri = $that.uri, req.status = $that.status,
          req.ts = $that.ts, req.epoch = $that.epoch, req: HttpRequest,
          app.host = $that.appliance, app: Appliance
      CREATE (ip)-[:REQUESTED]->(req)-[:TO]->(app)

  # ---- System events: crashes, restarts, file writes. Costs no model call. Throttled so
  # each crash's standing-query attribution completes before the next crash arrives; the
  # promotion recount reads edges the earlier enrichments wrote.
  - name: system-events
    source:
      type: File
      path: data/sysevents.ndjson
      format:
        type: JsonL
    maxPerSecond: 2
    query: |
      MATCH (ev), (app)
        WHERE id(ev)  = idFrom('sysevent', $that.event_id)
          AND id(app) = idFrom('appliance', $that.appliance)
      SET ev.event_type = $that.event_type, ev.process = $that.process,
          ev.path = $that.path, ev.user = $that.user,
          ev.ts = $that.ts, ev.epoch = $that.epoch, ev: SysEvent,
          app.host = $that.appliance, app: Appliance
      CREATE (ev)-[:ON]->(app)

  # ---- Firewall egress. Structure only; costs no model call.
  - name: firewall-egress
    source:
      type: File
      path: data/egress.ndjson
      format:
        type: JsonL
    query: |
      MATCH (app), (out), (dst)
        WHERE id(app) = idFrom('appliance', $that.appliance)
          AND id(out) = idFrom('outbound', $that.egress_id)
          AND id(dst) = idFrom('ip', $that.dest_ip)
      SET app.host = $that.appliance, app: Appliance,
          out.dest_port = $that.dest_port, out.proto = $that.proto,
          out.ts = $that.ts, out.epoch = $that.epoch, out: Outbound,
          dst.ip = $that.dest_ip, dst: IP
      CREATE (app)-[:CONNECTED_TO]->(out)-[:DEST]->(dst)

  # ---- Helpdesk tickets: free text from people. The chat model extracts which service the
  # ticket concerns and whether it reports a remote-access outage; a null response (output
  # failed the schema) leaves the ticket visibly unextracted rather than silently irrelevant.
  - name: helpdesk
    source:
      type: File
      path: data/helpdesk.ndjson
      format:
        type: JsonL
    query: |
      MATCH (t) WHERE id(t) = idFrom('ticket', $that.ticketId)
      CALL llm.prompt(
        'You are reading one helpdesk ticket, provided in the data block. Decide which service it concerns: "vpn" for remote access or VPN connectivity, "sso" for single sign-on or login portals, or "other". Summarize the symptom in at most eight words. Decide whether the ticket plausibly reports an outage or failure of remote access or sign-on (outageReport). Base everything only on the ticket text.',
        {ticket: $that.text},
        {schema: {
           type: 'object', additionalProperties: false,
           required: ['service', 'symptom', 'outageReport'],
           properties: {
             service: {type: 'string', maxLength: 10},
             symptom: {type: 'string', maxLength: 80},
             outageReport: {type: 'boolean'}
           }
        }}
      ) YIELD response
      SET t.ticketId = $that.ticketId, t.user = $that.user,
          t.ts = $that.ts, t.epoch = $that.epoch, t.text = $that.text,
          t.service = response.service, t.symptom = response.symptom,
          t.outageReport = response.outageReport,
          t.extracted = response IS NOT NULL,
          t: Ticket
      WITH t, response
      WHERE response IS NOT NULL AND response.outageReport = true AND response.service IN ['vpn', 'sso']
      MATCH (svc) WHERE id(svc) = idFrom('service', response.service)
      SET svc.name = response.service, svc: Service
      CREATE (t)-[:REPORTS]->(svc)
      // A ticket can arrive after the incident's brief already fired. This side writes the
      // same CORROBORATED_BY edge for that order; Quine edges are a set, so a ticket the
      // brief already linked is not duplicated.
      WITH t, svc
      MATCH (svc)<-[:AFFECTS]-(inc:Incident)
      WHERE abs(t.epoch - inc.epoch) <= 2700000
      CREATE (inc)-[:CORROBORATED_BY]->(t)

  # ---- Late input. Reads data/live.ndjson in NAMED_PIPE mode: Quine reads to the end,
  # then checks the file again every second. The kit ships the file empty. Append
  # data/advisory.ndjson to deliver the advisory after the incidents exist. Each other
  # appended line names its `stream`; a line with an advisoryId is the advisory. One
  # subquery per stream runs the same query as that stream's file ingest. Parallelism 1
  # keeps the lines in file order.
  - name: live
    source:
      type: File
      path: data/live.ndjson
      fileIngestMode: NAMED_PIPE
      format:
        type: JsonL
    parallelism: 1
    query: |
      WITH CASE WHEN $that.advisoryId IS NOT NULL THEN 'advisory' ELSE $that.stream END AS stream
      // auth: the saml-auth query
      CALL {
        WITH stream
        WITH stream WHERE stream = 'auth'
        MATCH (ip), (auth), (app)
          WHERE id(ip)   = idFrom('ip', $that.src_ip)
            AND id(auth) = idFrom('auth', $that.event_id)
            AND id(app)  = idFrom('appliance', $that.appliance)
        CALL llm.decide(
          {username: $that.username},
          {payload: {type: "yes-no",
                     instructions: "Is this authentication username a machine-generated or injection-style string rather than a name a person would sign in with?"}}
        ) YIELD answers
        SET ip.ip = $that.src_ip, ip: IP,
            auth.username = $that.username,
            auth.endpoint = $that.endpoint,
            auth.ts = $that.ts,
            auth.epoch = $that.epoch,
            auth.suspicionScore = answers.payload.probability,
            auth.payloadShaped = answers.payload.probability >= 0.8,
            auth: AuthEvent,
            app.host = $that.appliance, app: Appliance
        CREATE (ip)-[:SENT]->(auth)-[:TO]->(app)
      }
      // sysevent: the system-events query
      CALL {
        WITH stream
        WITH stream WHERE stream = 'sysevent'
        MATCH (ev), (app)
          WHERE id(ev)  = idFrom('sysevent', $that.event_id)
            AND id(app) = idFrom('appliance', $that.appliance)
        SET ev.event_type = $that.event_type, ev.process = $that.process,
            ev.path = $that.path, ev.user = $that.user,
            ev.ts = $that.ts, ev.epoch = $that.epoch, ev: SysEvent,
            app.host = $that.appliance, app: Appliance
        CREATE (ev)-[:ON]->(app)
      }
      // egress: the firewall-egress query
      CALL {
        WITH stream
        WITH stream WHERE stream = 'egress'
        MATCH (app), (out), (dst)
          WHERE id(app) = idFrom('appliance', $that.appliance)
            AND id(out) = idFrom('outbound', $that.egress_id)
            AND id(dst) = idFrom('ip', $that.dest_ip)
        SET app.host = $that.appliance, app: Appliance,
            out.dest_port = $that.dest_port, out.proto = $that.proto,
            out.ts = $that.ts, out.epoch = $that.epoch, out: Outbound,
            dst.ip = $that.dest_ip, dst: IP
        CREATE (app)-[:CONNECTED_TO]->(out)-[:DEST]->(dst)
      }
      // helpdesk: the helpdesk query
      CALL {
        WITH stream
        WITH stream WHERE stream = 'helpdesk'
        MATCH (t) WHERE id(t) = idFrom('ticket', $that.ticketId)
        CALL llm.prompt(
          'You are reading one helpdesk ticket, provided in the data block. Decide which service it concerns: "vpn" for remote access or VPN connectivity, "sso" for single sign-on or login portals, or "other". Summarize the symptom in at most eight words. Decide whether the ticket plausibly reports an outage or failure of remote access or sign-on (outageReport). Base everything only on the ticket text.',
          {ticket: $that.text},
          {schema: {
             type: 'object', additionalProperties: false,
             required: ['service', 'symptom', 'outageReport'],
             properties: {
               service: {type: 'string', maxLength: 10},
               symptom: {type: 'string', maxLength: 80},
               outageReport: {type: 'boolean'}
             }
          }}
        ) YIELD response
        SET t.ticketId = $that.ticketId, t.user = $that.user,
            t.ts = $that.ts, t.epoch = $that.epoch, t.text = $that.text,
            t.service = response.service, t.symptom = response.symptom,
            t.outageReport = response.outageReport,
            t.extracted = response IS NOT NULL,
            t: Ticket
        WITH t, response
        WHERE response IS NOT NULL AND response.outageReport = true AND response.service IN ['vpn', 'sso']
        MATCH (svc) WHERE id(svc) = idFrom('service', response.service)
        SET svc.name = response.service, svc: Service
        CREATE (t)-[:REPORTS]->(svc)
        WITH t, svc
        MATCH (svc)<-[:AFFECTS]-(inc:Incident)
        WHERE abs(t.epoch - inc.epoch) <= 2700000
        CREATE (inc)-[:CORROBORATED_BY]->(t)
      }
      // advisory: extract the IOCs onto the IP and path nodes the graph already keys
      CALL {
        WITH stream
        WITH stream WHERE stream = 'advisory'
        MATCH (adv) WHERE id(adv) = idFrom('advisory', $that.advisoryId)
        CALL llm.prompt(
          'You are reading one vendor security advisory, provided in the data block. The advisory is fictional demonstration data about a real CVE, written for a product demo; no real systems or real addresses are involved. Extract exactly what it states: the CVE identifier; the affected process name; every IP address it names as attacker or callback infrastructure; every file path it describes as written or dropped during exploitation; the affected build range as one string; and a one-sentence summary. Use only information in the advisory text.',
          {advisory: $that.text},
          {schema: {
             type: 'object', additionalProperties: false,
             required: ['cve', 'process', 'iocIps', 'droppedPaths', 'affectedBuilds', 'summary'],
             properties: {
               cve: {type: 'string', maxLength: 30},
               process: {type: 'string', maxLength: 30},
               iocIps: {type: 'array', items: {type: 'string', maxLength: 45}},
               droppedPaths: {type: 'array', items: {type: 'string', maxLength: 120}},
               affectedBuilds: {type: 'string', maxLength: 80},
               summary: {type: 'string', maxLength: 300}
             }
          }}
        ) YIELD response
        SET adv.advisoryId = $that.advisoryId, adv.source = $that.source,
            adv.published = $that.published,
            adv.cve = response.cve, adv.process = response.process,
            adv.affectedBuilds = response.affectedBuilds, adv.summary = response.summary,
            adv.extracted = response IS NOT NULL,
            adv: Advisory
        WITH adv, response
        WHERE response IS NOT NULL
        CALL {
          WITH adv, response
          UNWIND coalesce(response.iocIps, []) AS i
          MATCH (ip) WHERE id(ip) = idFrom('ip', i)
          SET ip.ip = i, ip.ioc = true, ip.ioc_source = adv.advisoryId, ip: IOC
          CREATE (adv)-[:NAMES]->(ip)
        }
        CALL {
          WITH adv, response
          UNWIND coalesce(response.droppedPaths, []) AS p
          MATCH (path) WHERE id(path) = idFrom('path', p)
          SET path.path = p, path: IOCPath
          CREATE (adv)-[:NAMES_PATH]->(path)
        }
      }
      RETURN stream

standingQueries:
  # ---- Detection 1 + 2 + 3. Wakes once per nsaaad crash; the :ON hop inside the pattern
  # means it fires only when the full pattern exists, whatever order the logs arrived in.
  - name: crash-watch
    pattern:
      type: Cypher
      query: >
        MATCH (crash:SysEvent)-[:ON]->(app:Appliance)
        WHERE crash.event_type = 'process_crash' AND crash.process = 'nsaaad'
        RETURN DISTINCT id(crash) AS id
    outputs:
      # Attribute the crash to whoever authenticated to the appliance in the 60 s before it,
      # then re-count estate-wide and promote any IP that crosses both thresholds. Edge writes
      # and label sets are idempotent, so the auth-side mirror below can repeat them safely.
      - name: attribute-and-promote
        resultEnrichment:
          query: |
            MATCH (crash:SysEvent)-[:ON]->(app:Appliance) WHERE id(crash) = $that.data.id
            MATCH (ip:IP)-[:SENT]->(auth:AuthEvent)-[:TO]->(app)
            WHERE auth.epoch <= crash.epoch AND auth.epoch >= crash.epoch - 60000
            CREATE (ip)-[:PRECEDED_CRASH]->(crash)
            WITH DISTINCT ip
            MATCH (ip)-[:PRECEDED_CRASH]->(c:SysEvent)-[:ON]->(app2:Appliance)
            MATCH (ip)-[:SENT]->(a:AuthEvent)-[:TO]->(app2)
            WHERE a.epoch <= c.epoch AND a.epoch >= c.epoch - 60000
            WITH ip, count(DISTINCT c) AS crashesPreceded, count(DISTINCT a) AS requestsBefore
            WHERE crashesPreceded >= 2 AND requestsBefore >= 2
            SET ip.attacker_infra = true, ip: AttackerInfra
            RETURN id(ip) AS promoted
        destinations:
          - type: Drop
      # Detection 3: three nsaaad crashes on one appliance inside a trailing 15 minutes.
      # The equality makes it fire once per episode, on the crash that completes the burst.
      - name: repeated-crash-dos
        resultEnrichment:
          query: |
            MATCH (crash:SysEvent)-[:ON]->(app:Appliance) WHERE id(crash) = $that.data.id
            MATCH (other:SysEvent)-[:ON]->(app)
            WHERE other.event_type = 'process_crash' AND other.process = 'nsaaad'
              AND other.epoch <= crash.epoch AND other.epoch >= crash.epoch - 900000
            WITH app, crash, count(DISTINCT other) AS nsaaadCrashes, min(other.epoch) AS t0
            WHERE nsaaadCrashes = 3
            MATCH (alert) WHERE id(alert) = idFrom('alert', 'repeated-crash-dos', app.host)
            SET alert.kind = 'repeated-crash-dos', alert.appliance = app.host,
                alert.crashes = nsaaadCrashes, alert.windowMs = crash.epoch - t0,
                alert: Alert
            CREATE (alert)-[:ON]->(app)
            RETURN id(alert) AS fired
        destinations:
          - type: Drop

  # ---- The mirror of detection 1: wakes once per auth event and looks for a crash in the
  # 60 s after it. Whichever log arrives last completes the attribution, so neither log lag
  # nor ingest order loses an edge. Runs the same promotion recount.
  - name: auth-mirror
    pattern:
      type: Cypher
      query: >
        MATCH (ip:IP)-[:SENT]->(auth:AuthEvent)-[:TO]->(app:Appliance)
        RETURN DISTINCT id(auth) AS id
    outputs:
      - name: attribute-forward
        resultEnrichment:
          query: |
            MATCH (ip:IP)-[:SENT]->(auth:AuthEvent)-[:TO]->(app:Appliance) WHERE id(auth) = $that.data.id
            MATCH (crash:SysEvent)-[:ON]->(app)
            WHERE crash.event_type = 'process_crash' AND crash.process = 'nsaaad'
              AND crash.epoch >= auth.epoch AND crash.epoch <= auth.epoch + 60000
            CREATE (ip)-[:PRECEDED_CRASH]->(crash)
            WITH DISTINCT ip
            MATCH (ip)-[:PRECEDED_CRASH]->(c:SysEvent)-[:ON]->(app2:Appliance)
            MATCH (ip)-[:SENT]->(a:AuthEvent)-[:TO]->(app2)
            WHERE a.epoch <= c.epoch AND a.epoch >= c.epoch - 60000
            WITH ip, count(DISTINCT c) AS crashesPreceded, count(DISTINCT a) AS requestsBefore
            WHERE crashesPreceded >= 2 AND requestsBefore >= 2
            SET ip.attacker_infra = true, ip: AttackerInfra
            RETURN id(ip) AS promoted
        destinations:
          - type: Drop

  # ---- Detection 2's pivot: fires once per promoted IP and assesses every appliance it
  # touched, crashed or not. The patched decoy is the reason this exists.
  - name: attacker-pivot
    pattern:
      type: Cypher
      query: >
        MATCH (ip:AttackerInfra) RETURN DISTINCT id(ip) AS id
    outputs:
      - name: assess-exposure
        resultEnrichment:
          query: |
            MATCH (ip:AttackerInfra) WHERE id(ip) = $that.data.id
            MATCH (ip)-[:SENT|REQUESTED]->(ev)-[:TO]->(app:Appliance)
            WITH DISTINCT ip, app
            OPTIONAL MATCH (c:SysEvent)-[:ON]->(app)
            WHERE c.event_type = 'process_crash' AND c.process = 'nsaaad'
            WITH ip, app, count(DISTINCT c) AS nsaaadCrashes
            SET app.assessment = CASE WHEN nsaaadCrashes > 0 THEN 'compromised'
                                      ELSE 'probed, no crash: verify build' END
            CREATE (ip)-[:TARGETED]->(app)
            RETURN id(app) AS assessed
        destinations:
          - type: Drop

  # ---- Detection 4: the post-exploitation chain. The pattern is built from derived
  # elements (the AttackerInfra label and PRECEDED_CRASH edge), so it completes only when
  # attribution and promotion have, regardless of what order the raw logs arrived in. The
  # output checks the two conditions the original post requires: the write happened after
  # the first attributed crash, and the appliance then reached a destination that either
  # carries the IOC label or has never been contacted by a healthy appliance.
  - name: kill-chain
    pattern:
      type: Cypher
      query: >
        MATCH (ip:AttackerInfra)-[:PRECEDED_CRASH]->(c:SysEvent)-[:ON]->(app:Appliance)<-[:ON]-(fw:SysEvent)
        WHERE fw.event_type = 'file_write'
        RETURN DISTINCT id(fw) AS id
    outputs:
      - name: assemble-incident
        resultEnrichment:
          query: |
            MATCH (fw:SysEvent)-[:ON]->(app:Appliance) WHERE id(fw) = $that.data.id
            MATCH (ip:AttackerInfra)-[:PRECEDED_CRASH]->(c:SysEvent)-[:ON]->(app)
            WITH fw, app, min(c.epoch) AS firstCrash, collect(DISTINCT id(ip)) AS attackerIds
            WHERE fw.epoch > firstCrash
            MATCH (app)-[:CONNECTED_TO]->(o:Outbound)-[:DEST]->(dst:IP)
            WHERE o.epoch > firstCrash
            WITH fw, app, firstCrash, attackerIds, dst,
                 min(o.epoch) AS myContact, 'IOC' IN labels(dst) AS knownIoc
            MATCH (app2:Appliance)-[:CONNECTED_TO]->(o2:Outbound)-[:DEST]->(dst)
            WHERE o2.epoch <= myContact
            OPTIONAL MATCH (x:AttackerInfra)-[:PRECEDED_CRASH]->(c2:SysEvent)-[:ON]->(app2)
            WHERE c2.epoch < o2.epoch
            WITH fw, app, firstCrash, attackerIds, dst, knownIoc, o2, count(c2) AS crashesBeforeContact
            WITH fw, app, firstCrash, attackerIds, dst, knownIoc,
                 count(o2) AS estateContacts,
                 sum(CASE WHEN crashesBeforeContact = 0 THEN 1 ELSE 0 END) AS healthyContacts
            WHERE knownIoc OR healthyContacts = 0
            MATCH (alert) WHERE id(alert) = idFrom('alert', 'post-exploitation', app.host, fw.path)
            SET alert.kind = 'post-exploitation-chain', alert.appliance = app.host,
                alert.droppedFile = fw.path, alert.writtenBy = fw.user,
                alert.egressTo = dst.ip, alert.estateContacts = estateContacts,
                alert.reason = CASE WHEN knownIoc THEN 'known IOC'
                                    ELSE 'no healthy appliance has ever contacted this host' END,
                alert: Alert
            CREATE (alert)-[:ON]->(app)
            WITH fw, app, attackerIds, dst
            MATCH (inc) WHERE id(inc) = idFrom('incident', app.host)
            SET inc.appliance = app.host,
                inc.epoch = coalesce(inc.epoch, fw.epoch),
                inc.egressTo = dst.ip
            CREATE (inc)-[:ON]->(app)
            CREATE (inc)-[:EGRESS_TO]->(dst)
            WITH DISTINCT inc, attackerIds
            UNWIND attackerIds AS aid
            MATCH (attacker) WHERE id(attacker) = aid
            CREATE (inc)-[:ATTRIBUTED_TO]->(attacker)
            WITH DISTINCT inc
            // Tickets only know their service, so give them an edge path to the incident:
            // the helpdesk query walks service -> AFFECTS -> incident for late arrivals.
            // These edges go in before the label, so the path is complete at the moment
            // the label makes the incident matchable.
            UNWIND ['vpn', 'sso'] AS svcName
            MATCH (svc) WHERE id(svc) = idFrom('service', svcName)
            SET svc.name = svcName, svc: Service
            CREATE (inc)-[:AFFECTS]->(svc)
            WITH DISTINCT inc
            SET inc: Incident
            RETURN id(inc) AS incident
        destinations:
          - type: Drop

  # ---- The sequel's output stage: fires once per Incident (the label is set last, after
  # the incident's edges exist). Collects compact evidence from the subgraph, asks the
  # decision model whether to page, and has the chat model write the brief. Both models
  # only see what the graph assembled; the prompt forbids invention, the schema bounds the
  # shape, and a schema-null brief leaves inc.briefed = false instead of a wrong summary.
  - name: incident-brief
    pattern:
      type: Cypher
      query: >
        MATCH (inc:Incident) RETURN DISTINCT id(inc) AS id
    outputs:
      - name: gate-and-brief
        resultEnrichment:
          query: |
            MATCH (inc:Incident)-[:ON]->(app:Appliance) WHERE id(inc) = $that.data.id
            MATCH (inc)-[:ATTRIBUTED_TO]->(attacker:IP)
            WITH DISTINCT inc, app, collect(DISTINCT attacker.ip) AS attackers
            MATCH (:AttackerInfra)-[:PRECEDED_CRASH]->(c:SysEvent)-[:ON]->(app)
            WITH inc, app, attackers, count(DISTINCT c) AS attributedCrashes,
                 min(c.epoch) AS firstCrash, collect(DISTINCT c.ts) AS crashTimes
            MATCH (fw:SysEvent)-[:ON]->(app)
            WHERE fw.event_type = 'file_write' AND fw.epoch > firstCrash
            WITH inc, app, attackers, attributedCrashes, crashTimes, firstCrash,
                 collect(DISTINCT (fw.path + ' written by ' + fw.user + ' at ' + fw.ts)) AS droppedFiles
            MATCH (app)-[:CONNECTED_TO]->(o:Outbound)-[:DEST]->(dst:IP)
            WHERE o.epoch > firstCrash AND dst.ip = inc.egressTo
            WITH inc, app, attackers, attributedCrashes, crashTimes, firstCrash, droppedFiles,
                 collect(DISTINCT dst.ip)[0] AS egressTo,
                 sum(CASE WHEN 'IOC' IN labels(dst) THEN 1 ELSE 0 END) AS iocContacts
            UNWIND ['vpn', 'sso'] AS svcName
            MATCH (svc) WHERE id(svc) = idFrom('service', svcName)
            OPTIONAL MATCH (svc)<-[:REPORTS]-(t)
            WHERE abs(t.epoch - inc.epoch) <= 2700000
            WITH inc, app, attackers, attributedCrashes, crashTimes, droppedFiles, egressTo,
                 iocContacts, collect(DISTINCT t) AS windowTickets
            // The edges and the count come from this one matched set, before the LLM calls:
            // a ticket arriving during the calls can no longer split them apart.
            FOREACH (tk IN windowTickets | CREATE (inc)-[:CORROBORATED_BY]->(tk))
            WITH inc, app, attackers, attributedCrashes, crashTimes, droppedFiles, egressTo,
                 iocContacts, size(windowTickets) AS userReports
            WITH inc, app,
                 {appliance: app.host, attackers: attackers,
                  attributedCrashes: attributedCrashes, crashTimes: crashTimes,
                  droppedFiles: droppedFiles, egressTo: egressTo,
                  egressIsKnownIoc: iocContacts > 0,
                  userOutageReportsInWindow: userReports} AS evidence
            CALL llm.decide(
              evidence,
              {severity: {type: "choice", options: ["page", "ticket"],
                          instructions: "Given this evidence about one authentication gateway appliance, should the on-call responder be paged immediately (page), or is a tracked ticket during business hours enough (ticket)?"}}
            ) YIELD answers
            CALL llm.prompt(
              'You are writing an incident brief for a security responder. The data block holds evidence a streaming graph assembled about one appliance: the attacker addresses, how many service crashes were attributed to them and when, the files dropped afterward, the outbound callback destination, and how many users reported outages in the window. State only facts present in the evidence; never invent counts, times, addresses, or causes. The timeline entries must be chronological and one sentence each. Give at most eight timeline entries and at most five recommended actions.',
              evidence,
              {schema: {
                 type: 'object', additionalProperties: false,
                 required: ['title', 'summary', 'timeline', 'recommendedActions'],
                 properties: {
                   title: {type: 'string', maxLength: 90},
                   summary: {type: 'string', maxLength: 600},
                   timeline: {type: 'array', maxItems: 8, items: {type: 'string', maxLength: 160}},
                   recommendedActions: {type: 'array', maxItems: 5, items: {type: 'string', maxLength: 120}}
                 }
              }}
            ) YIELD response
            SET inc.severity = answers.severity.choice,
                inc.severityConfidence = answers.severity.confidence,
                inc.title = response.title,
                inc.summary = response.summary,
                inc.timeline = response.timeline,
                inc.recommendedActions = response.recommendedActions,
                inc.briefed = response IS NOT NULL
            RETURN id(inc) AS briefed
        destinations:
          - type: Drop

  # ---- The page: wakes once per incident whose severity is `page`. The brief stage sets the
  # severity and the brief in one SET, so the brief is present when this fires. StandardOut
  # here; Slack, HttpEndpoint, SNS, Kafka, or Kinesis deliver it to a person or a pipeline.
  - name: page-on-call
    pattern:
      type: Cypher
      query: >
        MATCH (inc:Incident) WHERE inc.severity = 'page' RETURN DISTINCT id(inc) AS id
    outputs:
      - name: send-page
        resultEnrichment:
          query: |
            MATCH (inc:Incident) WHERE id(inc) = $that.data.id
            RETURN inc.appliance AS appliance, inc.title AS title, inc.summary AS summary,
                   inc.recommendedActions AS actions
        destinations:
          - type: StandardOut

nodeAppearances:
  # Promoted and IOC-flagged IPs carry several labels, and appearance predicates match the
  # joined label string exactly, so these two match on the marker property instead.
  - predicate:
      propertyKeys: []
      knownValues: { attacker_infra: true }
    icon: ion-flag
    color: '#ff0000'
    label: { type: Property, key: ip, prefix: '' }
  - predicate:
      propertyKeys: []
      knownValues: { ioc: true }
    icon: ion-alert-circled
    color: '#aa00aa'
    label: { type: Property, key: ip, prefix: 'IOC ' }
  - predicate:
      dbLabel: IP
      propertyKeys: []
      knownValues: {}
    icon: ion-ios-world
    label: { type: Property, key: ip, prefix: '' }
  - predicate:
      dbLabel: Appliance
      propertyKeys: []
      knownValues: { assessment: 'compromised' }
    icon: ion-cube
    color: '#ff0000'
    label: { type: Property, key: host, prefix: '' }
  - predicate:
      dbLabel: Appliance
      propertyKeys: []
      knownValues: { assessment: 'probed, no crash: verify build' }
    icon: ion-cube
    color: '#ffa500'
    label: { type: Property, key: host, prefix: '' }
  - predicate:
      dbLabel: Appliance
      propertyKeys: []
      knownValues: {}
    icon: ion-cube
    label: { type: Property, key: host, prefix: '' }
  - predicate:
      dbLabel: Incident
      propertyKeys: []
      knownValues: {}
    icon: ion-fireball
    color: '#ff0000'
    label: { type: Property, key: title, prefix: '' }
  - predicate:
      dbLabel: Alert
      propertyKeys: []
      knownValues: {}
    icon: ion-alert
    color: '#ffa500'
    label: { type: Property, key: kind, prefix: '' }
  - predicate:
      dbLabel: SysEvent
      propertyKeys: []
      knownValues: { event_type: 'process_crash' }
    icon: ion-nuclear
    color: '#cc0000'
    label: { type: Property, key: process, prefix: 'crash ' }
  - predicate:
      dbLabel: SysEvent
      propertyKeys: []
      knownValues: {}
    icon: ion-gear-b
    label: { type: Property, key: event_type, prefix: '' }
  - predicate:
      dbLabel: AuthEvent
      propertyKeys: []
      knownValues: {}
    icon: ion-log-in
    label: { type: Property, key: username, prefix: '' }
  - predicate:
      dbLabel: Ticket
      propertyKeys: []
      knownValues: {}
    icon: ion-chatbubble
    label: { type: Property, key: ticketId, prefix: '' }
  - predicate:
      dbLabel: Service
      propertyKeys: []
      knownValues: {}
    icon: ion-wrench
    label: { type: Property, key: name, prefix: '' }
  - predicate:
      dbLabel: Advisory
      propertyKeys: []
      knownValues: {}
    icon: ion-document-text
    color: '#aa00aa'
    label: { type: Property, key: advisoryId, prefix: '' }
  - predicate:
      dbLabel: IOCPath
      propertyKeys: []
      knownValues: {}
    icon: ion-document
    color: '#aa00aa'
    label: { type: Property, key: path, prefix: '' }
  - predicate:
      dbLabel: HttpRequest
      propertyKeys: []
      knownValues: {}
    icon: ion-link
    label: { type: Property, key: uri, prefix: '' }

quickQueries:
  - predicate: { propertyKeys: [], knownValues: {} }
    quickQuery:
      name: Adjacent Nodes
      querySuffix: MATCH (n)--(m) RETURN DISTINCT m
      sort: NODE
  - predicate: { propertyKeys: [], knownValues: {} }
    quickQuery:
      name: Refresh
      querySuffix: RETURN n
      sort: NODE
  - predicate: { propertyKeys: [], knownValues: {} }
    quickQuery:
      name: Local Properties
      querySuffix: RETURN id(n), properties(n)
      sort: TEXT
  - predicate:
      dbLabel: Appliance
      propertyKeys: []
      knownValues: {}
    quickQuery:
      name: System Events
      querySuffix: MATCH (n)<-[:ON]-(ev:SysEvent) RETURN ev
      sort: NODE
  - predicate:
      dbLabel: Incident
      propertyKeys: []
      knownValues: {}
    quickQuery:
      name: Full Evidence
      querySuffix: MATCH (n)-[]-(m) RETURN DISTINCT m
      sort: NODE

sampleQueries:
  - name: Promoted attacker infrastructure
    query: MATCH (ip:AttackerInfra) RETURN ip
  - name: Incidents and their appliances
    query: MATCH (inc:Incident)-[:ON]->(app) RETURN inc, app
  - name: Every assessed appliance, compromised or probed
    query: MATCH (ip:AttackerInfra)-[:TARGETED]->(app:Appliance) RETURN ip, app
  - name: The callback host and everyone who reached it
    query: MATCH (app:Appliance)-[:CONNECTED_TO]->(o:Outbound)-[:DEST]->(dst:IP) WHERE dst.ip = '203.0.113.66' RETURN app, o, dst
  - name: Attack subgraph around one appliance
    query: MATCH (ip:AttackerInfra)-[:PRECEDED_CRASH]->(c:SysEvent)-[:ON]->(app:Appliance) WHERE app.host = 'ns-gw-01' RETURN ip, c, app

statusQuery:
  cypherQuery: >
    MATCH (alert:Alert)
    WITH count(DISTINCT alert) AS alerts
    OPTIONAL MATCH (ip:AttackerInfra)
    WITH alerts, count(DISTINCT ip) AS attackerIps
    OPTIONAL MATCH (inc:Incident)
    RETURN alerts, attackerIps, count(DISTINCT inc) AS incidents

