AI Agents in Embedded: Opening the Full Pipeline
I open one AI-agent-built i.MX8M Plus sensor driver project, folder by folder: specs, property tests, review agents, and feedback loops.
On this page
- The Project Tree
- The Spec
- Four Test Layers
- Layer 1: Property-Based Tests (milliseconds, host)
- Layer 2: Spec-Driven Tests (seconds, target)
- Layer 3: Fuzzing (hours, host)
- Layer 4: Hardware-in-the-Loop (minutes, real hardware)
- CLAUDE.md: What Stays, What Goes
- Review Agents
- The Complete Loop
- Where This Breaks
- Getting Started
In the first post of this series I built a spec-driven feedback loop: acceptance criteria in a markdown file, a test wrapper that emits JSON, and an agent that iterates on those structured results. In the second post I stacked three layers of context on top of it: CLAUDE.md for hardware constraints, subagents that do nothing but review, and feedback with the compiler in the loop.
Both posts explain why each piece is there. Neither shows what the project looks like when you open the folder. I am writing this one to fill that gap: one project, every file in it, and how they fit together.
The target is an IMU sensor driver for i.MX8M Plus. It uses SPI with DMA, builds with Yocto scarthgap, and was tested on a Raspberry Pi 4. I developed it end to end with Claude Code. It is the same driver I kept using as the running example in the previous two posts, and this time I take it apart completely.
The Project Tree
sensor-driver/
├── CLAUDE.md
├── .claude/
│ ├── rules/
│ │ ├── kernel.md
│ │ ├── dts.md
│ │ └── test.md
│ └── agents/
│ ├── supervisor.md
│ ├── concurrency-reviewer.md
│ ├── register-contract-reviewer.md
│ ├── side-effect-reviewer.md
│ ├── coding-standard-reviewer.md
│ └── test-coverage-reviewer.md
├── specs/
│ └── imu-driver.md
├── tests/
│ ├── conftest.py
│ ├── inventory.yaml
│ ├── test_imu_driver.py
│ ├── test_imu_properties.py
│ ├── test_imu_hil.py
│ └── fuzz/
│ ├── corpus/
│ └── harness_spi_parser.c
├── scripts/
│ ├── run_target_tests.sh
│ └── static_analysis.sh
├── docs/
│ └── hardware/
│ └── imu-register-map.md
├── drivers/
│ └── imu/
│ ├── imu_core.c
│ ├── imu_dma.c
│ ├── imu_spi.c
│ └── imu.h
└── meta-sensor/
└── recipes-kernel/
└── linux-imx/
└── sensor-driver.bbappend
Each directory has its own role in the pipeline. Following them in the order the agent meets them during one development cycle makes the structure easier to see.
The first thing the agent reads in every session is CLAUDE.md. It runs ~20 lines: hardware constraints and learned corrections, and nothing else. I left out any description of the project structure, because the agent infers that from the repo itself. The details are in the context engineering post. Next to it sits .claude/rules/, scoped context that loads only when the agent edits a matching file. kernel.md binds to drivers/**/*.c, dts.md to *.dts and *.dtsi, test.md to tests/**/*.py. Rather than putting everything into CLAUDE.md, I keep each piece of context small and pointed at one thing.
.claude/agents/ holds the system prompts for the five specialized reviewers and the supervisor. Each file defines one agent’s role and checklist, and stops there. The concurrency and register contract reviewers each run 2 instances in parallel, so the same check happens twice, while the other three run once. The supervisor collects the results from every instance.
What the agent builds is decided by specs/: acceptance criteria written as markdown tables, one file per driver or module, from which the agent builds its tests. Those tests end up in tests/, four kinds of them. test_imu_driver.py holds spec-driven example tests, test_imu_properties.py holds property-based tests (Hypothesis + CFFI), and fuzz/ holds AFL++ harnesses. Alongside them, conftest.py and inventory.yaml are the labgrid configuration for reaching the target.
Running the tests falls to the two wrapper scripts in scripts/. run_target_tests.sh deploys the module, runs pytest, and returns JSON, and static_analysis.sh runs cppcheck and clang-tidy and writes the results out as JSON. docs/hardware/ keeps the register maps, errata notes, and pinout diagrams taken from the datasheets, which the register contract reviewer refers to during review.
The driver source itself lives in drivers/imu/, split by concern into core logic, DMA handling, and SPI communication. meta-sensor/ is the Yocto layer, and its .bbappend slots the driver into the BSP build.
The Spec
Everything starts here. Before the agent writes a single line of driver code, this file is already in place:
# IMU Sensor Driver (ICM-42688-P) Acceptance Criteria
## Target
- SoC: i.MX8M Plus (Cortex-A53)
- Interface: SPI (mode 3, 10MHz)
- DMA: SDMA channel, 64-byte aligned buffers
- Test board: Raspberry Pi 4 (Yocto scarthgap, kernel 6.1 LTS)
| ID | Criterion | Metric | Method |
|---|---|---|---|
| AC-1 | Sampling rate 1kHz within 1% tolerance | sample count per second | sysfs counter over 10s |
| AC-2 | Data integrity after 10K DMA transfers | CRC32 match rate = 100% | CRC on raw buffer vs parsed |
| AC-3 | RSS memory < 2MB after 1hr soak | /proc/meminfo delta | stress-ng + periodic sample |
| AC-4 | Recovery within 3s after SPI bus error | time to first valid read | unbind/rebind SPI device |
| AC-5 | IRQ-to-userspace latency < 500us (p99) | timestamp delta | cyclictest-style measurement |
| AC-6 | No data loss under CPU stress | sample gap detection | stress-ng —cpu 4 + counter |
## Constraints
- Kernel 6.1 LTS: no spi-fault-inject module available
- DMA buffers: 64-byte aligned (L1 cache line on Cortex-A53)
- SPI mode 3 (CPOL=1, CPHA=1) for ICM-42688-P
- CTRL_REG1 at 0x4E (not 0x11 as in MPU-6050)
The constraints section matters as much as the criteria. It keeps the agent from writing tests that reach for tools that are not there, or that set up the hardware wrong. Each constraint comes from something that actually broke during development.
Four Test Layers
The spec drives the example-based tests. But example-based tests only cover the scenarios I thought to write down. So there are four layers, and each one goes after bugs a level deeper than the one before.
Layer 1: Property-Based Tests (milliseconds, host)
These run on the host, against C code compiled as a shared library. No target hardware is needed. CFFI is a Python foreign function interface for calling C functions directly, and it loads the compiled C as is. Hypothesis then generates inputs by the thousand and shrinks any failure to a minimal case. Installing both takes one line: pip install cffi hypothesis.
# tests/test_imu_properties.py
from hypothesis import given, strategies as st, settings
import cffi
ffi = cffi.FFI()
ffi.cdef("""
typedef struct {
int16_t accel[3];
int16_t gyro[3];
uint32_t timestamp;
uint8_t status;
} imu_sample_t;
int parse_imu_frame(const uint8_t *buf, int len, imu_sample_t *out);
int build_imu_frame(const imu_sample_t *sample, uint8_t *buf, int max_len);
""")
lib = ffi.dlopen("./build/libimu_host.so")
@given(data=st.binary(min_size=1, max_size=64))
def test_parser_never_crashes(data):
"""No input -- valid, truncated, or garbage -- should crash the parser."""
buf = ffi.new("uint8_t[]", data)
sample = ffi.new("imu_sample_t *")
ret = lib.parse_imu_frame(buf, len(data), sample)
assert ret in (0, -1)
@given(
accel=st.tuples(*[st.integers(-32768, 32767)] * 3),
gyro=st.tuples(*[st.integers(-32768, 32767)] * 3),
ts=st.integers(0, 2**32 - 1),
)
def test_roundtrip_preserves_values(accel, gyro, ts):
"""Encode then decode must recover the original values."""
sample_in = ffi.new("imu_sample_t *")
for i in range(3):
sample_in.accel[i] = accel[i]
sample_in.gyro[i] = gyro[i]
sample_in.timestamp = ts
buf = ffi.new("uint8_t[64]")
n = lib.build_imu_frame(sample_in, buf, 64)
assert n > 0
sample_out = ffi.new("imu_sample_t *")
assert lib.parse_imu_frame(buf, n, sample_out) == 0
assert tuple(sample_out.accel) == accel
assert tuple(sample_out.gyro) == gyro
assert sample_out.timestamp == ts
@given(data=st.binary(min_size=1, max_size=15))
@settings(max_examples=10000)
def test_short_frames_rejected(data):
"""Frames shorter than minimum valid length must return -1."""
buf = ffi.new("uint8_t[]", data)
sample = ffi.new("imu_sample_t *")
# minimum frame: header(2) + payload(12) + crc(2) = 16 bytes
assert lib.parse_imu_frame(buf, len(data), sample) == -1
In 10 seconds this found a bug I had missed for three weeks: a specific 7-byte sequence that matched the frame header but carried a truncated payload. The parser was reading past the end of the buffer. Hypothesis shrank it to the minimal case by itself.
What this layer catches is buffer overflows, off-by-one errors, encoding/decoding mismatches, and edge cases in protocol parsing. These matter when electrical noise sends garbage over SPI, and they are the cases no person would think to write a test for.
Layer 2: Spec-Driven Tests (seconds, target)
These run on a real Raspberry Pi 4 through labgrid, with one test function per acceptance criterion.
# tests/test_imu_driver.py
import time
def test_sampling_rate_1khz(target):
"""AC-1: Sampling rate 1kHz within 1% tolerance."""
target.run("echo 1000 > /sys/class/imu/imu0/sampling_rate")
target.run("echo 0 > /sys/class/imu/imu0/sample_count")
time.sleep(10)
count = int(target.run("cat /sys/class/imu/imu0/sample_count"))
rate = count / 10.0
assert 990 <= rate <= 1010, f"Rate {rate} Hz outside 1% of 1000 Hz"
def test_dma_data_integrity(target):
"""AC-2: Data integrity after 10K DMA transfers."""
result = target.run("imu_integrity_test --transfers 10000 --verify crc32")
# imu_integrity_test is a small C program deployed to the target
lines = result.strip().split('\n')
last = lines[-1] # "PASS: 10000/10000 CRC match" or "FAIL: 9153/10000"
assert last.startswith("PASS"), f"Integrity check: {last}"
def test_spi_error_recovery(target):
"""AC-4: Recovery within 3s after SPI bus error."""
# Driver exposes force_error sysfs since spi-fault-inject is unavailable on kernel 6.1
target.run("echo 1 > /sys/class/imu/imu0/force_error")
time.sleep(0.5)
start = time.time()
for _ in range(30):
data = target.run("cat /sys/class/imu/imu0/data")
if "error" not in data.lower():
elapsed = time.time() - start
assert elapsed < 3.0, f"Recovery took {elapsed:.1f}s, limit 3s"
return
time.sleep(0.1)
raise AssertionError("Driver did not recover within 3s")
The run_target_tests.sh wrapper deploys the module, runs every test, and returns JSON. The agent never has to deal with SSH itself. This layer catches regressions against the acceptance criteria, timing issues specific to the target, and integration problems that only show up on real hardware with real peripherals.
Layer 3: Fuzzing (hours, host)
A fuzz harness for the SPI frame parser, built with AFL++ instrumentation:
/* tests/fuzz/harness_spi_parser.c */
#include <stdint.h>
#include <stdlib.h>
#include "imu.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
if (size > 256) return 0; /* limit input size */
imu_sample_t sample;
parse_imu_frame(data, (int)size, &sample);
return 0;
}
# Build and run
afl-clang-fast -o fuzz_parser tests/fuzz/harness_spi_parser.c drivers/imu/imu_spi.c -I drivers/imu/
afl-fuzz -i tests/fuzz/corpus -o findings -- ./fuzz_parser
I seed the corpus with valid frames, truncated frames, and known-bad sequences. AFL++ runs overnight in CI. In the first week alone it found two bugs: an integer overflow in timestamp parsing, and a use-after-free that fired when the CRC check failed on certain frame lengths.
Fuzzing catches memory safety bugs, undefined behavior, and inputs that cause crashes. Spec-driven tests never see these, because they only appear with specific byte patterns nobody would produce by hand.
Layer 4: Hardware-in-the-Loop (minutes, real hardware)
labgrid runs the real-hardware tests: DMA under CPU stress, recovery after a power cycle, sustained sampling under thermal load. It is slow, but it catches timing bugs and bugs in how peripherals interact.
# tests/test_imu_hil.py (runs via labgrid with power control)
def test_dma_under_cpu_stress(target, power):
"""AC-6: No data loss under CPU stress."""
target.run("stress-ng --cpu 4 --timeout 30 &")
target.run("echo 0 > /sys/class/imu/imu0/sample_count")
time.sleep(30)
count = int(target.run("cat /sys/class/imu/imu0/sample_count"))
expected = 30 * 1000 # 30s at 1kHz
loss = expected - count
assert loss == 0, f"Lost {loss} samples under stress ({count}/{expected})"
This layer catches timing and peripheral-interaction bugs under stress, behavior when recovering from a power cycle, and thermal effects that unit or spec tests miss.
The four layers form a pyramid. Layer 1 runs in milliseconds on every code change, and Layer 2 in seconds on every test cycle. Layer 3 runs overnight, Layer 4 on demand or weekly. Most bugs are caught in layers 1 and 2. The expensive layers pick up whatever gets past them.
CLAUDE.md: What Stays, What Goes
A bloated CLAUDE.md spends tokens without making the results any better (the context engineering post explains why). The only content worth its place is what the agent cannot infer.
My first CLAUDE.md ran to 58 lines, and most of them were waste. It looked like this:
## Project Structure
sensor-driver/ contains the IMU driver source code...
tests/ contains pytest-based tests using labgrid...
meta-sensor/ is the Yocto layer...
## Build
Uses meson build system. Cross-compile with:
meson setup build --cross-file cross-aarch64.ini
ninja -C build
## Testing
Run tests with: ./scripts/run_target_tests.sh build/imu_sensor.ko
The agent infers all of this from meson.build, inventory.yaml, and the folder structure. Those 30-plus lines do no work.
After trimming, 22 lines were left, and the file was far more focused:
## Hardware
- SoC: i.MX8M Plus (Cortex-A53), SPI IMU: ICM-42688-P
- CTRL_REG1 = 0x4E (not 0x11). SPI mode 3 (CPOL=1, CPHA=1)
- DMA buffers: 64-byte aligned (L1 cache line)
## Learned Corrections
- 2026-01-15: ICM-42688-P CTRL_REG1 is 0x4E, not 0x11
- 2026-01-18: DMA buffers must be 64-byte aligned on Cortex-A53
- 2026-02-03: SPI mode 3 for ICM-42688-P, not mode 0
- 2026-02-22: Kernel 6.1 LTS lacks spi-fault-inject module
- 2026-03-01: spin_lock_bh() in process context, spin_lock() in softirq
## Never Do This
- kmalloc(GFP_KERNEL) or msleep under spin_lock
- CPU access to DMA buffer without dma_sync_single_for_cpu
- Assume register addresses from generic datasheets -- always check ICM-42688-P
Every line comes from a real bug. The file grows when the agent makes a new mistake, and shrinks again once a linter or a scoped rule starts enforcing that constraint instead.
Review Agents
Not every reviewer runs on every change. Each agent checks a file glob when it starts, to see whether there is anything for it to look at:
| Reviewer | Triggers on | Instances |
|---|---|---|
| Concurrency | drivers/**/*.c, drivers/**/*.h | 2 (parallel) |
| Register contract | drivers/**/*.c, *.dts, *.dtsi | 2 (parallel) |
| Side-effect | any non-test file | 1 |
| Coding standard | drivers/**/*.c, drivers/**/*.h | 1 |
| Test coverage | tests/**/*.py, specs/**/*.md | 1 |
The concurrency and register contract reviewers run 2 instances each (I covered why in the context engineering post). A single LLM pass sometimes goes right past an issue that the same model catches on a second run.
A test-only commit wakes only the test coverage reviewer. A device tree change brings in the register contract reviewer and skips concurrency. Most commits touch driver code, so 3-4 reviewers fire with 5-6 instances in total. The supervisor gathers all of it:
Every reviewer’s system prompt has the same shape: one sentence that fixes its scope, a checklist of specific things to verify, and a plain instruction to ignore anything outside that scope.
The concurrency reviewer’s core prompt:
You review ONLY concurrent execution safety. Ignore style, naming, performance.
## Checklist
- [ ] No spinlock held in sleepable context
- [ ] Correct lock variant for execution context
- [ ] DMA buffers synced before CPU access
- [ ] No shared state accessed without protection
- [ ] Lock ordering consistent across all paths
The register contract reviewer:
You verify ONLY that hardware register accesses match the datasheet.
Reference: docs/hardware/imu-register-map.md
## Checklist
- [ ] Register addresses match ICM-42688-P datasheet
- [ ] Bit field masks and shifts correct
- [ ] Read/write direction matches register type
- [ ] Initialization sequence follows datasheet power-on requirements
- [ ] SPI mode, clock speed, and CS polarity correct
The supervisor’s rule is simple. If 2 or more instances or reviewers flag the same issue, it counts as high confidence and the agent fixes it on its own. If only 1 flags it, it counts as medium confidence: it goes into the report with a flag for human review, and it is never auto-fixed. For a critical reviewer running 2 instances, the moment both instances agree, the issue is already high confidence.
Before each review pass, scripts/static_analysis.sh runs cppcheck and clang-tidy and writes JSON. That JSON goes into each reviewer’s prompt as extra context. With the static-analysis findings underneath the LLM review, more gets caught than with either one alone.
The Complete Loop
Here is how one cycle runs, timed on my setup: Windows laptop host, RPi4 target, connected over ethernet.
| Step | Action | Time |
|---|---|---|
| 1 | Agent reads spec + generates/modifies driver code | ~30s |
| 2 | Cross-compile (aarch64, meson + ninja) | ~15s |
| 3 | Static analysis (cppcheck + clang-tidy to JSON) | ~10s |
| 4 | Property-based tests (Hypothesis, 1000 examples) | ~3s |
| 5 | Deploy + target tests (run_target_tests.sh to JSON) | ~240s |
| 6 | Agent reads all results, fixes failures | ~30s |
| Total | ~5.5min |
Steps 3 and 4 run on the host while step 5 runs on the target. If the property-based tests or static analysis catch a bug first, the agent fixes it before spending 4 minutes on a target deployment. To me that ordering matters more than anything else in the pipeline: fail fast, fail cheap.
Only after the agent’s fix passes every test do the reviewers run (~45 seconds total with concurrent API calls). The files that changed decide which reviewers show up. Touching driver code brings in both critical reviewers (2 instances each) plus side-effect and coding standard. Changing only tests brings in the test coverage reviewer and nothing else. The supervisor writes a report. High-confidence issues get fixed automatically and re-tested; medium-confidence issues only get flagged. A first pass usually turns up 1-2 issues, most often locking discipline or a missing DMA sync. By the second iteration the code usually comes out clean.
The whole loop, from “here’s the spec” to “all tests pass, all reviewers clear,” usually takes 2-3 iterations and 15-20 minutes for a driver feature. Compare that with the manual workflow from the first post: 30-60 minutes per iteration, 3-5 iterations, and only the happy path covered.
Where This Breaks
The pipeline handles the cases it was built for. Past those, it stops being any help.
Formal verification is one of them. Martin Kleppmann predicts that AI will bring formal verification into the mainstream within a few years, but the tooling is not yet ready for general-purpose embedded driver work. For now, property-based testing is the closest practical approximation.
Physical debugging is further out still. When the logic analyzer shows the SPI clock at 8MHz instead of 10MHz, or the DMA transfer completes and the interrupt never fires, the pipeline cannot help. That is work for an oscilloscope. The pipeline’s responsibility ends at “the code is correct according to its spec.” Whether the spec matches physical reality is still a question for a person.
Security regression, context degradation, and spec quality are covered at length in the context engineering post. In short: iterative refinement can quietly introduce vulnerabilities (the subagent reviewers act as a safety net), the agent starts to drift past the 2-hour mark (use /clear to reset), and the pipeline is only as good as its spec (writing precise acceptance criteria is the largest investment a person makes here; see the TDD post).
Getting Started
You do not need all of this at once. Each layer catches a different kind of bug, and you can stop at any point.
| Step | Action | Reference |
|---|---|---|
| 1 | specs/<driver>.md with 5 acceptance criteria | Post 1 |
| 2 | Test wrapper script (deploy + test + JSON) | Post 1 |
| 3 | CLAUDE.md with hardware constraints | Post 2 |
| 4 | One reviewer agent (concurrency or register) | Post 2 |
| 5 | Property-based tests + static analysis in CI | This post |
The agent isn’t the point. The feedback loops are. The agent just makes them cheap enough to actually use.
Comments
Loading comments...