Skip to content
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
a9cbef7
Add native schematic and symbol editors with part metadata and fitted…
David-Bascom05 Nov 26, 2026
8458c19
Integrate current schematic backend and retain both regression suites
David-Bascom05 Nov 26, 2026
f5b1086
Merge remote-tracking branch 'origin/feature/schematic-backend' into …
David-Bascom05 Nov 26, 2026
eb3453f
Use the WASI-safe scratch directory and process ID for PDF tests
David-Bascom05 Nov 26, 2026
6b6b201
Insert roles before all local symbols and keep empty footprints grouped
David-Bascom05 Nov 26, 2026
3aec731
Improve schematic fields, label drawings and power symbols
David-Bascom05 Nov 26, 2026
b36b571
Merge branch 'feature/schematic-backend' of https://github.com/David-…
David-Bascom05 Nov 26, 2026
73c5ac6
Move, rotate and mirror the gate that owns the displayed pin
David-Bascom05 Nov 26, 2026
5f4a913
Add schematic pin inspection, signal overlays and grid-aware drawing …
David-Bascom05 Nov 26, 2026
f8e55d6
Use the bundled font for the schematic readability warning
David-Bascom05 Nov 26, 2026
bc28101
Merge remote-tracking branch 'origin/main' into HEAD
David-Bascom05 Nov 26, 2026
8b89433
Toggle schematic no-connect markers on the selected pin
David-Bascom05 Nov 26, 2026
da01a8e
Show pin checklist on selection and highlight the connected rail
David-Bascom05 Nov 26, 2026
e138e62
Make pin role checklists editable in the properties dock
David-Bascom05 Nov 26, 2026
8a53245
Design datasheet-aware pin requirements and alternate functions
David-Bascom05 Nov 26, 2026
cd35c4d
Edit pin names, directions and symbol reference prefixes
David-Bascom05 Nov 26, 2026
dcd6bdf
Check pin voltage wants against connected supply guarantees
David-Bascom05 Nov 26, 2026
31601bf
Show passing and out-of-range supply checks in both editors
David-Bascom05 Nov 26, 2026
e9d1f7c
Assign application-specific connector roles on schematic placements
David-Bascom05 Nov 26, 2026
495e509
Align schematic component controls in the Properties inspector
David-Bascom05 Nov 26, 2026
4c27e95
Check pin-to-pin wants through typed components and named terminal paths
David-Bascom05 Nov 26, 2026
3ca2466
Allow connection wants to refer to pins resolved after placement
David-Bascom05 Nov 26, 2026
59a35f9
Register schematic role editing in language coverage
David-Bascom05 Nov 26, 2026
18a3f6f
Support nested electronics libraries and occurrence-aware schematic c…
David-Bascom05 Nov 26, 2026
0c28ffe
Add library hierarchy, block editing and project review to schematic …
David-Bascom05 Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions docs/schematic.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,24 @@ MCP `plan_bypass` takes the file, qualified consumer and return pin, symbol and
The [Lean model](../research/forge-lang/lean/ForgeLang/Schematic.lean) proves nominal role admissibility, preservation of wiring by role confirmation, and invariant reachability when a wire is reversed. Grammar witnesses use the shared .fg parser model. The Rust tests compare net partitions against an independent transitive-closure oracle and exercise hierarchy, gate placement and role refusals. The MCP integration test plans, commits, rejects a bad edit, undoes, and invalidates a changed library. The [coverage ledger](../research/forge-lang/lean/COVERAGE.md) identifies the remaining Rust-to-model proof gaps.

