id: ev-charger-session-audit
namespace: company.team
description: |
Charging sessions go wrong quietly and nobody finds out until a charger
fails inspection or a fleet manager disputes an energy bill. A keyed
webhook receives a notice every time a driver unplugs and a disabled
hourly schedule stands ready as the sweep net; a shell step writes the
sessions.json register and a python step audits it against the failed,
zero duration, connector mismatch and overstay rules. When any session is
anomalous the flow posts one CMMS work order per anomaly, opens one GitHub
issue and alerts the ops channel, while a clean register is logged as
healthy. Each run publishes verdict, anomaly_count, sessions and anomalies
as typed outputs.
triggers:
- id: on_session_end
type: io.kestra.plugin.core.trigger.Webhook
description: The charge point management system POSTs a session end notice so
the register is re audited the moment a driver unplugs.
key: "{{ secret('SESSION_END_WEBHOOK_KEY') }}"
- id: hourly_reconciliation
type: io.kestra.plugin.core.trigger.Schedule
description: Disabled hourly net that would sweep the whole session register
every hour until someone switches it on.
cron: "0 * * * *"
disabled: true
inputs:
- id: overstay_hours
type: INT
defaults: 6
description: Maximum hours a session may stay connected before it counts as an
overstay, applied to every row of the register.
- id: github_repository
type: STRING
defaults: acme-corp/fleet-energy-ops
description: Repository that receives the audit issue when anomalous sessions are found.
tasks:
# --- 1. the session register and its audit ---
- id: workspace
type: io.kestra.plugin.core.flow.WorkingDirectory
description: One shared directory so the sessions.json written by the shell step
is the exact file the auditor reads.
tasks:
- id: write_sessions
type: io.kestra.plugin.scripts.shell.Commands
description: Writes sessions.json from a heredoc of eight charging sessions
covering a clean 30 kWh charge, a failed mid session, a zero duration
plug, a connector mismatch and an eight hour overstay.
commands:
- |
cat > sessions.json <<'SESSIONS_EOF'
[
{"session_id": "SES-40011", "site_id": "DEPOT-NORTH", "connector_id": "CP1-A", "connector_type": "CCS2", "vehicle_connector": "CCS2", "started_at": "2026-03-02T08:00:00Z", "stopped_at": "2026-03-02T09:45:00Z", "energy_kwh": 30.0},
{"session_id": "SES-40012", "site_id": "DEPOT-NORTH", "connector_id": "CP1-B", "connector_type": "Type2", "vehicle_connector": "Type2", "started_at": "2026-03-02T12:00:00Z", "stopped_at": "2026-03-02T13:30:00Z", "energy_kwh": 22.5},
{"session_id": "SES-40013", "site_id": "DEPOT-SOUTH", "connector_id": "CP4-A", "connector_type": "CCS2", "vehicle_connector": "CCS2", "started_at": "2026-03-02T14:10:00Z", "stopped_at": "2026-03-02T15:35:00Z", "energy_kwh": 18.4},
{"session_id": "SES-40014", "site_id": "DEPOT-SOUTH", "connector_id": "CP4-B", "connector_type": "CCS2", "vehicle_connector": "CCS2", "started_at": "2026-03-02T16:05:00Z", "stopped_at": null, "energy_kwh": 4.6},
{"session_id": "SES-40015", "site_id": "DEPOT-NORTH", "connector_id": "CP2-A", "connector_type": "Type2", "vehicle_connector": "Type2", "started_at": "2026-03-02T17:30:00Z", "stopped_at": "2026-03-02T17:30:00Z", "energy_kwh": 0.0},
{"session_id": "SES-40016", "site_id": "DEPOT-NORTH", "connector_id": "CP2-B", "connector_type": "CCS2", "vehicle_connector": "Type2", "started_at": "2026-03-02T18:20:00Z", "stopped_at": "2026-03-02T19:50:00Z", "energy_kwh": 26.4},
{"session_id": "SES-40017", "site_id": "DEPOT-SOUTH", "connector_id": "CP5-A", "connector_type": "CCS2", "vehicle_connector": "CCS2", "started_at": "2026-03-02T21:00:00Z", "stopped_at": "2026-03-03T05:00:00Z", "energy_kwh": 41.2},
{"session_id": "SES-40018", "site_id": "DEPOT-SOUTH", "connector_id": "CP5-B", "connector_type": "Type2", "vehicle_connector": "Type2", "started_at": "2026-03-03T06:30:00Z", "stopped_at": "2026-03-03T07:55:00Z", "energy_kwh": 15.7}
]
SESSIONS_EOF
wc -l sessions.json
- id: audit_sessions
type: io.kestra.plugin.scripts.python.Script
description: Applies the failed, zero duration, connector mismatch and overstay
rules to every session in the register and prints the repo standard
outputs line carrying verdict, anomaly_count, sessions and anomalies.
taskRunner:
type: io.kestra.plugin.core.runner.Process
env:
SESSIONS_FILE: sessions.json
OVERSTAY_HOURS: "{{ inputs.overstay_hours }}"
script: |
import json
import os
from datetime import datetime, timezone
DEFAULT_OVERSTAY_HOURS = 6.0
def as_float(value):
try:
return float(str(value).strip())
except (TypeError, ValueError):
return None
def parse_time(value):
text = str(value or "").strip()
if not text or text.lower() == "none":
return None
try:
stamp = datetime.fromisoformat(text.replace("Z", "+00:00"))
except ValueError:
return None
if stamp.tzinfo is None:
stamp = stamp.replace(tzinfo=timezone.utc)
return stamp
def load_sessions(path):
if not os.path.exists(path):
return []
try:
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
except (ValueError, OSError):
return []
return data if isinstance(data, list) else []
def anomaly(session_id, connector_id, rule, detail):
return {
"session_id": session_id,
"connector_id": connector_id,
"rule": rule,
"detail": detail,
}
sessions_path = os.environ.get("SESSIONS_FILE", "").strip() or "sessions.json"
overstay_hours = as_float(os.environ.get("OVERSTAY_HOURS", ""))
if overstay_hours is None or overstay_hours <= 0:
overstay_hours = DEFAULT_OVERSTAY_HOURS
rows = load_sessions(sessions_path)
anomalies = []
tracked = 0
for row in rows:
if not isinstance(row, dict):
continue
session_id = str(row.get("session_id") or "").strip()
if not session_id:
continue
tracked += 1
connector_id = str(row.get("connector_id") or "").strip()
energy = as_float(row.get("energy_kwh"))
started = parse_time(row.get("started_at"))
stopped = parse_time(row.get("stopped_at"))
plug = str(row.get("connector_type") or "").strip()
vehicle = str(row.get("vehicle_connector") or "").strip()
if stopped is None:
anomalies.append(anomaly(
session_id, connector_id, "failed_session",
"stopped_at is null so the charge point never closed the session"))
elif energy is None or energy < 1:
shown = "unreadable" if energy is None else ("%g" % energy)
anomalies.append(anomaly(
session_id, connector_id, "failed_session",
"energy_kwh %s sits below the 1 kWh floor" % shown))
if started is not None and stopped is not None and started == stopped:
anomalies.append(anomaly(
session_id, connector_id, "zero_duration",
"started_at and stopped_at are identical so the session never ran"))
if plug and vehicle and plug.lower() != vehicle.lower():
anomalies.append(anomaly(
session_id, connector_id, "connector_mismatch",
"charge point reports %s while the vehicle declares %s" % (plug, vehicle)))
if started is not None and stopped is not None and stopped > started:
hours = (stopped - started).total_seconds() / 3600.0
if hours > overstay_hours:
anomalies.append(anomaly(
session_id, connector_id, "overstay",
"session ran %.2f hours against the %g hour stay limit"
% (hours, overstay_hours)))
if tracked == 0:
verdict = "NO_DATA"
elif anomalies:
verdict = "ANOMALIES_FOUND"
else:
verdict = "CLEAN"
print("ev session audit verdict=%s anomaly_count=%d sessions=%d overstay_hours=%g"
% (verdict, len(anomalies), tracked, overstay_hours))
print("::" + json.dumps({"outputs": {"verdict": verdict,
"anomaly_count": len(anomalies),
"sessions": tracked,
"anomalies": anomalies}},
ensure_ascii=True) + "::")
# --- 2. the anomaly gate ---
- id: anomaly_gate
type: io.kestra.plugin.core.flow.If
description: Escalates only when at least one session trips a rule, so a
register of healthy charges stays quiet.
condition: "{{ outputs.audit_sessions.vars.anomaly_count > 0 }}"
then:
# --- 3. one maintenance work order per anomaly ---
- id: raise_work_orders
type: io.kestra.plugin.core.flow.Loop
description: Walks the anomaly list one record at a time so maintenance gets one
CMMS work order per rule breach instead of an unreadable digest.
values: "{{ outputs.audit_sessions.vars.anomalies }}"
concurrencyLimit: 1
tasks:
- id: post_work_order
type: io.kestra.plugin.core.http.Request
description: Posts a single work order to the CMMS naming the session, the
connector and the rule that tripped, with the execution attached
for traceability.
method: POST
uri: "{{ secret('CMMS_WORKORDER_URL') }}"
headers:
Content-Type: application/json
Authorization: "Bearer {{ secret('CMMS_API_TOKEN') }}"
body: |
{"asset_type": "EV_CHARGER", "session_id": "{{ item.value.session_id }}", "connector_id": "{{ item.value.connector_id }}", "rule": "{{ item.value.rule }}", "summary": "{{ item.value.detail }}", "priority": "high", "source": "{{ flow.id }}", "execution_id": "{{ execution.id }}"}
retry:
type: exponential
interval: PT2S
maxInterval: PT10S
maxAttempts: 3
# --- 4. the audit record ---
- id: open_audit_issue
type: io.kestra.plugin.github.issues.Create
description: Opens one labeled tracking issue listing every anomaly with its
session, connector, rule and detail, so the audit leaves a backlog
record.
oauthToken: "{{ secret('GITHUB_TOKEN') }}"
repository: "{{ inputs.github_repository }}"
title: "EV session audit - {{ outputs.audit_sessions.vars.anomaly_count }}
anomaly record(s) across {{ outputs.audit_sessions.vars.sessions }}
session(s)"
body: |
## Charging session anomalies
**{{ outputs.audit_sessions.vars.anomaly_count }} anomaly record(s)** across **{{ outputs.audit_sessions.vars.sessions }} session(s)** in the latest register audit, against the {{ inputs.overstay_hours }} hour overstay limit.
| Session | Connector | Rule | Detail |
| --- | --- | --- | --- |
{% for item in outputs.audit_sessions.vars.anomalies %}| {{ item.session_id }} | {{ item.connector_id }} | {{ item.rule }} | {{ item.detail }} |
{% endfor %}
Execution: {{ execution.id }}
Work orders are being raised in the CMMS, one per row above. Close this issue once the register audits clean again.
labels:
- ev-charging
- anomaly
# --- 5. the channel summary ---
- id: alert_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Summarizes the anomaly count, the sessions audited and the most
frequent rule so the ops channel sees the exposure at once.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "EV session audit - {{ outputs.audit_sessions.vars.anomaly_count }} anomaly record(s) across {{ outputs.audit_sessions.vars.sessions }} session(s), overstay limit {{ inputs.overstay_hours }}h. First is {{ outputs.audit_sessions.vars.anomalies[0].session_id }} with {{ outputs.audit_sessions.vars.anomalies[0].rule }}. Work orders raised in the CMMS, rollup issue opened in {{ inputs.github_repository }}. Execution {{ execution.id }}."}
else:
# --- 6. the clean register ---
- id: log_clean
type: io.kestra.plugin.core.log.Log
description: Records the quiet outcome where every session closed with a stop
time, real energy, matching connectors and a stay inside the limit, so
a clean sweep still leaves evidence.
message: "EV session register clean - verdict {{
outputs.audit_sessions.vars.verdict }}, {{
outputs.audit_sessions.vars.anomaly_count }} anomaly record(s) across
{{ outputs.audit_sessions.vars.sessions }} session(s) against the {{
inputs.overstay_hours }} hour overstay limit."
errors:
- id: notify_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Escalate any failure to the ops channel with the execution url.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "FAILED: {{ flow.id }} {{ execution.id }}"}
outputs:
- id: verdict
type: STRING
value: "{{ outputs.audit_sessions.vars.verdict }}"
- id: anomaly_count
type: INT
value: "{{ outputs.audit_sessions.vars.anomaly_count }}"
- id: sessions
type: INT
value: "{{ outputs.audit_sessions.vars.sessions }}"
- id: anomalies
type: ARRAY
value: "{{ outputs.audit_sessions.vars.anomalies | toJson }}"