Metadata-Version: 2.5
Name: traceforge-pcb
Version: 1.0.1
Summary: An open-source AI agent that designs, edits and reviews KiCad circuit boards from plain English.
Project-URL: Homepage, https://github.com/ashutosh-rath02/traceforge
Project-URL: Repository, https://github.com/ashutosh-rath02/traceforge
Project-URL: Issues, https://github.com/ashutosh-rath02/traceforge/issues
Project-URL: Changelog, https://github.com/ashutosh-rath02/traceforge/blob/main/CHANGELOG.md
Project-URL: Documentation, https://github.com/ashutosh-rath02/traceforge/tree/main/docs
Author: Traceforge contributors
License-Expression: MIT
License-File: LICENSE
Keywords: agent,autorouter,eda,electronics,kicad,llm,mcp,pcb,schematic
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Electronic Design Automation (EDA)
Requires-Python: >=3.11
Requires-Dist: anthropic<3,>=2.3
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic<3,>=2.10
Requires-Dist: pyyaml<7,>=6
Requires-Dist: rich>=13
Provides-Extra: acp
Requires-Dist: agent-client-protocol<1.0,>=0.12; extra == 'acp'
Provides-Extra: all
Requires-Dist: cryptography<49; (sys_platform == 'darwin' and platform_machine == 'x86_64') and extra == 'all'
Requires-Dist: cryptography>=46; (python_version >= '3.14') and extra == 'all'
Requires-Dist: fastapi>=0.115; extra == 'all'
Requires-Dist: langchain-core<2,>=1.0; extra == 'all'
Requires-Dist: mcp<3,>=2.3; extra == 'all'
Requires-Dist: uvicorn>=0.30; extra == 'all'
Requires-Dist: websockets>=13; extra == 'all'
Provides-Extra: altium
Requires-Dist: olefile>=0.46; extra == 'altium'
Provides-Extra: datasheets
Requires-Dist: pypdf>=4; extra == 'datasheets'
Provides-Extra: desktop
Requires-Dist: fastapi>=0.115; extra == 'desktop'
Requires-Dist: pywebview>=5; extra == 'desktop'
Requires-Dist: uvicorn>=0.30; extra == 'desktop'
Requires-Dist: websockets>=13; extra == 'desktop'
Provides-Extra: dev
Requires-Dist: agent-client-protocol<1.0,>=0.12; extra == 'dev'
Requires-Dist: cryptography<49; (sys_platform == 'darwin' and platform_machine == 'x86_64') and extra == 'dev'
Requires-Dist: cryptography>=46; (python_version >= '3.14') and extra == 'dev'
Requires-Dist: fastapi>=0.115; extra == 'dev'
Requires-Dist: httpx>=0.27; extra == 'dev'
Requires-Dist: kicad-python>=0.4; extra == 'dev'
Requires-Dist: mcp<3,>=2.3; extra == 'dev'
Requires-Dist: olefile>=0.46; extra == 'dev'
Requires-Dist: openai>=1.60; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Requires-Dist: textual>=1.0; extra == 'dev'
Requires-Dist: uvicorn>=0.30; extra == 'dev'
Requires-Dist: websockets>=13; extra == 'dev'
Provides-Extra: gemini
Requires-Dist: google-genai>=1.50; extra == 'gemini'
Provides-Extra: images
Requires-Dist: pillow>=10; extra == 'images'
Provides-Extra: kicad-plugin
Requires-Dist: kicad-python>=0.4; extra == 'kicad-plugin'
Provides-Extra: langchain
Requires-Dist: langchain-core<2,>=1.0; extra == 'langchain'
Provides-Extra: mcp
Requires-Dist: cryptography<49; (sys_platform == 'darwin' and platform_machine == 'x86_64') and extra == 'mcp'
Requires-Dist: cryptography>=46; (python_version >= '3.14') and extra == 'mcp'
Requires-Dist: mcp<3,>=2.3; extra == 'mcp'
Provides-Extra: openai
Requires-Dist: openai>=1.60; extra == 'openai'
Provides-Extra: remote
Requires-Dist: websockets>=13; extra == 'remote'
Provides-Extra: server
Requires-Dist: fastapi>=0.115; extra == 'server'
Requires-Dist: uvicorn>=0.30; extra == 'server'
Requires-Dist: websockets>=13; extra == 'server'
Provides-Extra: tui
Requires-Dist: textual>=1.0; extra == 'tui'
Description-Content-Type: text/markdown

# Traceforge

**An open-source AI agent that designs, edits and reviews KiCad circuit boards from plain English.**