The session cache recognizes a change confined to the literal coordinates of a placement. It updates pin positions and print-bounds findings on each affected sheet occurrence, preserves confirmed links and electrical partitions, and adjusts source locations. Changes to wiring, parameters or imported symbols use a fresh compilation. The regression suite compares cached results, source locations and SVG against fresh compilation across repeated sheets and invalid edits. The [latency probe](../research/electronics/probes/README.md#native-schematic-response-time) exercises this path through MCP.

## Editing in ForgeCAD

Choose **File → New Schematic** or **File → New Symbol Library**. Each opens a document tab. Save both files in the project before linking the library. In the schematic, **Link Library** takes its relative filename and a local name. **Place Symbol** shows the definitions in the linked library. Clicking a library in the document browser opens its symbol editor. The [sensor interface](../examples/electronics/analog/sensor-interface.fg) and its [library](../examples/electronics/analog/analog-symbols.fg) are a working pair.

- Use **Wire** to pick the first pin, any bends, and the destination. Finish on an existing wire to branch it. **Junction** splits an existing segment. Moving a connected component keeps its wires attached. A plain crossing leaves the nets independent.
- **Assign Role** records a typed provider and consumer, with optional return pins and a preferred separation. Select a pin to inspect its declared roles and candidate providers. **Inspect → Electrical Checks** shows electrical and readability findings.
- In a library, select a symbol, place its pins and draw its outline. Select a pin to set its number, unit, orientation, electrical kind, wants and gives. Select a graphic to edit its coordinates. The library and all its instances share the same geometry.
- When a whole sheet is fitted, fine pin labels appear as you zoom in. Hover over an endpoint to identify it at any scale. The scroll wheel zooms around the pointer, middle drag pans, and **View → Fit All** frames the drawing. Hover over a ribbon tool to see its shortcut. Escape cancels the current tool. Source edits use the document's undo and redo history.

### Purchasing data and datasheets

Symbols accept a map of custom string fields and a datasheet reference. Placements can override individual fields and the datasheet. Field names are Forge identifiers. For example, a library can define `fields: {MPN: "TLV9001IDBVR", Manufacturer: "Texas Instruments"}`. A placement can add `fields: {Supplier: "Stockroom"}` while retaining both library fields. Value and footprint are placement properties.

**Attach PDF** on a saved symbol or placement stores the PDF bytes in the document’s `datasheets/` folder under a SHA-256 filename and records the relative path. Importing identical bytes reuses the file. A datasheet URL is stored as text. Share the project directory, including its libraries and attachments.

**Inspect → Bill of Materials** groups fitted physical occurrences by effective specification and copies CSV with the custom fields as columns. Multiple gates count once per component, and repeated sheets contribute separate occurrence paths. `populated: false` and `in_bom: false` independently exclude placements. The same data is available through the MCP schematic queries `bom` and `bom-csv`, or from the CLI.

```sh
forgecad schematic examples/electronics/analog/sensor-interface.fg bom-csv -o sensor-bom.csv
```
32 changes: 32 additions & 0 deletions examples/electronics/analog/analog-symbols.fg
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
symbol_library

rail = role(kind: "power", voltage_mv: 3300, key: "analog.supply3v3")
bypass = role(kind: "bypass", prefer: 3mm, key: "analog.local_bypass")

Amplifier = symbol(
datasheet: "https://www.ti.com/lit/ds/symlink/tlv9001.pdf",
fields: {Manufacturer: "Texas Instruments", MPN: "TLV9001IDBVR"},
pins: {
INP: pin(number: "3", kind: "input", at: (-7, 3)),
INM: pin(number: "4", kind: "input", at: (-7, -3)),
OUT: pin(number: "1", kind: "output", at: (9, 0)),
VDD: pin(number: "5", kind: "power_in", at: (0, 8), wants: [rail, bypass]),
VSS: pin(number: "2", kind: "passive", at: (0, -8))
},
graphics: [
polyline(points: [(-4, 6), (7, 0), (-4, -6), (-4, 6)]),
text(at: (-3.2, 2.5), value: "+"), text(at: (-3.2, -3.5), value: "-"),
line(from: (-7, 3), to: (-4, 3)), line(from: (-7, -3), to: (-4, -3)),
line(from: (7, 0), to: (9, 0)), line(from: (0, 8), to: (0, 3.8)),
line(from: (0, -8), to: (0, -3.8))
]
)
Resistor = symbol(pins: {
A: pin(number: "1", kind: "passive", at: (-6, 0)),
B: pin(number: "2", kind: "passive", at: (6, 0))
}, graphics: [rect(from: (-3,-1), to: (3,1)), line(from: (-6,0),to:(-3,0)), line(from: (3,0),to:(6,0))])
Capacitor = symbol(pins: {
P: pin(number: "1", kind: "passive", at: (0, 4), gives: [bypass]),
N: pin(number: "2", kind: "passive", at: (0, -4))
}, graphics: [line(from:(0,4),to:(0,0.55)),line(from:(-2.5,0.55),to:(2.5,0.55)),
line(from:(-2.5,-0.55),to:(2.5,-0.55)),line(from:(0,-0.55),to:(0,-4))])
36 changes: 36 additions & 0 deletions examples/electronics/analog/sensor-interface.fg
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
schematic

analog = library(file: "analog-symbols.fg")
main = sheet(title: "Sensor interface")

R1 = place(sheet: main, symbol: analog.Resistor, value: "10k", footprint: "R_0603", at: (-27, 3))
C1 = place(sheet: main, symbol: analog.Capacitor, value: "10 nF", footprint: "C_0603", at: (-15, -7))
U1 = place(sheet: main, symbol: analog.Amplifier, value: "TLV9001", footprint: "SOT-23-5", at: (4, 0))
C2 = place(sheet: main, symbol: analog.Capacitor, value: "100 nF", footprint: "C_0603", at: (23, 18))

input = port(sheet: main, at: (-42,3))
output = port(sheet: main, at: (38,0))
supply = port(sheet: main, at: (-7,22))
ground = port(sheet: main, at: (4,-21))
filter = junction(sheet: main, at: (-15,3))
feedback = junction(sheet: main, at: (19,0))
vdd = junction(sheet: main, at: (4,22))
gnd = junction(sheet: main, at: (4,-15))

w1 = wire(sheet: main, from: input, to: R1.A)
w2 = wire(sheet: main, from: R1.B, to: filter)
w3 = wire(sheet: main, from: filter, to: U1.INP)
w4 = wire(sheet: main, from: filter, to: C1.P)
w5 = wire(sheet: main, from: C1.N, to: gnd, via: [(-15,-15)])
w6 = wire(sheet: main, from: U1.OUT, to: feedback)
w7 = wire(sheet: main, from: feedback, to: output)
w8 = wire(sheet: main, from: feedback, to: U1.INM, via: [(19,-11),(-5,-11),(-5,-3)])
w9 = wire(sheet: main, from: U1.VDD, to: vdd)
w10 = wire(sheet: main, from: supply, to: vdd)
w11 = wire(sheet: main, from: vdd, to: C2.P)
w12 = wire(sheet: main, from: U1.VSS, to: gnd)
w13 = wire(sheet: main, from: gnd, to: ground)
pwr = label(sheet: main, on: vdd, value: "+3V3", at: (6,23))
ret = label(sheet: main, on: gnd, value: "GND", at: (6,-17))
cap_ret = label(sheet: main, on: C2.N, value: "GND", at: (24,13))
local_cap = fulfill(sheet: main, want: U1.VDD, give: C2.P, role: analog.bypass, return_from: C2.N, return_to: U1.VSS)
8 changes: 4 additions & 4 deletions interface/forge-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -784,19 +784,19 @@ fn command(cmd: &str, argv: &[String]) -> ExitCode {
let r = fg::Session::new(None, true).run(cmd, &a, &forge_agent::json::Json::Null);
let mut text = if json { r.json.to_string() } else { r.text };
if cmd == "schematic"
&& matches!(a.words.first().map(String::as_str), Some("svg" | "symbol-svg"))
&& let Some(svg) = r.json.get("result").and_then(forge_agent::json::Json::str)
&& matches!(a.words.first().map(String::as_str), Some("svg" | "symbol-svg" | "bom-csv"))
&& let Some(content) = r.json.get("result").and_then(forge_agent::json::Json::str)
{
if let Some(path) = out.as_deref() {
if let Err(e) = std::fs::write(path, svg) {
if let Err(e) = std::fs::write(path, content) {
eprintln!("writing {path}: {e}");
return ExitCode::FAILURE;
}
if !json {
text = format!("wrote {path}");
}
} else if !json {
text = svg.to_owned();
text = content.to_owned();
}
}
if let Some(png) = &r.png {
Expand Down
4 changes: 2 additions & 2 deletions interface/forge-cli/src/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,13 @@ const TOOLS: [Tool; 22] = [
),
(
"schematic",
"Inspect a native schematic or symbol library. Typed roles, pin candidates, confirmed links, net partitions, sheet geometry, ERC and rooted wiring. Use edit for checked source changes.",
"Inspect a native schematic or symbol library. Typed roles, pin candidates, confirmed links, net partitions, sheet geometry, ERC, rooted wiring and the fitted BOM. Use edit for checked source changes.",
1,
&[
("file", "path to .fg"),
(
"sel",
"summary, symbols, symbol ID, sheet PATH, erc, nets, links, pin PATH or tree PATH",
"summary, symbols, symbol ID, sheet PATH, erc, nets, links, pin PATH, tree PATH, bom or bom-csv",
),
],
),
Expand Down
110 changes: 110 additions & 0 deletions interface/forge-lang/src/schematic/bom.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
//! One purchasing line per distinct part specification, with all its fitted occurrences.
use super::*;
use forge_agent::json::Json;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct PartSpec {
pub symbol: String,
pub value: String,
pub footprint: Option<String>,
pub datasheet: Option<String>,
pub fields: Map<String, String>,
}
#[derive(Debug)]
pub struct BomLine {
pub part: PartSpec,
pub references: Vec<String>,
}
pub(super) fn field_json(fields: &Map<String, String>) -> Json {
Json::Obj(
fields
.iter()
.map(|(k, v)| (k.clone(), v.clone().into()))
.collect(),
)
}
impl BomLine {
pub fn json(&self) -> Json {
let p = &self.part;
Json::obj(vec![
("symbol", p.symbol.clone().into()),
("value", p.value.clone().into()),
("footprint", p.footprint.clone().map_or(Json::Null, Into::into)),
("datasheet", p.datasheet.clone().map_or(Json::Null, Into::into)),
("fields", field_json(&p.fields)),
("quantity", self.references.len().into()),
(
"references",
Json::Arr(self.references.iter().cloned().map(Into::into).collect()),
),
])
}
}
pub fn bom(doc: &Document, c: &Circuit) -> Vec<BomLine> {
let mut lines: Map<PartSpec, Vec<String>> = Map::new();
for (path, sheet) in &c.occurrences {
for row in doc.rows.iter().filter(|r| r.sheet == *sheet) {
if let Item::Place {
symbol,
value,
footprint,
fields,
datasheet,
populated: true,
in_bom: true,
..
} = &row.item
{
let lib = &doc.symbols[symbol];
let mut merged = lib.fields.clone();
merged.extend(fields.clone());
let part = PartSpec {
symbol: symbol.clone(),
value: value.clone(),
footprint: footprint.clone(),
fields: merged,
datasheet: datasheet.clone().or_else(|| lib.datasheet.clone()),
};
lines.entry(part).or_default().push(format!("{path}/{}", row.id));
}
}
}
lines
.into_iter()
.map(|(part, references)| BomLine { part, references })
.collect()
}
pub fn bom_csv(lines: &[BomLine]) -> String {
let keys: Set<_> = lines.iter().flat_map(|l| l.part.fields.keys()).collect();
let csv = |v: Vec<String>| {
v.into_iter()
.map(|x| format!("\"{}\"", x.replace('"', "\"\"")))
.collect::<Vec<_>>()
.join(",")
};
let mut rows = vec![csv([
"Quantity",
"References",
"Symbol",
"Value",
"Footprint",
"Datasheet",
]
.map(str::to_owned)
.into_iter()
.chain(keys.iter().map(|s| (*s).clone()))
.collect())];
for l in lines {
let p = &l.part;
let mut row = vec![
l.references.len().to_string(),
l.references.join(" "),
p.symbol.clone(),
p.value.clone(),
p.footprint.clone().unwrap_or_default(),
p.datasheet.clone().unwrap_or_default(),
];
row.extend(keys.iter().map(|k| p.fields.get(*k).cloned().unwrap_or_default()));
rows.push(csv(row));
}
rows.join("\r\n") + "\r\n"
}
86 changes: 86 additions & 0 deletions interface/forge-lang/src/schematic/datasheet.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
//! Store an explicitly imported PDF beside its owning .fg. A content address makes shared
//! datasheets portable and a second import idempotent on native and browser filesystems.
use forge_dirs::fs;
use std::{
io::{self, Write},
path::Path,
};
pub const MAX_PDF_BYTES: usize = 32 * 1024 * 1024;
pub fn store_pdf(owner: &Path, bytes: &[u8]) -> io::Result<String> {
if !bytes.starts_with(b"%PDF-") || bytes.len() > MAX_PDF_BYTES {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Choose a PDF of at most 32 MiB",
));
}
let parent = owner
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
let root = fs::canonicalize(parent)?;
let folder = root.join("datasheets");
match fs::create_dir(&folder) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(e),
}
if fs::canonicalize(&folder)? != folder {
return Err(io::Error::other(
"The datasheets folder must be inside the document folder",
));
}
let id = forge_git::HashKind::Sha256.of(bytes);
let name = format!("{id}.pdf");
let dest = folder.join(&name);
match fs::OpenOptions::new().write(true).create_new(true).open(&dest) {
Ok(mut f) => {
if let Err(e) = f.write_all(bytes) {
drop(f);
let _ = fs::remove_file(&dest);
return Err(e);
}
}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
if fs::canonicalize(&dest)? != dest
|| !fs::symlink_metadata(&dest)?.is_file()
|| fs::metadata(&dest)?.len() != bytes.len() as u64
|| fs::read(&dest)? != bytes
{
return Err(io::Error::other(
"Different content already occupies the datasheet path",
));
}
}
Err(e) => return Err(e),
}
Ok(format!("datasheets/{name}"))
}

/// Preserve locally imported attachments when a document is saved in another folder.
pub fn copy_managed(old: &Path, new: &Path, link: &str) -> io::Result<()> {
let Some(hash) = link
.strip_prefix("datasheets/")
.and_then(|name| name.strip_suffix(".pdf"))
else {
return Ok(());
};
if old.parent() == new.parent() || hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
return Ok(());
}
let base = old
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
let path = base.join(link);
if fs::canonicalize(&path)? != fs::canonicalize(base)?.join(link) {
return Err(io::Error::other(
"The datasheet must be inside the document folder",
));
}
let bytes = crate::deps::read_plain(&path, MAX_PDF_BYTES as u64)
.map_err(|_| io::Error::other("Cannot read the original datasheet"))?;
if forge_git::HashKind::Sha256.of(&bytes).to_string() != hash {
return Err(io::Error::other("The original datasheet has changed"));
}
store_pdf(new, &bytes).map(|_| ())
}
Loading
Loading