Draft: revisioned schematic authoring with exact-source native inspection #1
The current viewer can inspect existing schematics but cannot create a revisioned circuit. This draft adds a separate development authoring mode: exact symbol registration, placement/movement, pin connections, labels and undo through shared UI/CLI transactions, with atomic snapshots and SSE paint acknowledgements.
The TMF8829 decoupling slice exposed two useful failures: embedded library unit names were not migrated with their exported identity, and a Manhattan wire passed through an unintended capacitor pin. The exporter now preserves consistent unit names, and structured contact diagnostics detect unintended pin/endpoint/overlap contacts. Exact-revision native SVG inspection rejects stale or hash-mismatched evidence and displays the actual ERC count.
Validation: seven Rust tests pass. KiCad 10.0.2 service loads the revision-14 six-component export and produces SVG/ERC. Its 42 ERC findings remain open; this is an unfinished circuit, not an ERC pass or desktop/native parity claim. Original manufacturer assets remain unchanged. Live authoring and subsequent native inspection are recorded in the Depth Lab project.
This is deliberately a draft: complete settings/lifecycle integration, wire waypoints and body clearance, native netlist equivalence, richer UI editing, and fast-preview pin/group text remain open. Source guide: docs/AUTHORING-DEVELOPMENT.md. No release, fleet installation or default-branch merge is requested by this draft.
Diff Skip to comments (3)
@@ -1,25 +1,28 @@⋯ 17 unchanged lines ⋯ ureq = "2" roxmltree = "0.20" cfb = "0.10"+uuid = { version = "1", features = ["v4", "v5"] }+sha2 = "0.10" [profile.release] opt-level = "z" lto = true strip = true+@@ -1,1034 +1,1133 @@⋯ 18 unchanged lines ⋯ "roxmltree", "serde", "serde_json",+ "sha2", "tiny_http", "ureq",+ "uuid", ] [[package]]⋯ 74 unchanged lines ⋯ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]++[[package]] name = "bumpalo" version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index"⋯ 85 unchanged lines ⋯ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" [[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]] name = "crc32fast" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index"⋯ 3 unchanged lines ⋯ ] [[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]++[[package]] name = "displaydoc" version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index"⋯ 60 unchanged lines ⋯ ] [[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]] name = "getrandom" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index"⋯ 5 unchanged lines ⋯ ] [[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+]++[[package]] name = "heck" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index"⋯ 217 unchanged lines ⋯ ] [[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]] name = "regex" version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index"⋯ 30 unchanged lines ⋯ dependencies = [ "cc", "cfg-if",- "getrandom",+ "getrandom 0.2.17", "libc", "untrusted", "windows-sys 0.52.0",⋯ 90 unchanged lines ⋯ ] [[package]]+name = "sha1_smol"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"++[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]++[[package]] name = "shlex" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index"⋯ 80 unchanged lines ⋯ ] [[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"++[[package]] name = "unicode-ident" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index"⋯ 51 unchanged lines ⋯ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf3923a6f5c4c6382e0b653c4117f48d631ea17f38ed86e2a828e6f7412f5239" dependencies = [+ "getrandom 0.4.3", "js-sys",+ "sha1_smol", "wasm-bindgen", ] [[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index"⋯ 244 unchanged lines ⋯ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"+@@ -1,91 +1,110 @@⋯ 88 unchanged lines ⋯ See also: **adom-2dboard** — the same idea for `.kicad_pcb`, with net and trace highlighting.++## Development: revisioned schematic authoring++The `feature/revisioned-schematic-authoring` branch adds a separate single-sheet+`author` mode. It preserves the import viewer and stores a lossless document with+registered exact symbol sources, stable reference/pin endpoints, edit history,+revision checks, retry receipts and atomic snapshots. UI and CLI edits share a+transaction endpoint; SSE publishes saved state and the browser acknowledges paint.++```bash+adom-schematic --ai-thread 'Example circuit' author --dir ./circuit --name 'Example circuit'+adom-schematic --ai-thread 'Example circuit' edit --port <returned-port> --transaction edit.json+adom-schematic state --port <returned-port>+```++See [authoring development guide](docs/AUTHORING-DEVELOPMENT.md) for operations,+visible verification and limitations. This branch is a development slice, not a+released general schematic editor or a claim of native CAD parity.+@@ -1,91 +1,103 @@⋯ 88 unchanged lines ⋯ - KiCad today; Altium and Fusion exports are the planned next step. - Sibling app: **adom-2dboard** (`.kicad_pcb`, with net/trace highlighting).++## Development authoring branch++The separate `author` mode is documented in [AUTHORING-DEVELOPMENT.md](docs/AUTHORING-DEVELOPMENT.md).+Read it before authoring: this is a single-sheet development slice with typed+revisioned transactions, not a released complete editor. Verify saved revision,+SSE paint acknowledgement and the actual work-pane view. Check `contactIssues` and+run native KiCad loading/ERC against the exact exported bytes. Native inspection+requires matching source/render hashes; never present a stale native render as the+current design. A successful parser test cannot detect all native syntax errors.+When renaming embedded library identities, rename unit prefixes consistently too.+@@ -1,174 +1,196 @@⋯ 4 unchanged lines ⋯ //! a per-component hotspot layer so hovering a symbol shows what it is plus live //! stock & price. Meant to be embedded as a live schematic "view" in any app. +mod author;+mod author_server; mod sexpr; mod sch_parse; mod kicad_sch;⋯ 10 unchanged lines ⋯ #[derive(Parser)] #[command(name = "adom-schematic", version, about = "Interactive schematic viewer (.kicad_sch): KiCad-native render + per-component hover with stock & price")]-struct Cli { #[command(subcommand)] command: Cmd }+struct Cli { #[arg(long, global=true)] ai_thread: Option<String>, #[command(subcommand)] command: Cmd } #[derive(Subcommand)] enum Cmd {+ /// Start or reuse an isolated revisioned schematic authoring project.+ Author { #[arg(long)] dir: PathBuf, #[arg(long, default_value="Schematic")] name: String, #[arg(long, default_value_t=0)] port:u16, #[arg(long, default_value_t=24.)] ttl_hours:f64 },+ /// Apply a typed authoring transaction from JSON using the same route as the UI.+ Edit { #[arg(long)] port:u16, #[arg(long)] transaction:PathBuf },+ /// Read the authoring document revision and UI evidence without a mutation.+ State { #[arg(long)] port:u16 }, /// Render a `.kicad_sch` to a composed interactive SVG (+ optional -meta.json). Render { #[arg(long)] file: PathBuf, #[arg(long)] out: PathBuf, #[arg(long)] meta: bool }, /// Export a self-contained INTERACTIVE HTML for embedding as a schematic view.⋯ 53 unchanged lines ⋯ } fn run() -> Result<()> {- match Cli::parse().command {+ let cli=Cli::parse();+ match cli.command {+ Cmd::Author {dir,name,port,ttl_hours} => author_server::run(dir,name,cli.ai_thread.unwrap_or_default(),port,ttl_hours)?,+ Cmd::State {port} => println!("{}",ureq::get(&format!("http://127.0.0.1:{port}/state")).call()?.into_string()?),+ Cmd::Edit {port,transaction} => {+ let mut v:serde_json::Value=serde_json::from_slice(&fs::read(transaction)?)?;+ if v.get("aiThread").is_none(){v["aiThread"]=serde_json::json!(cli.ai_thread.unwrap_or_default());}+ if v["aiThread"].as_str().unwrap_or("").trim().is_empty(){anyhow::bail!("caller_identity_required: use --ai-thread")}+ match ureq::post(&format!("http://127.0.0.1:{port}/author/transaction")).set("Content-Type","application/json").send_string(&v.to_string()) {+ Ok(r)=>println!("{}",r.into_string()?),+ Err(ureq::Error::Status(_,r))=>anyhow::bail!("{}",r.into_string()?),+ Err(e)=>return Err(e.into()),+ }+ }, Cmd::Render { file, out, meta } => { let raw = fs::read(&file).with_context(|| format!("read {}", file.display()))?; let (svg, m) = kicad_sch::render_sheet_bytes(&raw)?;⋯ 81 unchanged lines ⋯ } Ok(()) }+@@ -0,0 +1,894 @@+//! Revisioned single-sheet authoring. The saved document is authoritative;+//! KiCad is an editable export, not an image or a pre-authored replay.+use anyhow::{bail, Context, Result};+use serde::{Deserialize, Serialize};+use std::collections::{BTreeMap, BTreeSet};+use std::path::Path;+use uuid::Uuid;++#[derive(Clone, Debug, PartialEq)]+enum S {+ Atom(String),+ Text(String),+ List(Vec<S>),+}+impl S {+ fn value(&self) -> Option<&str> {+ match self {+ S::Atom(s) | S::Text(s) => Some(s),+ _ => None,+ }+ }+ fn list(&self) -> &[S] {+ match self {+ S::List(v) => v,+ _ => &[],+ }+ }+ fn tag(&self) -> Option<&str> {+ self.list().first().and_then(S::value)+ }+ fn child(&self, k: &str) -> Option<&S> {+ self.list().iter().find(|x| x.tag() == Some(k))+ }+ fn arg(&self, n: usize) -> Result<&str> {+ self.list()+ .get(n)+ .and_then(S::value)+ .context("Missing S-expression argument")+ }+ fn emit(&self) -> String {+ match self {+ S::Atom(s) => s.clone(),+ S::Text(s) => q(s),+ S::List(v) => format!("({})", v.iter().map(S::emit).collect::<Vec<_>>().join(" ")),+ }+ }+}+fn q(s: &str) -> String {+ serde_json::to_string(s).unwrap()+}+fn parse(s: &str) -> Result<S> {+ fn item(c: &[char], i: &mut usize) -> Result<S> {+ while c.get(*i).is_some_and(|c| c.is_whitespace()) {+ *i += 1+ }+ match c.get(*i) {+ Some('(') => {+ *i += 1;+ let mut a = vec![];+ loop {+ while c.get(*i).is_some_and(|c| c.is_whitespace()) {+ *i += 1+ }+ if c.get(*i) == Some(&')') {+ *i += 1;+ return Ok(S::List(a));+ }+ if *i == c.len() {+ bail!("Unclosed list")+ }+ a.push(item(c, i)?)+ }+ }+ Some('"') => {+ *i += 1;+ let mut s = String::new();+ loop {+ let x = *c.get(*i).context("Unclosed string")?;+ *i += 1;+ if x == '"' {+ break;+ }+ if x == '\\' {+ let e = *c.get(*i).context("Unclosed escape")?;+ *i += 1;+ s.push(match e {+ 'n' => '\n',+ 'r' => '\r',+ 't' => '\t',+ '"' => '"',+ '\\' => '\\',+ _ => bail!("Unsupported string escape"),+ })+ } else {+ s.push(x)+ }+ }+ Ok(S::Text(s))+ }+ Some(')') | None => bail!("Unexpected end or closing parenthesis"),+ _ => {+ let mut s = String::new();+ while let Some(x) = c.get(*i) {+ if x.is_whitespace() || *x == '(' || *x == ')' {+ break;+ }+ s.push(*x);+ *i += 1+ }+ Ok(S::Atom(s))+ }+ }+ }+ let c: Vec<_> = s.chars().collect();+ let mut i = 0;+ let a = item(&c, &mut i)?;+ if c[i..].iter().any(|c| !c.is_whitespace()) {+ bail!("Trailing content")+ }+ Ok(a)+}+fn id(doc: &str, key: &str) -> String {+ Uuid::new_v5(+ &Uuid::NAMESPACE_URL,+ format!("adom-schematic:{doc}:{key}").as_bytes(),+ )+ .to_string()+}+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Library {+ pub symbol: String,+ pub source_sha256: String,+}+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Component {+ pub reference: String,+ pub library: String,+ pub value: String,+ pub x: f64,+ pub y: f64,+ pub rotation: u16,+}+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]+pub struct PinRef {+ pub reference: String,+ pub pin: String,+}+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Connection {+ pub id: String,+ pub from: PinRef,+ pub to: PinRef,+}+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Label {+ pub endpoint: PinRef,+ pub net: String,+}+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Document {+ pub id: String,+ pub name: String,+ pub libraries: BTreeMap<String, Library>,+ pub components: BTreeMap<String, Component>,+ pub connections: Vec<Connection>,+ pub labels: Vec<Label>,+}+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Receipt {+ pub revision: u64,+ pub request: String,+}+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Project {+ pub revision: u64,+ pub document: Document,+ pub history: Vec<Document>,+ pub receipts: BTreeMap<String, Receipt>,+}+#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]+pub enum Operation {+ AddLibrary {+ key: String,+ symbol: String,+ },+ ReplaceLibrary {+ key: String,+ symbol: String,+ },+ Place {+ component: Component,+ },+ Move {+ reference: String,+ x: f64,+ y: f64,+ rotation: u16,+ },+ Connect {+ connection: Connection,+ },+ Label {+ label: Label,+ },+ Undo,+}+#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct Transaction {+ pub ai_thread: String,+ pub expected_revision: u64,+ pub operation_id: String,+ pub operations: Vec<Operation>,+}+#[derive(Clone, Debug, Serialize)]+pub struct Pin {+ pub number: String,+ pub x: f64,+ pub y: f64,+ pub angle: f64,+ pub electrical_type: String,+}+fn digest(s: &str) -> String {+ use sha2::{Digest, Sha256};+ format!("{:x}", Sha256::digest(s.as_bytes()))+}+fn library_root(s: &str) -> Result<S> {+ let a = parse(s)?;+ let symbols: Vec<_> = if a.tag() == Some("kicad_symbol_lib") {+ a.list()+ .iter()+ .filter(|x| x.tag() == Some("symbol"))+ .cloned()+ .collect()+ } else if a.tag() == Some("symbol") {+ vec![a]+ } else {+ bail!("Expected a KiCad symbol library")+ };+ if symbols.len() != 1 {+ bail!("Provide one exact library symbol, not a multi-component library")+ }+ let a = symbols[0].clone();+ if a.child("extends").is_some() {+ bail!("Resolve inherited library symbols before import")+ }+ for child in a.list().iter().filter(|x| x.tag() == Some("symbol")) {+ let name = child.arg(1)?;+ let suffix: Vec<_> = name.rsplit('_').take(2).collect();+ if suffix.len() != 2 || !matches!(suffix[1], "0" | "1") || suffix[0] != "1" {+ bail!("This authoring slice supports common/unit-1 symbols only; preserve multi-unit parts for the extended editor")+ }+ }+ Ok(a)+}+fn pins(s: &str) -> Result<Vec<Pin>> {+ let a = library_root(s)?;+ let mut out = vec![];+ let mut seen = BTreeSet::new();+ for unit in a.list().iter().filter(|x| x.tag() == Some("symbol")) {+ for p in unit.list().iter().filter(|x| x.tag() == Some("pin")) {+ let at = p.child("at").context("Pin missing position")?;+ let number = p+ .child("number")+ .context("Pin missing number")?+ .arg(1)?+ .to_string();+ if !seen.insert(number.clone()) {+ bail!("Duplicate pin number {number}")+ }+ let pin = Pin {+ number,+ x: at.arg(1)?.parse()?,+ y: at.arg(2)?.parse()?,+ angle: at.arg(3)?.parse()?,+ electrical_type: p.arg(1)?.into(),+ };+ if ![pin.x, pin.y, pin.angle].iter().all(|v| v.is_finite()) {+ bail!("Non-finite pin coordinate")+ };+ out.push(pin);+ }+ }+ if out.is_empty() {+ bail!("Symbol has no pins")+ };+ Ok(out)+}+fn coords(x: f64, y: f64, r: u16) -> Result<()> {+ if !x.is_finite()+ || !y.is_finite()+ || x.abs() > 1000.+ || y.abs() > 1000.+ || ![0, 90, 180, 270].contains(&r)+ {+ bail!("Use finite sheet-mm coordinates within ±1000 and rotation 0/90/180/270")+ };+ Ok(())+}+impl Project {+ pub fn new(name: &str) -> Self {+ Self {+ revision: 0,+ document: Document {+ id: Uuid::new_v4().to_string(),+ name: name.into(),+ libraries: BTreeMap::new(),+ components: BTreeMap::new(),+ connections: vec![],+ labels: vec![],+ },+ history: vec![],+ receipts: BTreeMap::new(),+ }+ }+ /// Stage on a clone. The caller persists it before replacing live state.+ pub fn stage(&self, t: &Transaction) -> Result<Self> {+ if t.ai_thread.trim().is_empty() {+ bail!("caller_identity_required: pass --ai-thread or aiThread")+ }+ if t.operation_id.is_empty() {+ bail!("operation_id_required: supply a unique retry key")+ }+ let request = serde_json::to_string(t)?;+ if let Some(r) = self.receipts.get(&t.operation_id) {+ if r.request == request {+ return Ok(self.clone());+ }+ bail!("operation_id_conflict: retry key has different content")+ }+ if t.expected_revision != self.revision {+ bail!("revision_conflict: read current state before editing")+ }+ if t.operations.is_empty() || t.operations.len() > 100 {+ bail!("Use 1 to 100 operations per transaction")+ }+ let mut next = self.clone();+ if t.operations.len() == 1 && matches!(t.operations[0], Operation::Undo) {+ next.document = next.history.pop().context("Nothing to undo")?;+ } else {+ next.history.push(self.document.clone());+ for op in &t.operations {+ next.document.apply(op)?;+ }+ }+ next.document.validate()?;+ next.revision += 1;+ next.receipts.insert(+ t.operation_id.clone(),+ Receipt {+ revision: next.revision,+ request,+ },+ );+ Ok(next)+ }+ pub fn persist(&self, folder: &Path) -> Result<()> {+ std::fs::create_dir_all(folder)?;+ // One authoritative atomic snapshot includes source and history. Exports+ // are regenerated from this same snapshot, never read as authority.+ let tmp = folder.join("project.json.tmp");+ use std::io::Write;+ let mut f = std::fs::File::create(&tmp)?;+ f.write_all(&serde_json::to_vec_pretty(self)?)?;+ f.sync_all()?;+ std::fs::rename(tmp, folder.join("project.json"))?;+ Ok(())+ }+ pub fn restore(folder: &Path) -> Result<Self> {+ let p: Self = serde_json::from_slice(&std::fs::read(folder.join("project.json"))?)?;+ p.document.validate()?;+ Ok(p)+ }+}+impl Document {+ fn apply(&mut self, op: &Operation) -> Result<()> {+ match op {+ Operation::AddLibrary { key, symbol } => {+ if key.is_empty() || key.contains(':') {+ bail!("Use a nonempty unqualified library key")+ }+ if self.libraries.contains_key(key) {+ bail!("Library already registered; in-use library replacement requires an explicit migration")+ }+ pins(symbol)?;+ self.libraries.insert(+ key.clone(),+ Library {+ symbol: symbol.clone(),+ source_sha256: digest(symbol),+ },+ );+ }+ Operation::ReplaceLibrary { key, symbol } => {+ let old = self.libraries.get(key).context("Unknown library")?;+ let signature = |s: &str| -> Result<BTreeMap<String, String>> {+ Ok(pins(s)?+ .into_iter()+ .map(|p| (p.number, p.electrical_type))+ .collect())+ };+ if signature(&old.symbol)? != signature(symbol)? {+ bail!("library_migration_conflict: pin identities or electrical types changed")+ }+ self.libraries.insert(+ key.clone(),+ Library {+ symbol: symbol.clone(),+ source_sha256: digest(symbol),+ },+ );+ }+ Operation::Place { component: c } => {+ if c.reference.is_empty()+ || !c+ .reference+ .chars()+ .all(|x| x.is_ascii_alphanumeric() || x == '_')+ {+ bail!("Use a nonempty alphanumeric reference")+ }+ if self.components.contains_key(&c.reference) {+ bail!("Reference already exists")+ };+ coords(c.x, c.y, c.rotation)?;+ if !self.libraries.contains_key(&c.library) {+ bail!("Register the exact library symbol before placement")+ }+ self.components.insert(c.reference.clone(), c.clone());+ }+ Operation::Move {+ reference,+ x,+ y,+ rotation,+ } => {+ coords(*x, *y, *rotation)?;+ let c = self+ .components+ .get_mut(reference)+ .context("Unknown reference")?;+ c.x = *x;+ c.y = *y;+ c.rotation = *rotation;+ }+ Operation::Connect { connection: c } => {+ self.endpoint(&c.from)?;+ self.endpoint(&c.to)?;+ if c.id.is_empty()+ || c.from == c.to+ || self.connections.iter().any(|x| x.id == c.id)+ {+ bail!("Connection needs distinct pins and a new stable ID")+ };+ self.connections.push(c.clone());+ }+ Operation::Label { label: l } => {+ self.endpoint(&l.endpoint)?;+ if l.net.trim().is_empty() {+ bail!("Net name must not be empty")+ };+ if self.labels.iter().any(|x| x.endpoint == l.endpoint) {+ bail!("Endpoint already labeled")+ };+ self.labels.push(l.clone());+ }+ Operation::Undo => bail!("Undo must be the sole operation in a transaction"),+ };+ Ok(())+ }+ pub fn endpoint(&self, p: &PinRef) -> Result<[f64; 2]> {+ let c = self+ .components+ .get(&p.reference)+ .context("Unknown endpoint reference")?;+ let lib = self.libraries.get(&c.library).context("Unknown library")?;+ let p = pins(&lib.symbol)?+ .into_iter()+ .find(|x| x.number == p.pin)+ .context("Unknown endpoint pin")?;+ let a = -(c.rotation as f64).to_radians();+ let x = p.x;+ let y = -p.y;+ Ok([+ c.x + x * a.cos() - y * a.sin(),+ c.y + x * a.sin() + y * a.cos(),+ ])+ }+ pub fn pin_inventory(&self) -> Result<Vec<serde_json::Value>> {+ let mut out = vec![];+ for c in self.components.values() {+ for pin in pins(&self.libraries[&c.library].symbol)? {+ let p = PinRef {+ reference: c.reference.clone(),+ pin: pin.number.clone(),+ };+ out.push(serde_json::json!({"endpoint":p,"at":self.endpoint(&p)?,"electricalType":pin.electrical_type}));+ }+ }+ Ok(out)+ }+ fn validate(&self) -> Result<()> {+ for c in self.components.values() {+ coords(c.x, c.y, c.rotation)?;+ pins(+ &self+ .libraries+ .get(&c.library)+ .context("Missing library")?+ .symbol,+ )?;+ }+ for c in &self.connections {+ self.endpoint(&c.from)?;+ self.endpoint(&c.to)?;+ }+ for l in &self.labels {+ self.endpoint(&l.endpoint)?;+ }+ Ok(())+ }+ /// Conservative contact audit of the exact orthogonal segments we export.+ /// Intended net groups come from explicit pin links and equal local labels.+ /// This does not replace KiCad's native netlist/ERC or validate component bodies.+ pub fn contact_issues(&self) -> Result<Vec<serde_json::Value>> {+ let mut pins_at = BTreeMap::new();+ for c in self.components.values() {+ for pin in pins(&self.libraries[&c.library].symbol)? {+ let p = PinRef {+ reference: c.reference.clone(),+ pin: pin.number,+ };+ pins_at.insert(p.clone(), self.endpoint(&p)?);+ }+ }+ let mut groups: BTreeMap<PinRef, usize> = pins_at+ .keys()+ .enumerate()+ .map(|(i, p)| (p.clone(), i))+ .collect();+ let merge = |g: &mut BTreeMap<PinRef, usize>, a: &PinRef, b: &PinRef| {+ let (x, y) = (g[a], g[b]);+ for v in g.values_mut() {+ if *v == y {+ *v = x;+ }+ }+ };+ for c in &self.connections {+ merge(&mut groups, &c.from, &c.to);+ }+ for (i, a) in self.labels.iter().enumerate() {+ for b in &self.labels[i + 1..] {+ if a.net == b.net {+ merge(&mut groups, &a.endpoint, &b.endpoint);+ }+ }+ }+ let on = |p: [f64; 2], a: [f64; 2], b: [f64; 2]| {+ (p[0] >= a[0].min(b[0]) - 1e-7 && p[0] <= a[0].max(b[0]) + 1e-7)+ && (p[1] >= a[1].min(b[1]) - 1e-7 && p[1] <= a[1].max(b[1]) + 1e-7)+ && ((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])).abs() < 1e-7+ };+ let mut segments = vec![];+ for c in &self.connections {+ let a = self.endpoint(&c.from)?;+ let b = self.endpoint(&c.to)?;+ for pair in [a, [b[0], a[1]], b].windows(2) {+ if pair[0] != pair[1] {+ segments.push((c, pair[0], pair[1]));+ }+ }+ }+ let mut issues = vec![];+ let mut seen = BTreeSet::new();+ for (c, a, b) in &segments {+ for (p, at) in &pins_at {+ if groups[p] != groups[&c.from]+ && on(*at, *a, *b)+ && seen.insert(format!("pin:{}:{}:{}", c.id, p.reference, p.pin))+ {+ issues.push(serde_json::json!({"code":"wire_contacts_unintended_pin","connection":c.id,"pin":p,"at":at,"hint":"Move the part or explicitly route the wire; this contact is absent from intended topology."}));+ }+ }+ }+ for (i, (c, a, b)) in segments.iter().enumerate() {+ for (d, x, y) in &segments[i + 1..] {+ if groups[&c.from] == groups[&d.from] {+ continue;+ }+ // An endpoint on another segment also covers all collinear overlaps.+ // Interior/interior perpendicular crossings have no junction here.+ if [*a, *b].iter().any(|p| on(*p, *x, *y))+ || [*x, *y].iter().any(|p| on(*p, *a, *b))+ {+ let key = if c.id < d.id {+ format!("wire:{}:{}", c.id, d.id)+ } else {+ format!("wire:{}:{}", d.id, c.id)+ };+ if seen.insert(key) {+ issues.push(serde_json::json!({"code":"unintended_wire_contact","connections":[c.id,d.id],"hint":"Separate endpoints and overlapping segments of different intended nets; verify native connectivity."}));+ }+ }+ }+ }+ Ok(issues)+ }+ pub fn export_kicad(&self) -> Result<String> {+ self.validate()?;+ let root = id(&self.id, "sheet");+ let mut out=format!("(kicad_sch (version 20250114) (generator \"adom-schematic\") (uuid {root}) (paper \"A4\")\n(title_block (title {}))\n(lib_symbols\n",q(&self.name));+ for (key, lib) in &self.libraries {+ let mut a = library_root(&lib.symbol)?;+ let source_name = a.arg(1)?.to_string();+ if let S::List(v) = &mut a {+ v[1] = S::Text(format!("Adom:{key}"));+ for unit in v.iter_mut().filter(|x| x.tag() == Some("symbol")) {+ let suffix = unit+ .arg(1)?+ .strip_prefix(&format!("{source_name}_"))+ .context("Library unit does not match its root symbol name")?+ .to_string();+ if let S::List(u) = unit {+ u[1] = S::Text(format!("{key}_{suffix}"));+ }+ }+ }+ out += &a.emit();+ out += '\n'.to_string().as_str();+ }+ out += ")\n";+ for c in self.components.values() {+ let sid = id(&self.id, &format!("component:{}", c.reference));+ out+=&format!("(symbol (lib_id {}) (at {} {} {}) (unit 1) (in_bom yes) (on_board yes) (dnp no) (uuid {sid})\n",q(&format!("Adom:{}",c.library)),c.x,c.y,c.rotation);+ out+=&format!("(property \"Reference\" {} (at {} {} 0) (effects (font (size 1.27 1.27)) (justify left)))\n",q(&c.reference),c.x+2.54,c.y-2.54);+ out+=&format!("(property \"Value\" {} (at {} {} 0) (effects (font (size 1.27 1.27)) (justify left)))\n",q(&c.value),c.x+2.54,c.y);+ let lib = library_root(&self.libraries[&c.library].symbol)?;+ for k in ["Footprint", "Datasheet", "Manufacturer", "Part Number"] {+ if let Some(p) = lib+ .list()+ .iter()+ .find(|p| p.tag() == Some("property") && p.arg(1).ok() == Some(k))+ {+ out+=&format!("(property {} {} (at {} {} 0) (effects (font (size 1.27 1.27)) (hide yes)))\n",q(k),q(p.arg(2)?),c.x,c.y);+ }+ }+ for p in pins(&self.libraries[&c.library].symbol)? {+ out += &format!(+ "(pin {} (uuid {}))\n",+ q(&p.number),+ id(&self.id, &format!("pin:{}:{}", c.reference, p.number))+ );+ }+ out += &format!(+ "(instances (project {} (path {} (reference {}) (unit 1)))) )\n",+ q(&self.name),+ q(&format!("/{root}")),+ q(&c.reference)+ );+ }+ let mut joined: BTreeMap<PinRef, usize> = BTreeMap::new();+ for c in &self.connections {+ let a = self.endpoint(&c.from)?;+ let z = self.endpoint(&c.to)?;+ let points = [a, [z[0], a[1]], z];+ for (i, p) in points.windows(2).enumerate() {+ if (p[0][0] - p[1][0]).abs() + (p[0][1] - p[1][1]).abs() < 1e-8 {+ continue;+ };+ out+=&format!("(wire (pts (xy {} {}) (xy {} {})) (stroke (width 0) (type default)) (uuid {}))\n",p[0][0],p[0][1],p[1][0],p[1][1],id(&self.id,&format!("wire:{}:{i}",c.id)));+ }+ *joined.entry(c.from.clone()).or_default() += 1;+ *joined.entry(c.to.clone()).or_default() += 1;+ }+ for (p, n) in joined {+ if n > 1 {+ let a = self.endpoint(&p)?;+ out += &format!(+ "(junction (at {} {}) (diameter 0) (color 0 0 0 0) (uuid {}))\n",+ a[0],+ a[1],+ id(&self.id, &format!("junction:{}:{}", p.reference, p.pin))+ );+ }+ }+ for l in &self.labels {+ let a = self.endpoint(&l.endpoint)?;+ out+=&format!("(label {} (at {} {} 0) (effects (font (size 1.27 1.27)) (justify left bottom)) (uuid {}))\n",q(&l.net),a[0],a[1],id(&self.id,&format!("label:{}:{}",l.endpoint.reference,l.endpoint.pin)));+ }+ out += ")\n";+ parse(&out)?;+ Ok(out)+ }+}+#[cfg(test)]+mod tests {+ use super::*;+ const CAP: &str = include_str!("../tests/fixtures/wurth-885012206026.kicad_sym");+ fn tx(p: &Project, key: &str, operations: Vec<Operation>) -> Transaction {+ Transaction {+ ai_thread: "authoring test".into(),+ expected_revision: p.revision,+ operation_id: key.into(),+ operations,+ }+ }+ fn placed() -> Project {+ let p = Project::new("decoupling");+ p.stage(&tx(+ &p,+ "setup",+ vec![+ Operation::AddLibrary {+ key: "cap".into(),+ symbol: CAP.into(),+ },+ Operation::Place {+ component: Component {+ reference: "C1".into(),+ library: "cap".into(),+ value: "1uF".into(),+ x: 50.,+ y: 50.,+ rotation: 0,+ },+ },+ ],+ ))+ .unwrap()+ }+ #[test]+ fn embedded_library_units_follow_exported_identity() {+ let p = placed();+ let out = p.document.export_kicad().unwrap();+ let root = parse(&out).unwrap();+ let libs = root.child("lib_symbols").unwrap();+ let lib = libs+ .list()+ .iter()+ .find(|x| x.tag() == Some("symbol"))+ .unwrap();+ assert_eq!(lib.arg(1).unwrap(), "Adom:cap");+ let units: Vec<_> = lib+ .list()+ .iter()+ .filter(|x| x.tag() == Some("symbol"))+ .map(|x| x.arg(1).unwrap())+ .collect();+ assert!(units.contains(&"cap_1_1"));+ assert!(units.iter().all(|x| x.starts_with("cap_")));+ assert_eq!(p.document.libraries["cap"].symbol, CAP);+ }+ #[test]+ fn detects_wire_through_unintended_capacitor_pin() {+ let mut p = placed();+ p.document.components.insert(+ "C2".into(),+ Component {+ reference: "C2".into(),+ library: "cap".into(),+ value: "1uF".into(),+ x: 70.,+ y: 30.,+ rotation: 0,+ },+ );+ p.document.connections.push(Connection {+ id: "rail".into(),+ from: PinRef {+ reference: "C1".into(),+ pin: "1".into(),+ },+ to: PinRef {+ reference: "C2".into(),+ pin: "1".into(),+ },+ });+ let issues = p.document.contact_issues().unwrap();+ assert!(issues+ .iter()+ .any(|v| v["pin"]["reference"] == "C2" && v["pin"]["pin"] == "2"));+ p.document.components.get_mut("C2").unwrap().y = 70.;+ assert!(p.document.contact_issues().unwrap().is_empty());+ }+ #[test]+ fn quoted_parentheses_roundtrip() {+ let s = "(property \"Description\" \"sensor (SPI) \\\"quoted\\\"\")";+ let a = parse(s).unwrap();+ assert_eq!(parse(&a.emit()).unwrap(), a);+ assert!(parse("(x \"broken)").is_err());+ }+ #[test]+ fn exact_manufacturer_pin_and_rotation_export() {+ let mut p = placed();+ let pin = PinRef {+ reference: "C1".into(),+ pin: "1".into(),+ };+ assert_eq!(p.document.endpoint(&pin).unwrap(), [50., 46.19]);+ p = p+ .stage(&tx(+ &p,+ "move",+ vec![Operation::Move {+ reference: "C1".into(),+ x: 50.,+ y: 50.,+ rotation: 90,+ }],+ ))+ .unwrap();+ let a = p.document.endpoint(&pin).unwrap();+ assert!((a[0] - 46.19).abs() < 1e-8);+ assert!((a[1] - 50.).abs() < 1e-8);+ let out = p.document.export_kicad().unwrap();+ let native = crate::sch_parse::parse(&out);+ assert_eq!(native.comps.len(), 1);+ assert_eq!(native.comps[0].pin_count, 2);+ assert_eq!(native.comps[0].reference, "C1");+ }+ #[test]+ fn stale_retry_and_undo_preserve_identity() {+ let p = placed();+ let t = tx(+ &p,+ "move",+ vec![Operation::Move {+ reference: "C1".into(),+ x: 70.,+ y: 50.,+ rotation: 0,+ }],+ );+ let n = p.stage(&t).unwrap();+ assert_eq!(n.stage(&t).unwrap().revision, 2);+ let mut stale = t.clone();+ stale.operation_id = "other".into();+ assert!(n+ .stage(&stale)+ .unwrap_err()+ .to_string()+ .contains("revision_conflict"));+ let u = n.stage(&tx(&n, "undo", vec![Operation::Undo])).unwrap();+ assert_eq!(u.revision, 3);+ assert_eq!(+ u.document.export_kicad().unwrap(),+ p.document.export_kicad().unwrap()+ );+ }+ #[test]+ fn bad_endpoint_rolls_back_entire_batch() {+ let p = placed();+ let pin = PinRef {+ reference: "C1".into(),+ pin: "99".into(),+ };+ let t = tx(+ &p,+ "bad",+ vec![+ Operation::Move {+ reference: "C1".into(),+ x: 90.,+ y: 50.,+ rotation: 0,+ },+ Operation::Label {+ label: Label {+ endpoint: pin,+ net: "VIO".into(),+ },+ },+ ],+ );+ assert!(p.stage(&t).is_err());+ assert_eq!(p.document.components["C1"].x, 50.);+ }+ #[test]+ fn lossless_snapshot_and_unmodified_source_hash() {+ let p = placed();+ let f = std::env::temp_dir().join(format!("adom-sch-{}", Uuid::new_v4()));+ p.persist(&f).unwrap();+ let n = Project::restore(&f).unwrap();+ assert_eq!(+ n.document.export_kicad().unwrap(),+ p.document.export_kicad().unwrap()+ );+ assert_eq!(n.document.libraries["cap"].source_sha256, digest(CAP));+ std::fs::remove_dir_all(f).unwrap();+ }+}+@@ -0,0 +1,307 @@+//! Live authoring server alongside the existing import viewer. No hardware I/O.+use crate::author::{Project, Transaction};+use anyhow::{bail, Context, Result};+use serde_json::{json, Value};+use std::{+ io::{Read, Write},+ path::PathBuf,+ sync::mpsc,+ time::{Duration, Instant},+};+use tiny_http::{Header, Method, Response, Server};+fn header(k: &str, v: &str) -> Header {+ Header::from_bytes(k, v).unwrap()+}+fn send(req: tiny_http::Request, status: u16, v: Value) {+ let _ = req.respond(+ Response::from_string(v.to_string())+ .with_status_code(status)+ .with_header(header("Content-Type", "application/json")),+ );+}+fn snapshot(p: &Project, owner: &str) -> Result<Value> {+ let sch = p.document.export_kicad()?;+ let sheet = crate::sch_parse::parse(&sch);+ let (x, y, w, h) = sheet.content_bbox;+ let inner = crate::kicad_self::render_inner(&sch);+ let svg = format!(+ r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="{} {} {} {}"><rect class="adom-sheet-bg" x="{}" y="{}" width="{}" height="{}" fill="#fbfbf6"/><g class="adom-sheet">{}</g></svg>"##,+ x,+ y,+ w.max(30.),+ h.max(30.),+ x,+ y,+ w.max(30.),+ h.max(30.),+ inner+ );+ Ok(+ json!({"name":p.document.name,"svg":svg,"meta":serde_json::from_str::<Value>(&crate::kicad_sch::meta_json(&sch)?)?,"author":{"revision":p.revision,"documentId":p.document.id,"aiThread":owner,"libraries":p.document.libraries.keys().collect::<Vec<_>>(),"components":p.document.components,"pins":p.document.pin_inventory()?,"contactIssues":p.document.contact_issues()?,"connections":p.document.connections,"labels":p.document.labels,"status":"Development authoring slice; circuit/ERC and native parity pending","hints":["Use expectedRevision and operationId for every edit; read state on conflicts.","Endpoints are stable reference/pin identities; moving a component updates connected wire endpoints.","Local Rust preview is not a native KiCad render or ERC result.","Inspect contactIssues for unintended pin or wire contacts. Body clearance and native netlist equivalence remain separate checks."]}}),+ )+}+fn error(e: impl std::fmt::Display) -> Value {+ let msg = e.to_string();+ let code = msg.split(':').next().unwrap_or("invalid_edit");+ json!({"ok":false,"error":msg,"errorCode":code,"hint":"Read /state and retry only the rejected transaction. Accepted operation IDs are idempotent."})+}+pub fn run(folder: PathBuf, name: String, owner: String, port: u16, ttl_hours: f64) -> Result<()> {+ if owner.trim().is_empty() {+ bail!("caller_identity_required: use --ai-thread")+ }+ if !ttl_hours.is_finite() || ttl_hours <= 0. {+ bail!("TTL must be positive")+ }+ std::fs::create_dir_all(&folder)?;+ let folder = folder.canonicalize()?;+ let instance_file = folder.join("instance.json");+ if let Ok(s) = std::fs::read_to_string(&instance_file) {+ if let Ok(v) = serde_json::from_str::<Value>(&s) {+ if let Some(p) = v["port"].as_u64() {+ if let Ok(r) = ureq::get(&format!("http://127.0.0.1:{p}/author/identity"))+ .timeout(Duration::from_secs(2))+ .call()+ {+ let live: Value = serde_json::from_str(&r.into_string()?)?;+ if live["folder"] == folder.to_string_lossy().as_ref() {+ if live["aiThread"] != owner {+ bail!("project_in_use: another ai-thread owns this live project")+ };+ println!(+ "{}",+ json!({"ok":true,"reused":true,"port":p,"aiThread":owner,"hint":"Reuse the live authoring instance; no files were replaced."})+ );+ return Ok(());+ }+ }+ }+ }+ }+ let mut p = if folder.join("project.json").exists() {+ Project::restore(&folder)?+ } else {+ let p = Project::new(&name);+ p.persist(&folder)?;+ p+ };+ let mut state = snapshot(&p, &owner)?;+ let server = Server::http(("127.0.0.1", port)).map_err(|e| anyhow::anyhow!("bind: {e}"))?;+ let port = server+ .server_addr()+ .to_ip()+ .context("No IP listener")?+ .port();+ let identity = json!({"ok":true,"name":"adom-schematic","version":env!("CARGO_PKG_VERSION"),"mode":"authoring-development","pid":std::process::id(),"port":port,"folder":folder,"aiThread":owner,"ttlHours":ttl_hours});+ let home = std::env::var("HOME").context("HOME unavailable")?;+ let registry = PathBuf::from(home).join(".adom/instances/adom-schematic");+ std::fs::create_dir_all(®istry)?;+ let key = uuid::Uuid::new_v5(+ &uuid::Uuid::NAMESPACE_URL,+ format!("{}:{owner}", folder.display()).as_bytes(),+ )+ .to_string();+ let reg = registry.join(format!("{key}.json"));+ std::fs::write(&instance_file, serde_json::to_vec_pretty(&identity)?)?;+ std::fs::write(®, serde_json::to_vec_pretty(&identity)?)?;+ println!("{}", identity);+ let html = include_str!("app.html")+ .replace("</body>", "<script src=\"author-ui.js\"></script></body>");+ let mut clients: Vec<mpsc::Sender<String>> = vec![];+ let mut last = Instant::now();+ let mut console: Vec<Value> = vec![];+ let mut ack = json!({"revision":null});+ loop {+ let mut req = match server.recv_timeout(Duration::from_secs(1))? {+ Some(r) => r,+ None => {+ if last.elapsed().as_secs_f64() > ttl_hours * 3600. {+ break;+ }+ continue;+ }+ };+ last = Instant::now();+ let path = req.url().split('?').next().unwrap_or("/").to_string();+ let method = req.method().clone();+ if method == Method::Get && path == "/events" {+ let (tx, rx) = mpsc::channel();+ tx.send(format!(+ ": {}\n\nevent: state\ndata: {}\n\n",+ " ".repeat(2048),+ state+ ))?;+ clients.push(tx);+ std::thread::spawn(move || {+ // tiny_http's default chunk encoder buffers small events. Flush+ // every SSE frame explicitly so edit acknowledgements are live.+ let mut w = req.into_writer();+ if w.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nX-Accel-Buffering: no\r\nConnection: close\r\n\r\n").and_then(|_|w.flush()).is_err(){return}+ loop {+ let message = match rx.recv_timeout(Duration::from_secs(15)) {+ Ok(s) => s,+ Err(mpsc::RecvTimeoutError::Timeout) => ": heartbeat\n\n".into(),+ Err(_) => break,+ };+ if w.write_all(message.as_bytes())+ .and_then(|_| w.flush())+ .is_err()+ {+ break;+ }+ }+ });+ continue;+ }+ if method == Method::Get {+ let asset = match path.as_str() {+ "/" | "/index.html" => Some((html.as_str(), "text/html; charset=utf-8")),+ "/viewer.js" => Some((include_str!("viewer.js"), "text/javascript")),+ "/author-ui.js" => Some((include_str!("author_ui.js"), "text/javascript")),+ _ => None,+ };+ if let Some((s, ct)) = asset {+ let _ =+ req.respond(Response::from_string(s).with_header(header("Content-Type", ct)));+ continue;+ }+ match path.as_str() {+ "/state" => send(req, 200, state.clone()),+ "/version" | "/author/identity" => send(req, 200, identity.clone()),+ "/author/native" => {+ let check = (|| -> Result<Value> {+ use sha2::{Digest, Sha256};+ let report: Value = serde_json::from_slice(&std::fs::read(+ folder.join("native-validation.json"),+ )?)?;+ let sch = p.document.export_kicad()?;+ let hash = format!("{:x}", Sha256::digest(sch.as_bytes()));+ if report["sourceSha256"] != hash || report["revision"] != p.revision {+ bail!("native_validation_stale: validate the current exported revision")+ }+ let svg = std::fs::read_to_string(folder.join("native-validation.svg"))?;+ if report["svgSha256"] != format!("{:x}", Sha256::digest(svg.as_bytes())) {+ bail!("native_render_hash_mismatch")+ }+ let (svg, meta) =+ crate::kicad_sch::render_sheet_with_base(&sch, Some(&svg))?;+ Ok(json!({"ok":true,"report":report,"svg":svg,"meta":meta}))+ })();+ match check {+ Ok(v) => send(req, 200, v),+ Err(e) => send(req, 409, error(e)),+ }+ }+ "/author/ack" => send(req, 200, ack.clone()),+ "/console" => send(req, 200, json!({"lines":console})),+ "/ui/pull" => send(req, 200, json!({"cmds":[],"toasts":[]})),+ "/enrich" => send(+ req,+ 200,+ json!({"hint":"Use adom-parts-search for an explicit quota-aware distributor query; authoring never searches vendors automatically."}),+ ),+ "/export/kicad" => {+ let _ = req.respond(+ Response::from_string(p.document.export_kicad()?)+ .with_header(header("Content-Type", "text/plain; charset=utf-8"))+ .with_header(header(+ "Content-Disposition",+ "attachment; filename=schematic.kicad_sch",+ )),+ );+ }+ _ => send(req, 404, error("unknown_endpoint")),+ };+ continue;+ }+ if method != Method::Post {+ send(req, 405, error("method_not_allowed"));+ continue;+ }+ let mut body = String::new();+ req.as_reader().take(2_000_001).read_to_string(&mut body)?;+ if body.len() > 2_000_000 {+ send(req, 413, error("request_too_large"));+ continue;+ }+ if path == "/console" {+ if let Ok(v) = serde_json::from_str::<Value>(&body) {+ console.push(v);+ if console.len() > 500 {+ console.remove(0);+ }+ }+ send(req, 200, json!({"ok":true}));+ continue;+ }+ if path == "/author/ack" {+ if let Ok(v) = serde_json::from_str::<Value>(&body) {+ ack = v;+ }+ send(req, 200, json!({"ok":true}));+ continue;+ }+ let v: Value = match serde_json::from_str(&body) {+ Ok(v) => v,+ Err(e) => {+ send(req, 400, error(e));+ continue;+ }+ };+ if v["aiThread"].as_str().unwrap_or("").trim().is_empty() {+ send(+ req,+ 400,+ error("caller_identity_required: provide aiThread"),+ );+ continue;+ }+ if path == "/shutdown" {+ if v["reason"].as_str().unwrap_or("").trim().is_empty() {+ send(+ req,+ 400,+ error("reason_required: state why this instance can stop"),+ );+ continue;+ }+ p.persist(&folder)?;+ send(req, 200, json!({"ok":true,"savedRevision":p.revision}));+ break;+ }+ if path != "/author/transaction" {+ send(req, 404, error("unknown_endpoint"));+ continue;+ }+ let t: Transaction = match serde_json::from_value(v) {+ Ok(t) => t,+ Err(e) => {+ send(req, 400, error(e));+ continue;+ }+ };+ match p.stage(&t).and_then(|next| {+ let s = snapshot(&next, &owner)?;+ next.persist(&folder)?;+ Ok((next, s))+ }) {+ Ok((next, s)) => {+ p = next;+ state = s;+ let event = format!("event: state\ndata: {}\n\n", state);+ clients.retain(|tx| tx.send(event.clone()).is_ok());+ console.push(json!({"aiThread":t.ai_thread,"operationId":t.operation_id,"revision":p.revision}));+ send(+ req,+ 200,+ json!({"ok":true,"revision":p.revision,"operationRevision":p.receipts[&t.operation_id].revision,"operationId":t.operation_id,"hints":state["author"]["hints"]}),+ );+ }+ Err(e) => send(req, 422, error(e)),+ }+ }+ p.persist(&folder)?;+ let _ = std::fs::remove_file(instance_file);+ let _ = std::fs::remove_file(reg);+ Ok(())+}+@@ -0,0 +1,18 @@+/* The same authoring transaction endpoint serves human controls and the CLI. */+(async()=>{+ const initial=await fetch('state').then(r=>r.json());if(!initial.author)return;+ let latest=initial.author;const style=document.createElement('style');style.textContent=`+ body.author #svgbox{top:152px!important}body.author #side{display:none!important}#authorBar{position:absolute;top:44px;left:0;right:0;min-height:92px;z-index:10;padding:6px 12px;background:var(--panel,#15202b);border-bottom:1px solid var(--edge,#39434d);font:12px sans-serif;color:var(--ink,#eee)}+ #authorBar .row{display:flex;gap:6px;align-items:center;flex-wrap:wrap;margin:4px 0}#authorBar input,#authorBar select,#authorBar button{font:inherit;background:var(--bg,#18232e);color:inherit;border:1px solid var(--edge,#40505d);border-radius:4px;padding:4px}#authorBar input[type=number]{width:48px}#authorBar .ref{width:44px}#authorStatus{color:var(--muted,#abb7c2)}#authorBar a{color:var(--accent,#73caca)}+ `;document.head.append(style);document.body.classList.add('author');+ const bar=document.createElement('section');bar.id='authorBar';bar.innerHTML=`<div class="row"><strong id="authorRevision"></strong><span id="authorStatus">Development circuit • not released</span><button id="authorUndo" title="Restore the previous document as a new revision">Undo</button><a href="export/kicad">KiCad file</a><button id="authorNative">Inspect native KiCad render</button><button id="authorLocal">Live preview</button></div><div class="row"><select id="authorLib" title="Registered exact component library"></select><input id="authorRef" class="ref" value="C1" aria-label="Reference"><input id="authorX" type="number" value="50" aria-label="X millimetres"><input id="authorY" type="number" value="50" aria-label="Y millimetres"><button id="authorPlace">Place</button><select id="authorFrom" title="Start pin"></select><select id="authorTo" title="End pin"></select><button id="authorConnect">Connect</button></div>`;document.body.append(bar);+ const $=s=>document.getElementById(s);function options(el,rows){const old=el.value;el.replaceChildren(...rows.map(([v,t])=>{const o=document.createElement('option');o.value=v;o.textContent=t;return o}));if(rows.some(([v])=>v===old))el.value=old;}+ function update(s){if(!s.author)return;latest=s.author;window.AdomAuthorSnapshot=s;window.AdomAuthorState=latest;window.AdomSch.mount(s.svg,s.meta);$('authorRevision').textContent=`${s.name} · revision ${latest.revision}`;options($('authorLib'),latest.libraries.map(k=>[k,k]));const pins=latest.pins.map(p=>[JSON.stringify(p.endpoint),`${p.endpoint.reference}.${p.endpoint.pin}`]);options($('authorFrom'),pins);options($('authorTo'),pins);requestAnimationFrame(()=>requestAnimationFrame(()=>fetch('author/ack',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({revision:latest.revision,componentCount:latest.pins.length?Object.keys(latest.components).length:0,paintedAt:new Date().toISOString()})})));}+ async function transact(operations){const r=await fetch('author/transaction',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({aiThread:'Schematic UI',expectedRevision:latest.revision,operationId:crypto.randomUUID(),operations})});const s=await r.json();if(!s.ok){window.AdomSch.toast(s.error,'error');return}window.AdomSch.toast(`Saved revision ${s.revision}`,'success');}+ $('authorPlace').onclick=()=>transact([{op:'place',component:{reference:$('authorRef').value,library:$('authorLib').value,value:$('authorLib').value,x:Number($('authorX').value),y:Number($('authorY').value),rotation:0}}]);+ $('authorConnect').onclick=()=>{if(!$('authorFrom').value||!$('authorTo').value)return;transact([{op:'connect',connection:{id:crypto.randomUUID(),from:JSON.parse($('authorFrom').value),to:JSON.parse($('authorTo').value)}}]);};+ $('authorNative').onclick=async()=>{const r=await fetch('author/native');const v=await r.json();if(!v.ok){window.AdomSch.toast(v.error,'error');return}window.AdomSch.mount(v.svg,v.meta);$('authorStatus').textContent=`KiCad ${v.report.kicadVersion} service render • revision ${v.report.revision} • ${v.report.violationCount} ERC findings`;};+ $('authorLocal').onclick=()=>{update({name:initial.name,author:latest,...window.AdomAuthorSnapshot});$('authorStatus').textContent='Live Rust preview • native checks separate';};+ $('authorUndo').onclick=()=>transact([{op:'undo'}]);update(initial);const events=new EventSource('events');events.addEventListener('state',e=>update(JSON.parse(e.data)));events.onerror=()=>{$('authorStatus').textContent='Reconnecting… saved document retained';};events.onopen=()=>{$('authorStatus').textContent='Live • development circuit • ERC pending';};+})().catch(e=>console.error('Authoring UI:',e));+@@ -0,0 +1,123 @@+(kicad_symbol_lib (version 20211014) (generator kicad_symbol_editor)+ (symbol "0603_R_885012206026" (pin_numbers hide) (pin_names hide) (in_bom yes) (on_board yes)+ (property "Reference" "C" (id 0) (at 5.08 5.08 0)+ (effects (font (size 1.27 1.27)) (justify left))+ )+ (property "Value" "1 uF" (id 1) (at 5.08 22.86 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Footprint" "Capacitor_SMD_Wurth:C_Wurth_WCAP-CSGP-0603_R" (id 2) (at 5.08 20.32 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Datasheet" "https://www.we-online.com/catalog/datasheet/885012206026.pdf?ki" (id 3) (at 5.08 17.78 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Manufacturer" "Wurth Elektronik" (id 4) (at 5.08 15.24 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Manufacturer URL" "https://www.we-online.com" (id 5) (at 5.08 12.7 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Created Date" "20251008" (id 6) (at 5.08 10.16 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Series" "WCAP-CSGP" (id 7) (at 5.08 7.62 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Size" "0603_R" (id 8) (at 5.08 5.08 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Mounting Technology" "SMT" (id 9) (at 5.08 2.54 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Part Number" "885012206026" (id 10) (at 5.08 2.54 0)+ (effects (font (size 1.27 1.27)) (justify left))+ )+ (property "Capacitance" "1 uF" (id 11) (at 5.08 0 0)+ (effects (font (size 1.27 1.27)) (justify left))+ )+ (property "Voltage" "10.0" (id 12) (at 5.08 -2.54 0)+ (effects (font (size 1.27 1.27)) (justify left))+ )+ (property "C" "1 uF" (id 11) (at 12.7 -2.54 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Tol. C" "±10%" (id 12) (at 12.7 -5.08 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "VR (V (DC))" "10.0" (id 13) (at 12.7 -7.62 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Operating Temperature" "-55 °C up to +125 °C" (id 14) (at 12.7 -10.16 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "DF (%)" "10" (id 15) (at 12.7 -12.7 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "RISO" "0.1 Gohm" (id 16) (at 12.7 -15.239999999999998 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Ceramic Type" "X7R Class II" (id 17) (at 12.7 -17.779999999999998 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "L (mm)" "1.6" (id 18) (at 12.7 -20.319999999999997 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "W (mm)" "0.8" (id 19) (at 12.7 -22.859999999999996 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "H (mm)" "0.8" (id 20) (at 12.7 -25.399999999999995 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Fl (mm)" "0.4" (id 21) (at 12.7 -27.939999999999994 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Q (%)" "–" (id 22) (at 12.7 -30.479999999999993 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "Demoboard" "nan" (id 23) (at 12.7 -33.019999999999996 0)+ (effects (font (size 1.27 1.27)) (justify left) hide)+ )+ (property "ki_keywords" "SMT" (id 24) (at 0 0 0)+ (effects (font (size 1.27 1.27)) hide)+ )+ (property "ki_description" "MLCCs 10 V(DC) ED" (id 25) (at 0 0 0)+ (effects (font (size 1.27 1.27)) hide)+ )+ (property "ki_fp_filters" "*WCAP-CSGP*0603*" (id 26) (at 0 0 0)+ (effects (font (size 1.27 1.27)) hide)+ )+ (property "Critical Parameter" "" (id 27) (at 0 -7.62 0)+ (effects (font (size 1.27 1.27)) (justify left))+ )+ (symbol "0603_R_885012206026_0_1"+ (polyline+ (pts+ (xy -2.032 -0.762)+ (xy 2.032 -0.762)+ )+ (stroke (width 0.508) (type default))+ (fill (type none))+ )+ (polyline+ (pts+ (xy -2.032 0.762)+ (xy 2.032 0.762)+ )+ (stroke (width 0.508) (type default))+ (fill (type none))+ )+ )+ (symbol "0603_R_885012206026_1_1"+ (pin passive line (at 0 3.81 270) (length 2.794)+ (name "1" (effects (font (size 1.27 1.27))))+ (number "1" (effects (font (size 1.27 1.27))))+ )+ (pin passive line (at 0 -3.81 90) (length 2.794)+ (name "2" (effects (font (size 1.27 1.27))))+ (number "2" (effects (font (size 1.27 1.27))))+ )+ )+ )+)+@@ -0,0 +1,77 @@+# Revisioned authoring development slice++Start `adom-schematic --ai-thread 'Circuit work' author --dir ./circuit` and use+the returned port. A live same-folder instance is reused after identity read-back;+a different owner returns `project_in_use`. The existing import viewer is unchanged.+The default authoring port is allocated by the OS. Saved state is `project.json`;+a folder-local and per-thread global instance record identify the server. The+24-hour idle timeout saves state and removes instance records. Settings UI, `ls`,+webview tab cleanup on reap and cross-process startup locking are still pending.++Show the URL in a Hydrogen work-pane webview with an explicit non-editor panel ID.+Keep VS Code visible. Do not use Simple Browser or foreground desktop CAD to obtain+a capture. Read the actual rendered surface after opening it.++## Transactions++POST `/author/transaction` with `aiThread`, `expectedRevision`, a unique+`operationId`, and `operations`. CLI `edit --transaction file.json` sends the same+request and supplies `aiThread` from its global flag if the file omits it.++Operations are `add_library {key,symbol}`, `replace_library {key,symbol}`,+`place {component:{reference,library,value,x,y,rotation}}`,+`move {reference,x,y,rotation}`, `connect {connection:{id,from,to}}`,+`label {label:{endpoint,net}}`, and `undo`. Endpoints are `{reference,pin}`.+Undo must be the only operation. Coordinates are sheet millimetres; rotations are+0/90/180/270. Exact library sources are retained with SHA-256. Replacement requires+the same pin-number/electrical-type signature; callers must inspect any origin or+geometry change and explicitly migrate placements where needed.++A rejected batch changes nothing. An identical accepted operation retry returns+its receipt; changing content under that ID fails. Revision conflicts require a+fresh state read. A successful HTTP mutation alone does not establish visible+paint: read `/author/ack`, then inspect the actual surface. SSE current-state replay,+15-second heartbeat and explicit flushing avoid buffering small edits.++## Evidence and native inspection++GET `/state`, `/author/identity`, `/author/ack`, `/console`, `/export/kicad`.+The native exporter embeds library definitions, consistently renames their unit+prefixes, and keeps stable entity UUIDs. Save export bytes without locale decoding.+Use the `service-kicad` CLI for native SVG and ERC. A parser unit test is not proof+that KiCad can load the file.++The optional `/author/native` inspection reads `native-validation.json` and+`native-validation.svg` from the project folder. It requires exact current export+SHA-256 and revision plus a matching SVG hash; stale or modified artifacts are+rejected. The report contains `sourceSha256`, `svgSha256`, `revision`,+`kicadVersion`, `violationCount` and the actual checks/limitations. Creating this+report is presently an explicit external validation step, not an automatic+validation command. The UI labels native service rendering separately from the+fast local preview. Any design edit returns the UI to the live preview.++The native inspection does not prove a desktop KiCad document was opened, nor+Fusion/Altium parity. ERC findings are not suppressed merely to obtain a pass.++## Current limits++One sheet; common/unit-1 symbols only; no inherited or multi-unit symbols. No+arbitrary wire waypoints, routing around bodies, netlist equivalence, bus support,+interactive drag placement, deletion or complete circuit synthesis. Manhattan+routes are derived from endpoint geometry. `contactIssues` conservatively identifies+unintended pin contacts and cross-net endpoint/overlap contacts. Interior crossings+without junctions are treated as separate wires. This audit does not replace native+connectivity/ERC or symbol-body clearance checks.++The fast renderer currently omits pin/group text and some symbol graphics; use the+hash-matched native inspection for readable pin/group review. Human authoring UI+currently exposes placement, connection and undo only. Library registration,+replacement, movement and labeling use typed transactions. Caller names provide+attribution, not authentication. The server binds loopback and is a development+instance, not a hardened shared service.++Tests exercise quoted library text, exact pin transforms, stable identity, retries,+undo, batch rollback, persistence, library-unit naming and unintended capacitor-pin+contact detection. Live native load, SVG and ERC evidence belongs with the worked+project and exact exported file hash.+
Comments
Log in to comment.