Skip to main content
Glama
README.md
# PLC Tracer

**Ask a PLC program why an output is off.**

A conveyor stops and the HMI says "C1 stopped". Finding out why usually means a laptop, the PLC
program and someone who can read it, following the logic by hand: C1 needs C2 available, C2 needs C3,
C3 has a latched jam fault, the jam came from a photo-eye blocked for 8 s. That takes 10 to 30 minutes.

PLC Tracer does it in one step. It reads IEC 61131-3 Structured Text, puts the program, the plant
wiring, the alarms, the maintenance notes and the recent events into one [Relate](https://relatedb.ai)
graph, and walks that graph with the live values down to the physical cause and what to do about it.

```
$ plctrace why M1Run --scenario jam_pe3
Why is M1Run FALSE?

M1Run = C1.Run = FALSE  :=  C1.Available AND NOT C1.Waiting
└─ C1.Available = FALSE  :=  C1.LineRun AND C1.Permit AND C1.NextAvailable AND NOT C1.Fault
   └─ C1.NextAvailable = C2.Available = FALSE  :=  C2.LineRun AND C2.Permit AND C2.NextAvailable AND NOT C2.Fault
      └─ C2.NextAvailable = C3.Available = FALSE  :=  C3.LineRun AND C3.Permit AND C3.NextAvailable AND NOT C3.Fault
         └─ C3.Fault = TRUE  :=  TRUE   IF C3.JamTimer.Q   [held since 39.3 s (6.7 s ago)]
            ├─ C3.JamTimer.Q = TRUE   [TON: IN has been TRUE for 8.0 s]   (at 39.3 s)
            │  └─ C3.JamTimer.IN = TRUE   [became TRUE at 31.3 s]   (at 39.3 s)
            │     ├─ C3.EyeBlocked = PE3 = TRUE   [PE3 photo-eye: C3 discharge, inside the transfer guard; now TRUE (still)]
            │     └─ C3.Running = TRUE   (holds, at 31.3 s)
            └─ C3.Ack = StartEdge.Q = FALSE   [rising edge of CLK: no edge this scan]   TO CLEAR
               └─ StartEdge.CLK = StartPb = FALSE   [S1 START button: Operator station OS1 at C1]   TO CLEAR

FAULT     M1Run is FALSE (M1 contactor, C1 belt)
          A latched fault is in the way.
Cause     PE3 photo-eye blocked, since 31.3 s, still now   (PE3)
          C3 discharge, inside the transfer guard
Alarm     A302 C3 jam at PE3
To clear  1. PE3 photo-eye must be clear
          2. press S1 START button
Note      PE3 at the C3 transfer   (below)
```

A plain dependency query over the same graph says M1Run depends on **15** physical inputs. It cannot
say which one matters. The tracer evaluates the logic with the values at each moment and follows only
the terms that decide the result, so it ends at one: PE3, with its location, the alarm, the
maintenance note and the two things to do.

It runs three ways, all on the same graph:

| | |
|---|---|
| **CLI** | `plctrace why M1Run` in a terminal, coloured |
| **MCP server** | an AI assistant asks the line questions through MCP: `why`, `line_status`, `what_if`, `find`, read-only `cypher` |
| **Browser** | [the web view](https://bartoszmilewski-engineeringsupport.github.io/plc-tracer/) loads each scenario's graph into Relate WASM and runs the queries in the page |

![The web view: the line, the trace for M1Run, and the plain dependency query beside it](docs/web-view.jpg)

No PLC, no LLM and no API key are needed: the demo is a simulated five-conveyor line with twelve
scenarios: eight faults, and four that stress the engine and the tracer (a fluttering eye, two jams
in one scan, an INT overflow, a latch older than the event history).

## Quick start

[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/bartoszmilewski-engineeringsupport/plc-tracer)
sets everything up and runs the first trace. To run it on your own machine you need Python 3.10 or newer.

```bash
git clone https://github.com/bartoszmilewski-engineeringsupport/plc-tracer
cd plc-tracer
python -m venv .venv
source .venv/bin/activate            # Windows: .venv\Scripts\activate
pip install -e ".[mcp,dev]"

plctrace scenarios                   # the twelve scenarios
plctrace why M1Run --scenario jam_pe3
plctrace why C3 --scenario air_low   # a zone or a device name works too: C3, M3, PE3, ES2
plctrace why M4 --scenario pallet_change --json
pytest -q                            # 506 tests, 23 known defects as xfails
```

`--scenario` runs the simulator (start the line, 30 s of normal running, inject the fault), loads the
graph into an in-memory Relate database and answers from it. That takes about half a second.

| Scenario | Ask | What the tracer finds |
|---|---|---|
| `jam_pe3` | `M1Run` | FAULT: PE3 blocked, latched jam on C3; clear PE3, press START |
| `broken_m4` | `M2Run` | FAULT: M4 has no feedback (contactor KM4); fix M4, press START |
| `estop_es2` | `M3Run` | SAFETY: ES2 pressed at the palletiser gate, through safety relay K1 |
| `door_open` | `LampRun` | SAFETY: guard door GD1 open |
| `air_low` | `M1Run` | INTERLOCK: PS1 air pressure low at the C3 pusher |
| `pallet_change` | `M4Run` | WAIT: the palletiser is changing a pallet. A normal wait, not a fault |
| `dirty_eye_pe2` | `M1Run` | FAULT: PE2 reads blocked with no tote there (dirty lens); clean it, press START |
| `double_fault` | `M1Run` | FAULT: M4 has no feedback; the tote stuck at C3 is a consequence, not the cause |

To keep a graph on disk and query it later without the simulator:

```bash
plctrace load --scenario broken_m4 --db store/broken_m4
plctrace why M2 --db store/broken_m4
plctrace cypher "MATCH (d:Device)-[:WIRED_TO]->(t:Tag {io: 'DI'}) RETURN d.name, t.value" --db store/broken_m4
```

## Ask it from an AI assistant (MCP)

`plctrace mcp` is an MCP server on stdio, so any MCP client can start it. This repo has a `.mcp.json`,
which MCP clients that read project config pick up when started in the repo with the venv active.
To add it by hand, put this in the client's MCP config (use the full path to `plctrace` in your venv):

```json
{
  "mcpServers": {
    "plc-tracer": {
      "command": "/path/to/plc-tracer/.venv/bin/plctrace",
      "args": ["mcp", "--scenario", "jam_pe3"]
    }
  }
}
```

Then ask: *"Line 2 has stopped. Why, and what do I do?"*, *"If I clear the tote at PE3 and press
START, does everything run again?"*, *"Is the C4 stop a fault?"*

| Tool | What it does |
|---|---|
| `line_status` | zones in order, motors (run, feedback), eyes and other devices, active alarms |
| `why` | the trace for a tag, device or zone; `answer` is the text above, plus causes, remedies, chain as data |
| `what_if` | plays actions on a **copy** of the simulated line (clear a jam, release an e-stop, press START) and reports what runs afterwards |
| `find` | tags, devices, alarms, and the maintenance notes through Relate's full-text index |
| `note`, `writers` | a note's text; the ST lines that write a tag, with the condition they run under |
| `inputs_of` | every input a tag depends on, whatever its value: the static answer, for comparison |
| `load_scenario`, `list_scenarios` | switch the simulated line to another scenario |
| `schema`, `cypher` | the graph's labels and relationships; a read-only Cypher query (writes are refused) |

`plctrace mcp --db store/jam_pe3` serves a stored graph instead (no simulator, so no `what_if`).

## The browser view

`web/` is a static page. For each scenario it fetches `web/data/<scenario>.json`, creates the graph in
[`@relate/relate-wasm`](https://www.npmjs.com/package/@relate/relate-wasm) with UNWIND batches (about
700 nodes and 1,400 relationships in 130 ms), and then:

- draws the line from a Cypher query over zones, devices and their signals;
- shows the trace for whatever you click (made by the Python tracer at export time, the same text as
  the CLI);
- runs the plain dependency query live beside it, so you can see 15 inputs against one cause, and that
  ES2 is not among the 15 at all (it acts through the safety relay's wiring, which the tracer follows);
- has a Cypher console with examples.

Run it locally: `python -m http.server -d web 8000` and open http://localhost:8000. After changing the
demo, `plctrace web` rewrites `web/data`. Links such as `#pallet_change/C4` open a scenario and a
trace directly (a zone, a device, or the tag the scenario asks about).

## How it uses Relate

Relate is the only store. Everything the tracer and the tools know comes from Cypher over one graph:

- **Embedded Python** (`relate-db`): `graph.load` replaces the graph in one transaction with UNWIND
  batches (about 830 nodes and 1,600 relationships in 60 ms), with unique keys on `Tag.path`, `Stmt.id`,
  `Device.name`, `Alarm.code` and `Zone.name`, and a full-text index on the notes. In memory for `--scenario`, a directory store for `--db`.
- **The tracer** (`plctrace/why.py`) reads only through Cypher: a tag's writers
  (`(:Stmt)-[:WRITES]->(:Tag)`), the event before a given moment
  (`(:Event)-[:CHANGED]->(:Tag) WHERE e.i < $i ORDER BY e.i DESC`), a device's wiring, zone, alarms
  and notes, the devices feeding a safety relay (`[:FED_BY]`), a motor's run output for its feedback.
- **Variable-length paths** for the static comparison (`[:FEEDS*1..40]`) and for `inputs_of`.
- **Full-text search** over maintenance notes (`db.index.fulltext.queryNodes`) in `find`.
- **WebAssembly**: the same graph, loaded and queried in the browser.

The graph:

```
(Instance)-[:OF_TYPE]->(Pou)            (Instance)-[:PART_OF]->(Instance)     (Tag)-[:OF]->(Instance)
(Stmt)-[:WRITES]->(Tag)                 (Tag)-[:READ_BY {role, neg}]->(Stmt)  (Tag)-[:FEEDS]->(Tag)
(Device)-[:WIRED_TO {role}]->(Tag)      (Device)-[:IN_ZONE]->(Zone)           (Zone)-[:FEEDS_INTO]->(Zone|Device)
(Device)-[:FED_BY]->(Device)            (Alarm)-[:ON]->(Tag)                  (Note)-[:ABOUT]->(Device|Zone|Alarm)
(Event)-[:CHANGED]->(Tag)               (Event)-[:BY]->(Stmt)
```

A `Stmt` is one write: an assignment, an FB input or output, or a standard FB's output. It carries the
source line, the expression, the full condition it runs under (IF/ELSIF/CASE branches, RETURNs before
it) and the values it read the last time it ran. An `Event` is one change of a tag, with the statement
that made it and the values that statement read at that moment.

## How the tracer decides

- **Follow only what decides.** For `A AND B AND NOT C` = FALSE, follow the terms that are FALSE. For
  an AND that is TRUE, no single term decides, so follow the one that changed last: it is what made
  the result change.
- **Latched values are explained when they were set.** `C3.Fault` was set 6.7 s ago; the trace goes
  to the event that set it and evaluates the statement with the values it read then (the eye was
  blocked, the timer had run 8 s). The writes that would clear it give the remedy (press START).
  Seal-in latches (`Run := (Start OR Run) AND NOT Stop`) are explained by the Start that set them or
  the Stop that dropped them.
- **Order inside a scan counts.** Past values are looked up by event sequence number, not by time, and
  a write inside an IF records the values the IF saw when it chose the branch.
- **The plant is part of the program.** A motor without feedback leads to its run output; a safety
  relay that is off leads to the e-stops and doors wired into it.
- **Not every stop is a fault.** Tags can have a role in `plant.yaml` (`*.Fault: fault`,
  `*.Waiting: wait`). Causes rank fault, safety, interlock, then wait, so a zone queuing behind a
  palletiser changing pallets is reported as a normal wait.

### Numbers

Measured on a desktop PC (jam_pe3, Python 3.14, Relate 1.5.0):

| Step | Time |
|---|---|
| Parse and build the ST program | 67 ms |
| Simulate start-up, 30 s of running and the fault (500 events) | 0.24 s |
| Load the graph into Relate (827 nodes, 1,581 relationships, one transaction) | 78 ms |
| `why("M1Run")` over the graph | 7 ms |
| The whole CLI command, from process start | 0.65 s |
| Load a scenario into Relate WASM in the browser | 125-140 ms |

[docs/DESIGN.md](docs/DESIGN.md) has the details; [docs/PROJECT.md](docs/PROJECT.md) explains the whole project from the start;
[docs/TEST_PLAN.md](docs/TEST_PLAN.md) lists the manual checks.

## Your own program

A demo folder has the ST files, a `plant.yaml` (zones, devices and the tags they are wired to, alarms,
tag roles), a `scenarios.yaml` for the simulator and `notes/*.md` with front matter
(`title`, `about: [PE3, A302]`). `plctrace --demo path/to/folder why ...` uses it. The simulator's
conveyor model (`plctrace/sim/beltline.py`) is specific to belt lines; the parser, the scan engine,
the graph and the tracer are not.

Supported ST (a tested subset of IEC 61131-3, not full compliance): PROGRAM and FUNCTION_BLOCK with
VAR sections and `AT %IX0.0` addresses; assignments, IF/ELSIF/ELSE, CASE with ranges, RETURN, FB calls
with `:=` and `=>`; BOOL, integer, REAL and TIME expressions, typed literals, the conversion
functions, SEL, MUX, LIMIT, MIN, MAX, ABS; TON, TOF, TP, R_TRIG, F_TRIG, SR, RS, CTU, CTD. Integer
division truncates toward zero and MOD takes the dividend's sign. A division by zero or a conversion
out of range is a runtime error: the statement is skipped and the error is shown in the trace with
its file and line.

Not supported: loops, arrays, pointers, methods, calling a user FUNCTION, more than one call of the
same FB instance per scan. A value stored to an integer variable that does not fit its type is a
runtime error, but the steps of an expression are computed without limits, and REAL is computed as
64-bit. TIME and REAL values are not kept in the history, so a timer's elapsed
time in the past shows its current value.

## Built with

Python, [Lark](https://github.com/lark-parser/lark) for the ST grammar, Relate (`relate-db` and
`@relate/relate-wasm`), the MCP Python SDK. The tracer itself uses no LLM.

The results are checked by the test suite and CI on Python 3.10 to 3.14: see
[docs/TEST_PLAN.md](docs/TEST_PLAN.md).

## Licence

MIT, see [LICENSE](LICENSE). Relate is Apache-2.0 (Neo4j). The demo line's zone logic follows the
author's own [QNX-PLC](https://github.com/bartoszmilewski-engineeringsupport/qnx-plc) conveyor program
(MIT). The demo program, plant and notes were written for this project; they describe no real site.