Describe a board, and Traceforge picks the parts, writes the schematic, places and routes the PCB, runs KiCad's checks and fixes what they report. Point it at an existing KiCad project and it can change it, answer questions about it, or review it before you send it to the fab. It runs in your terminal, inside Claude Code / Cursor / Codex as an MCP server, as a LangChain Runnable, or as a hosted service your team shares.

<p align="center">
  <img src="docs/images/attiny_usbc_board.png" width="520" alt="Board generated and routed by traceforge"><br>
  <em><a href="examples/attiny_usbc/design.yaml">examples/attiny_usbc</a>: 21 parts, generated, placed and routed by traceforge, with ground pours on both layers. KiCad DRC: 0 errors, 0 unconnected.</em>
</p>

## What it does

- **Design from a description.** The agent researches parts in your installed KiCad libraries, writes a *design spec* (parts, footprints, values and which net every pin is on), and compiles it into a real KiCad project: a readable schematic (functional groups in labelled boxes, orthogonal wires and junctions, KiCad power symbols, hierarchical sheets for big designs), a board with every footprint, net, outline, net class and fab rule, then placement and routing.
- **Edit existing projects.** Structured tools move and rotate footprints, add tracks, vias and copper pours, set fields such as LCSC or MPN, and change outlines, keeping UUIDs, nets and pad rotations consistent. For anything else it edits the S-expression files directly.
- **Verify, not guess.** It runs KiCad ERC and DRC (with schematic parity), exports KiCad's own netlist, and adds built-in checks: fab capability limits (JLCPCB, PCBWay, OSH Park), schematic/board parity, courtyard overlaps, edge-mount connectors that are not on the board edge, copper-to-edge distance, silkscreen size, missing part numbers and routing completeness.
- **Pre-fab review.** `traceforge validate` runs a 9-stage review (intake, architecture, parts, schematic, parity, placement, routing, DFM/DFA, release). Deterministic checks run first, then a panel of read-only AI reviewers, one per concern, returns findings rated P0–P3, each with evidence. You get a Markdown and JSON report and a CI-friendly exit code.
- **Fab outputs.** Gerbers and drill files, BOM, a JLCPCB-style placement file (CPL), netlist and SVG renders.

## Quick start

```bash
pip install "traceforge-pcb[mcp]"         # the command and the Python package are both `traceforge`
export ANTHROPIC_API_KEY=sk-ant-...      # or: ant auth login
traceforge doctor                         # checks KiCad, libraries and model access
# API keys can also go in a .env file in the project (or a parent folder) or in
# ~/.config/traceforge/.env; only API-key variables are read from .env files.
```

Requirements: Python 3.11+, KiCad 7, 8, 9 or 10 with its standard symbol and footprint libraries (KiCad 8 or newer gives the full ERC, parity DRC and 3D render; KiCad 7 works with reduced checks, see [KiCad versions](#kicad-versions)), and an API key (Anthropic, OpenAI or Gemini) for the agent features. The `build`, `route`, `check`, `export`, `search` and `pins` commands need no API key.

Try it in under a minute with no API key: compile an example spec into a KiCad project, route it and run the checks.

```bash
traceforge doctor                                              # is KiCad found? what is missing?
traceforge build 555_blinker --out build/ --route --check      # a bundled example, about 10 seconds
# build/blinker555.kicad_pro opens in KiCad: schematic, routed board, ground pours
traceforge examples                                            # the other bundled boards
traceforge examples copy attiny_usbc                           # copy one to edit its design.yaml
traceforge docs                                                # the documentation, offline
```

The PyPI distribution is named `traceforge-pcb` because `traceforge` is taken there by an unrelated project. Extras are installed the same way: `traceforge-pcb[desktop]`, `[altium]`, `[datasheets]`, `[gemini]`, `[openai]`, `[tui]`, `[acp]`, `[langchain]`, `[server]`. To work on the code, see [Development](#development).

If pip starts compiling `cryptography` (Rust errors, typically on a brand-new Python such as 3.14), upgrade pip and add `--only-binary cryptography`. Traceforge looks for `kicad-cli` on `PATH`, in `/Applications` and `~/Applications` (macOS), in `Program Files\KiCad\<version>` and `%LOCALAPPDATA%\Programs\KiCad\<version>` (Windows) and in `/usr/bin`; set `TRACEFORGE_KICAD_CLI` and `KICAD10_SYMBOL_DIR` / `KICAD10_FOOTPRINT_DIR` (or the KICAD9/8 names) for other locations. `traceforge doctor --json` prints what was found.

### Talk to it

```bash
cd my-board/
traceforge                                 # interactive session
traceforge run "Add reverse-polarity protection to the 12 V input and re-run DRC"
traceforge plan "Move this design to a 4-layer stackup"     # writes a plan, changes nothing
traceforge ask "What limits the current on the 3V3 rail?"   # read-only answer
traceforge run --plan .traceforge/plans/4-layer.md          # carry out a saved plan
```

In a session, `/help` lists the commands: `/mode`, `/approve` (`/approve shell` sets which commands auto mode runs), `/effort`, `/model` (an id or a tier: `fast`, `balanced`, `best`), `/resume`, `/threads`, `/export`, `/usage`, `/context`, `/copy`, `/attach` and `/paste` (images), `/skills`, `/plans` and `/build`, `/hooks`, `/trust`, `/jobs` and `/kill` (background commands), `/cwd`, `/update`. Mention files with `@path` (images are attached) and paste KiCad S-expressions directly. Conversations are saved; `traceforge threads [list|show|export|rename|delete|search]` manages them and `-r` continues the last one.

- **Skills**: `.traceforge/skills/<name>/SKILL.md` (front matter + instructions), run as `/<name> task`; `traceforge skills new <name>` creates one.
- **Hooks**: `.traceforge/hooks.yaml` with `before_turn`, `after_edit` and `after_turn` commands (see `traceforge/hooks.py`). Project hooks, and project settings that change the server or loosen approvals, only apply after `traceforge trust`.
- **Background commands**: the agent can run long commands with `background: true`; their output is fed back after the turn.
- **Hosted mode** resumes a turn after a dropped connection (protocol 2 checkpoints); `traceforge usage` and `auth status` show the key's quota.

### Build a board from a spec, no AI involved

The example specs ship inside the package (`traceforge examples` lists them); `build` takes a path to your own
spec or the name of a bundled example.

```bash
traceforge build 555_blinker --out build/ --route --check
```

```yaml
name: blinker555
board: {width: 40, height: 30, corner_radius: 1.5}
power_nets: [VCC, GND]                  # get a PWR_FLAG so ERC knows they are driven
net_classes:
  Power: {nets: [VCC, GND], track_width: 0.5}
parts:
  - ref: U1
    symbol: Timer:NE555P
    footprint: Package_DIP:DIP-8_W7.62mm
    pins: {1: GND, 2: TRIG, 3: OUT, 4: VCC, 5: CTRL, 6: TRIG, 7: DIS, 8: VCC}  # numbers: names differ between KiCad versions
  - {ref: R1, symbol: "Device:R", footprint: "Resistor_SMD:R_0805_2012Metric", value: 10k, pins: {1: VCC, 2: DIS}}
  # ...
```

Pins can be given by number or by name. `traceforge pins Timer:NE555P` shows a symbol's pins, and `traceforge search symbol esp32 s3` / `traceforge search footprint SOT-23` find parts. The full spec schema is in [`src/traceforge/design/spec.py`](src/traceforge/design/spec.py).

### Multi-layer boards

The same spec describes 2, 4, 6 and 8 layer boards: `board.layers`, a `stackup` (JLCPCB presets, plane layers,
split planes, copper weights, dielectrics), parts on both sides (`side: bottom`, `decoupling: opposite`),
`net_classes` with enforced minimum widths and allowed layers, `rule_areas` keep-outs, `diff_pairs` with a
target impedance (the width is solved for the layer the pair ends up on, outer microstrip or inner stripline)
and an optional KiCad skew rule (`drc_skew`), `length_groups` (byte lanes and buses matched by serpentine
tuning), a `rules` block for a finer board-wide clearance (never below the fab's minimum; `build --route` uses it, the standalone `route` command takes `--clearance`), and automatic
fan-out of QFN, QFP, BGA and fine-pitch connector pins (`escape`, `--no-fan-out`). The router reports, per
net, length, vias, impedance and reference planes per layer, and says why a net failed
(`failure_reasons`); nets that still fail go through a rip-up-and-reroute pass (`repair_time`). Through vias
only, impedance from closed-form formulas, and routing can stop short on dense boards: the 4-layer RP2040, the
6-layer carrier and the USB hub route to within a handful of open connections (not zero), and the 8-layer
BGA board needs via-in-pad. [docs/multilayer.md](docs/multilayer.md) documents every option and
its limits, [docs/tutorials](docs/tutorials/README.md) walks through a 4-layer RP2040, a USB hub and a 6-layer
carrier, and [docs/multilayer-results.md](docs/multilayer-results.md) holds the measured numbers. The agent
chooses the layer count itself (system prompt), the hard tier of `traceforge bench` (`build-h01`, `-h04`,
`-h05`) scores such boards with the same neutral scorer, and the desktop app's board viewer has a toggle per
copper layer.

### Review before fabrication

```bash
traceforge validate                    # dev profile: fails on P0
traceforge validate --profile release  # fails on P0 and P1
traceforge validate --no-review        # deterministic checks only, no API calls
traceforge validate --gate full --until S4 --skip sch.erc --junit out/junit.xml
traceforge validate list               # every check: stage, kind, gate
traceforge validate graph              # stages and check dependencies
traceforge validate explain sch.circuit_rules
```

Exit codes: `0` passed, `1` a gate failed, `2` usage or config error (bad graph, unknown stage or
check), `3` a check errored or was blocked so the result is incomplete, `130` interrupted.

Deterministic checks include LED polarity and resistor current (Vf and current rating from live part data,
else typical by colour; flags LEDs under ~1 mA and currents over the LED or MCU pin rating), USB-C CC
resistor values, button/pull-up topology, distance-based decoupling, LDO output capacitor type,
capacitance and ESR (from the capacitor's catalogue entry vs the regulator's data or a built-in table),
footprint vs part number/symbol package and pin map, hidden reference designators, board rules vs fab
limits, repository portability, intent documents vs design, and BOM/CPL files vs the board. Results are
cached by the hash of the files each check reads; each run is kept in `.traceforge/validate/runs/` with
`next_actions.json`. From Python, `validate(...)` also takes `gate` (stage/full/strict), `until`, `skip`,
`repeat` (consensus), `context_files` and `no_cache`; `traceforge.validate.junit()` and `fix_prompt()`
render JUnit XML and a fix task for the agent.

**Review quality.** Every AI finding must carry a `cites` list (`net:VBUS`, `ref:U1`, `pin:U1.3`,
`file.kicad_sch:120`). A grounding pass checks each cited net, part, pin and file line against the design
(sheet-path prefixes such as `/RAIL_IO_3` vs `RAIL_IO_3`, hierarchical labels and KiCad pin-name suffixes such
as `VCC_2` are matched). A finding citing something that does not exist, or nothing at all, is marked
UNGROUNDED, demoted to a P3 warning (`claimed_severity` keeps what the reviewer said) and can never fail a
gate. Related tools: `errata_hunt` (datasheet and errata documents fetched, candidate items with page/section
citations and severity, de-duplicated and ranked; items without a retrievable source are `verified: false`;
extraction is heuristic), `kicad_thermal` (dissipation per part, copper area from the board's pours, tracks and
vias, junction temperature from theta_JA, hotspots, mitigation; a screening model whose limits it prints) and
`kicad_ipc2221` / the `pcb.ipc2221` check (tracks too narrow for the declared current, spacing too small for the
voltage; declare in `.traceforge/electrical.yaml` or net class names like `Power_10A`; IPC-2221 and IEC 60664-1
style tables are guides, not certification). The `compliance-review` skill adds a DO-160 category checklist;
`thermal-review` guides the thermal workflow.

Extend or override the checks per project in `.traceforge/validate.yaml`:

```yaml
extends: default
disable: [dfa.assembly]
checks:
  - id: custom.usb
    stage: S6
    kind: review
    title: USB 2.0 routing
    prompt: Check D+/D- are routed as a 90-ohm pair, length matched within 0.5 mm, over unbroken ground.
```

### 3D models

`traceforge models3d check` reports, for every footprint, whether its `(model ...)` path resolves in KiCad's 3D library (or `${KIPRJMOD}`), is missing, or absent; real parts without a model are P1, mounting holes and test points are P3. Footprints without a model get library proposals with a confidence (exact name matches 0.90 and up; fuzzy package-family matches stay below that and are never assigned automatically).

```
traceforge models3d assign U1 ~/Downloads/part.step     # copied to ./3dmodels, referenced via ${KIPRJMOD}
traceforge models3d assign --auto                       # exact library matches only
traceforge models3d assign J5 --generate step           # labelled generic box sized from the footprint
traceforge models3d render --side both                  # top and bottom PNG, needs KiCad 8+
```

Assignment never replaces an existing model unless you pass `--overwrite`. Rendering uses `kicad-cli pcb render`, which does not exist in KiCad 7; there the command says so and renders nothing. Generated models are placeholders for fit checks, not the real package.
### Simulate (ngspice)

```bash
traceforge sim run board.kicad_sch --op --source VBUS=5 --probe "i(R6)"      # LED current
traceforge sim run filter.cir --ac "dec 100 10 100k" --probe "v(out)" --export csv svg --pz in,out
traceforge sim tune filter.cir --ac "dec 100 10 100k" --param R1,R2 --target "f3db(v(out))=500"
traceforge sim plot .traceforge/sim/run.raw --formats svg csv
```

Needs `ngspice` on PATH (`apt install ngspice`, `brew install ngspice`) and, for schematics,
`kicad-cli`. Netlists come from the schematic's connectivity; parts without a `Sim.*` model
get a generic stand-in that is reported, and parts with no model are listed as skipped.
Results: summary, `.meas` values, -3 dB point, poles (ngspice `.pz`, else fitted), margins,
CSV, VCD and SVG. `sim tune` adjusts a value until a measurement meets a target. LTspice:
`--engine ltspice` writes a netlist and `.asc` only (LTspice is not run), and an LTspice `.raw`
file can be read with `sim plot`. See `docs/simulation.md`.

### Use it from Claude Code, Cursor or Codex (MCP)

```bash
claude mcp add traceforge -- traceforge -C /path/to/board mcp
```

Or install the Claude Code plugin from this repository (`/plugin marketplace add ashutosh-rath02/traceforge`, then `/plugin install traceforge`): it starts the MCP server and adds a `traceforge-review` skill.

Tools exposed: `status`, `run`, `plan`, `ask`, `resume`, `threads_list`, `check`, `build`, `validate` (gate, until, only/skip, repeat, JUnit path, fix prompt), `validate_info`, `part_lookup`, `part_search`, `parts_check`, `datasheet_fetch` and `models` (available models and per-role routing). The host delegates electronics work, and Traceforge does the KiCad editing and verification. MCP sessions default to `--approve auto` (file edits and simple commands run; potentially destructive shell commands are refused, because there is no one to approve them).

### Use it from LangChain

```python
from traceforge.langchain import TraceforgeRunnable

board = TraceforgeRunnable(workspace="hardware/")
result = await board.ainvoke("Add a 100 nF decoupling capacitor at every IC supply pin")
print(result["output"])
```

## Desktop app

`traceforge app` opens a desktop window around a KiCad project folder: chat tabs on the left and centre, the board and schematic on the right.

```bash
pip install "traceforge-pcb[desktop]"
traceforge app path/to/project        # or run it inside the folder; with no folder it asks
traceforge app --browser              # use your default browser instead of a native window
```

Or download a standalone build (macOS `.app`, Windows `.exe`, Linux) from the GitHub release page, unzip it and open it. KiCad itself is not bundled: the board viewer and the ERC/DRC checks use the `kicad-cli` on your machine.

What is in it:

- **Chat tabs** with Plan / Ask / Agent modes, model, effort and approval pickers, tool-call cards, thinking and usage lines, and approvals (allow once, always allow this tool, switch to auto, or no with a reason). History is local. Edit a message you sent and **branch** from there; the original chat stays.
- **`@` mentions**: type `@` to pick a reference designator (`@U1`, `@C3`) or a file. A mentioned component's value, footprint, pad nets and datasheet link go into the model's context. Drop in or paste screenshots, PDFs and other files; pasted KiCad text is passed as a snippet.
- **Board and schematic viewer**: pan, zoom, click a part to select it. It reloads when the files change. **Ctrl/Cmd+K** on the selected (or hovered) part opens actions such as typical wiring diagram, datasheet summary, pin functions, errata and alternatives, answered in a **quick chat** panel (**Ctrl/Cmd+Shift+Space**) that can attach the current view as an image.
- **Accept / Reject**: the project is snapshotted before each agent turn that may write. Afterwards you see every changed file with a text diff and, for `.kicad_pcb` / `.kicad_sch`, before and after renders with the changed footprints, symbols and tracks highlighted. Reject restores the snapshot byte for byte (a file you edited yourself since the turn is left alone); the agent is told what was rolled back.
- **Next-step chips** after each answer, a **checks** panel (ERC, DRC, built-in rules, optional parts verification) whose findings link to the parts they name, a file **editor** and a **git** panel (status, diff, stage, commit, branches).
- **Settings**: API keys go to the OS keychain (if `keyring` works) or `~/.config/traceforge/.env` with mode 600, and are never sent back to the page. Provider, approval level, fab profile, dark and light themes.

The server listens on `127.0.0.1` only, on a random port, and every request needs the random token from the launch URL. File access is confined to the project folder.

Build the app yourself:

```bash
pip install -e ".[desktop]" pyinstaller     # from a source checkout
pyinstaller packaging/traceforge-app.spec --noconfirm     # dist/Traceforge/ (dist/Traceforge.app on macOS)
```

`.github/workflows/app.yml` does this for macOS (arm64 and Intel), Windows and Linux on version tags and manual runs, and attaches the archives to the release.

## How it works

```
  you ──► CLI / MCP / LangChain ──► agent loop (Claude, streaming, adaptive thinking)
                                        │ tool calls
              ┌─────────────────────────┼──────────────────────────────┐
         files & shell           KiCad tools                    design compiler
     (sandboxed to the       ERC · DRC · netlist ·        spec ─► schematic + board
      workspace, approvals)   place · track · via ·        ─► placement ─► router
                              pour · fields · exports           (+ ground plane)
```

- **Agent loop** ([`agent.py`](src/traceforge/agent.py)): Claude via the official Anthropic SDK, with streaming, adaptive thinking, prompt caching, eager tool-input streaming with client-side argument validation, server-side refusal fallback, and append-only history so conversations can be resumed and interrupted safely.
- **Tools** ([`tools/`](src/traceforge/tools)): file and shell tools confined to the workspace (no paths outside it, secrets are never readable), plus about 20 KiCad tools. Modes restrict what is available: `plan`, `ask` and review sessions are read-only.
- **Approvals** ([`approval.py`](src/traceforge/approval.py)): `ask` asks before every write and command; `auto` lets file edits and simple commands run and asks for anything chained or destructive; `yolo` runs everything except destructive commands; `read-only` refuses changes.
- **Design compiler** ([`design/`](src/traceforge/design)): copies symbols and footprints from your installed KiCad libraries, so the output is exactly what KiCad's own editors would produce. It writes the file format of the installed KiCad (or `--kicad-version 7|8|9`; KiCad 10 opens the 9 format) and reads files from KiCad 6 to 10. Output is deterministic (stable UUIDs), so regenerating gives clean diffs.
- **Placement and routing** ([`kicad/route.py`](src/traceforge/kicad/route.py)): placement driven by connectivity (edge-mount connectors seated on the outline with their opening outward, parts near what they connect to, mounting-hole keepouts, parts on both sides), then a grid A* router that works on any layer count (2 to 8): negotiated-congestion rip-up, a rip-up-and-reroute repair pass for nets that still fail, per-net-class widths, clearances and vias, fan-out of fine-pitch packages, coupled differential pairs with length tuning and length-matching groups. Ground and power planes are poured on inner or outer layers and connected through vias. KiCad's own connectivity engine confirms the result when it is available.
- **Hosted mode** ([`remote/`](src/traceforge/remote)): `traceforge serve` runs the model side on a server holding the API key, with per-user API keys and monthly token limits. Clients (`traceforge login`, `--server`) run every tool locally, so design files never leave the user's machine except as tool results the model reads. The protocol is documented in [`remote/__init__.py`](src/traceforge/remote/__init__.py).

More detail: [docs/architecture.md](docs/architecture.md).

## Configuration

`~/.config/traceforge/config.yaml` (user) and `.traceforge/config.yaml` (project):

```yaml
# model: best               # optional: a model id or tier (fast | balanced | best); pins the main work
# effort: high               # optional: low | medium | high | xhigh | max; pins the main work
routing: true              # pick a model and effort per kind of work (see below)
routes: {}                 # per-role overrides, e.g. {main: best, explore: gpt-5.4-mini}
approval: ask              # ask | auto | yolo | read-only
fab: jlcpcb                # jlcpcb | pcbway | oshpark | generic
fallbacks: true            # server-side refusal fallback (first-party API only)
```

**Model routing.** Different work goes to different models, so a session is not run entirely on the most expensive one. The main agent works on the balanced tier at medium effort (`gpt-6.1-sol` with an OpenAI key, `gemini-3-flash-preview` with a Gemini key (`GEMINI_API_KEY` or `GOOGLE_API_KEY`, needs `pip install "traceforge-pcb[gemini]"`), Claude Sonnet with an Anthropic key). Read-only subagents and history summaries use the fast tier (`gpt-5.4-mini` / `gemini-3.1-flash-lite-preview` / Claude Haiku), and plans use the best tier at high effort. When several tool calls in a row fail, the rest of that task moves to the best tier, then the next task starts on balanced again. `traceforge models` shows the current routing.

**Auto approval** (`--approve auto`, or `A` at an approval prompt) runs file edits and shell commands without asking. It still asks before destructive commands (`rm -rf`, `git reset --hard`, ...), recursive deletes, and writes to files that run code or configure tools (CI, hooks, shell scripts, `pyproject.toml`, ...). `/approve shell simple` makes it stricter again.

Environment overrides: `TRACEFORGE_MODEL`, `TRACEFORGE_EFFORT`, `TRACEFORGE_ROUTING`, `TRACEFORGE_APPROVAL`, `TRACEFORGE_FAB`, `TRACEFORGE_SERVER`, `TRACEFORGE_SERVER_KEY`, `TRACEFORGE_KICAD_CLI`, `TRACEFORGE_KICAD_PYTHON`, and KiCad's own `KICAD9_SYMBOL_DIR` / `KICAD9_FOOTPRINT_DIR` (or the 8/7 variants). Put project-specific instructions for the agent (requirements, constraints, part preferences) in `TRACEFORGE.md` at the project root; `traceforge init` creates a template.

## KiCad versions

| | KiCad 8 / 9 / 10 | KiCad 7 |
|---|---|---|
| Open generated projects | yes | yes |
| ERC | `kicad-cli sch erc` | not available; built-in schematic checks only |
| DRC | `kicad-cli pcb drc` with parity and zone refill | KiCad DRC through its Python module (`pcbnew`), when installed |
| Gerbers, drill, netlist, SVG | yes | yes |
| BOM | `kicad-cli` | built-in BOM writer |
| 3D render (`models3d render`) | `kicad-cli pcb render` | not available (the command does not exist); reported, nothing is faked |

The test suite passes on KiCad 7 (local) and on 8, 9 and 10 (official Docker images). Files from KiCad 6 to 10 are read (KiCad 10 name-only nets, `.kicad_symdir` libraries, variants, component classes, rule areas). `traceforge build --kicad-version 7|8|9|auto` (or `kicad_version:` in the spec, or `TRACEFORGE_KICAD_VERSION`) picks the format written; the default is the installed KiCad's. Altium Designer and CircuitMaker projects (`.PrjPcb`, `.SchDoc`, `.PcbDoc`) are read directly (`pip install 'traceforge-pcb[altium]'`): `traceforge altium info|pin|netlist|bom|convert`, plus agent tools for parts, pins, nets, BOM and review. See [docs/altium.md](docs/altium.md).

## Firmware

`traceforge firmware` turns the schematic into firmware that matches the board (details in [docs/firmware.md](docs/firmware.md)):

```bash
traceforge firmware pins board.kicad_sch --style c --out firmware   # pins.h from the nets (also cpp, rust)
traceforge firmware scaffold design.yaml --target platformio --driver BME280
traceforge firmware driver SHT31 --out drivers                     # init/read C code from the register table
traceforge firmware build firmware                                  # real compile, parsed errors, flash/RAM size
traceforge firmware tools                                           # arduino-cli, platformio, idf.py, avr-gcc, arm-none-eabi-gcc
```

Targets: Arduino, PlatformIO, ESP-IDF, bare-metal STM32F1 (CMake/Make, GPIO only) and AVR (avr-gcc Makefile). Flashing is never run without `-y` or the agent's approval prompt. The agent has the same functions as tools (`firmware_pins`, `firmware_scaffold`, `firmware_driver`, `firmware_toolchain`, `firmware_build`, `firmware_flash`) and a `firmware` skill.

## Limitations

Be aware of these before you trust a board to it:

- **Routing** is a grid router. Two-layer boards of connectors, passives and small ICs route to zero open nets (the 2-layer examples all do, with 0 DRC errors). Multi-layer boards use inner signal layers, planes, fan-out, coupled pairs and length groups, but dense ones can stop short: the 4-layer RP2040, the 6-layer carrier and the 4-layer USB hub were last routed to 3, 4 and 1 open connections, and those examples carry a `.ci-skip` marker for that reason; the 8-layer BGA example (0.8 mm pitch, through vias only) leaves many nets open until via-in-pad is allowed (`--via-in-pad`, an extra-cost fab option). Through vias only, no blind or buried vias or microvias; impedance is from closed-form formulas, not a field solver; length matching covers pairs and groups, not DDR timing budgets. Read the route report (`failure_reasons`) and `traceforge check` before trusting a board; see [docs/multilayer-results.md](docs/multilayer-results.md).
- **Placement** is a greedy heuristic. Edge-mount connectors (USB, barrel, audio, RJ45, coax, card sockets) are rotated and seated with their opening on the board edge, using the "PCB Edge" line in KiCad's footprints; other connectors are only pulled towards an edge. Pin parts that an enclosure constrains (buttons, LEDs behind light pipes, mounting features) with `at:` and `rotation:` in the spec, or move them with `kicad_place`.
- **Firmware** pin tables exist for the ATtiny85, the ESP32-S3-WROOM-1 module and STM32F103 pin names only; other MCUs need a table entry in `firmware/mcus.py`. Drivers are starting points written from datasheets, not tested on hardware.
- **Generated schematics** are grouped by function with wires, power symbols and labelled boxes, and split into hierarchical sheets above 40 parts (see [docs/schematics.md](docs/schematics.md)). The generator's own connectivity verifier and `kicad-cli sch export netlist` agree with the spec and the examples pass KiCad ERC. The layout checker still reports a few overlapping labels next to dense ICs (net labels on a power symbol's value text, repeated labels of one net), documented there; nothing connects wrongly, but expect to nudge some labels and parts by hand.
- **Board side**: parts can go on the bottom (`side: bottom`, `decoupling: opposite`). The bottom-side placement-file (CPL) rotation convention has not been checked against a fab's own tool.
- **Fab limits**: the JLCPCB 4, 6 and 8 layer stackups and capability limits in the fab profiles come from published pages and have not been verified against an order.
- **Platforms**: tested on Linux (KiCad 7 locally, KiCad 8, 9 and 10 in Docker). macOS and Windows installs, Python 3.14, the desktop app's native window on a GUI machine and the KiCad plugin inside a live KiCad window have not been run. CI workflows exist for them but have not produced results.
- **Benchmark**: `traceforge bench` and its scorer are open and reproducible ([benchmarks/SCORING.md](benchmarks/SCORING.md)); no head-to-head scores against other tools are published.
- **Simulation** uses generic models for parts without a SPICE model (LEDs, diodes, op-amps, LDOs, MOSFETs, BJTs); real behaviour differs. MCUs, connectors and unmodelled ICs are skipped. LTspice files are generated but not run or opened by Traceforge.
- **The AI is not a substitute for review.** Traceforge cites evidence and runs every check it can, but a human should review any board before money is spent on fabrication or assembly.

## Development

```bash
git clone https://github.com/ashutosh-rath02/traceforge && cd traceforge
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
pytest              # KiCad-dependent tests skip when KiCad is not installed (full run: about 15 minutes)
ruff check . && ruff format --check .
scripts/ci-local.sh 9.0     # the same suite inside the official KiCad 9 image (needs Docker; also 8.0, 10.0)
```

The agent tests use a scripted fake model client, so the test suite needs no API key. See [CONTRIBUTING.md](CONTRIBUTING.md) and the [documentation index](docs/index.md).

## License

MIT. See [LICENSE](LICENSE). KiCad symbol and footprint libraries used at run time are CC-BY-SA 4.0 with KiCad's library exception, which allows using them in your designs.

## Live part data

`traceforge parts 10k 0603 1% --basic` searches the JLCPCB/LCSC catalogue, `traceforge parts --lookup C2286`
shows one part, and `traceforge parts --check` (also run by `traceforge check` and the `parts.catalog`
validate check) verifies every LCSC/MPN in a project: the part exists, its package fits the footprint
(chip size, SOIC body width, pin count, pitch, SMD/THT), value and MPN agree, stock and basic/extended.
The agent gets the same through `part_lookup`, `part_search`, `parts_check`, `datasheet_fetch`
(`pip install 'traceforge-pcb[datasheets]'`), `web_search`, `web_fetch` and `reference_project_search`.
Results are cached in `~/.cache/traceforge/parts`; `TRACEFORGE_OFFLINE=1` uses the cache only.
Optional keys: `NEXAR_CLIENT_ID/SECRET`, `DIGIKEY_CLIENT_ID/SECRET`, `MOUSER_API_KEY` (parts);
`TAVILY_API_KEY`, `BRAVE_API_KEY`, `PERPLEXITY_API_KEY`, or `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` (web search).

### Sourcing and cost

```
traceforge parts bom examples/sourcing_demo/bom.csv --out out/    # priced roll-up at 1/10/100/1000 boards + JLCPCB, PCBWay, generic, Excel CSVs
traceforge parts brief STM32G431CBU6 --country IN --target-qty 1000 --out brief.md
traceforge parts alternates C25804                                # alternates with reasons; suggestions only
```

`bom` accepts a `design.yaml`, a KiCad schematic or project folder, or a BOM CSV; `--board x.kicad_pcb` adds a JLCPCB placement (CPL) file.
`brief` writes Markdown and JSON: suppliers with citations, an HS code with its rationale, authorised distributors,
single-source risk, volume price bands (extrapolation assumptions printed) and a landed-cost estimate with the arithmetic.
Agent tools: `sourcing_compare`, `parts_alternates`, `sourcing_brief`, `bom_cost`.

Status, stated plainly. JLCPCB, LCSC and jlcsearch are exercised live. DigiKey (Product Information v4), Mouser (Search v1)
and Nexar were written from the vendors' documentation and are tested only against hand-written fixtures in
`tests/fixtures/parts/` (labelled as such); they have not run against real accounts. Exchange rates come from
frankfurter.app, cached; offline, the last cached table, then a built-in approximate table, and the output names which.
HS codes (`src/traceforge/parts/data/hs_codes.yaml`) and duty rates (`duty_rates.yaml`, India BCD/SWS/IGST example) are
editable data and a guide only: the India rates are marked unverified, other countries have no row and get no duty estimate.
Confirm both with your customs broker. `--hs-table` / `--duty-table` load your own files.

Terminal UI, Zed/ACP, branches, undo and next steps: see [docs/terminal-and-editors.md](docs/terminal-and-editors.md).
