From 263c4bc6cf2a4ddf1789b29dfb6cad0a6ce0ea5c Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sat, 21 Nov 2026 17:21:04 -0500 Subject: [PATCH] Overhaul system prompt, skill-ify workflows, and support dual Altium+KiCad projects - Rewrite KiCad board editing, mechanical, KiCad runtime, orchestration, and background work blocks for clarity and token efficiency (-58.8% on default golden prompt). - Emphasize IPC-first KiCad editing (kicad_edit primary, kicad_ipc escape hatch) and remove the raw GitHub BACKPLANE_IPC.md URL from the runtime block. - Skill-ify bulky workflows into bundled skills with crisp triggers: backplane-buy, manufacturing-review, fab-spec, freecad, kicad-sim, kicad-ipc. - Detect projects containing both Altium (.PrjPcb) and KiCad (.kicad_pro) files and emit guidance for both with clear canonical and per-tool scoping. - Make KiStack the default skill set for KiCad work (and CAD rules in Altium). - Update golden prompt fixture and unit tests; remove obsolete gen_prompt.py. --- deploy/skills/backplane-buy/SKILL.md | 14 ++ deploy/skills/fab-spec/SKILL.md | 32 +++ deploy/skills/freecad/SKILL.md | 18 ++ deploy/skills/kicad-ipc/SKILL.md | 12 + deploy/skills/kicad-sim/SKILL.md | 8 + deploy/skills/manufacturing-review/SKILL.md | 8 + native/host/src/agents/bundled.rs | 11 +- native/host/src/agents/inputs.rs | 58 +---- native/host/src/agents/mod.rs | 4 +- native/host/src/agents/prompt.rs | 240 +++++++++++--------- native/host/src/agents/prompt_text.rs | 31 +-- native/host/src/agents/tests.rs | 2 +- native/host/src/kicad/ipc.rs | 14 -- native/host/src/settings/fab.rs | 12 +- test/agents/fixtures/argv-default.json | 22 +- test/agents/gen_prompt.py | 49 ---- 16 files changed, 282 insertions(+), 253 deletions(-) create mode 100644 deploy/skills/backplane-buy/SKILL.md create mode 100644 deploy/skills/fab-spec/SKILL.md create mode 100644 deploy/skills/freecad/SKILL.md create mode 100644 deploy/skills/kicad-ipc/SKILL.md create mode 100644 deploy/skills/kicad-sim/SKILL.md create mode 100644 deploy/skills/manufacturing-review/SKILL.md delete mode 100644 test/agents/gen_prompt.py diff --git a/deploy/skills/backplane-buy/SKILL.md b/deploy/skills/backplane-buy/SKILL.md new file mode 100644 index 0000000000..43ff756abe --- /dev/null +++ b/deploy/skills/backplane-buy/SKILL.md @@ -0,0 +1,14 @@ +--- +name: backplane-buy +description: "Follow when Backplane opens a Buy it thread to prepare and quote an order." +--- + +# backplane-buy + +This thread orders the project's parts; the person pressed Buy it. Be brief: short messages, a small table at most, no walls of text. Steps: +1. Read `.backplane/intent.md` and every `*.fab.json` (find . -name '*.fab.json' -not -path './extra/*' -not -path './mfg/*'). If a board or part to order has none yet, write it first, measured using the bundled fab-spec skill, and say so in a line. Then let the person choose what to order: call `order_ask` with `pick` true, the question "What should this order include?" and one option per board or part (its name, what it is and the quantity, e.g. "Main board · 4-layer PCB · 5"), all of them, and end your turn. Backplane shows them as a list they untick and may add parts to. Their answer says what to order, what to leave out and anything they added: order only what they kept; for a part they added, find it in the project, write its fab.json as above and say so in a line; if you cannot find it, ask with `order_ask`. +2. Call the backplane tool `order_review` with action "gate". When the review is current and passed it says so: go on. Otherwise Backplane itself tells the person where the review stands (the issues as a list, with the link to `.backplane/review.md`) and asks them; end your turn, and their answer comes as their next message: "Review for manufacturing": call delegate_task with the prompt "Review this project for manufacturing." (the task works in this thread's folder, on the very files to be ordered, and its result comes back here), say in one line that it runs as a task of this thread and the order goes on when it's done, and end your turn; when its result comes, call the gate again. "Fix them first": delegate_task again with the exact changes `.backplane/review.md` asks for (in this folder, so the order gets them), and once that is done the review once more, then the gate. "Order without a review" or "Order anyway": go on. Export nothing until the gate passes or the person says to order anyway. Never review or change the design yourself here; this thread only orders. +3. Ask only what is missing, one question at a time with the backplane tool `order_ask` (it never waits: end your turn after each, and the answer comes as the person's next message), never in plain words in your reply: Backplane shows each question in its own card above the message box. Questions with choices get two to four short ones, the likely one first: quantities, and for each rigid board (kind pcb) whether it comes assembled or bare; other board kinds come bare. Where it ships is typed: `order_ask` with the question "Ship to which country?", `typed` true and no options, so the person gets a box to type it in; when an earlier order's `mfg/*/manifest.json` exists, add `last` with its country's name (it shows as a quick choice). Use the country's two-letter ISO code as ship_to. A region (EU, Europe, Asia) is not a country: ask which country. When it ships to the US, ask the state the same way next (its sales tax is in the quote): `order_ask` with the question "Ship to which US state?", `typed` true and no options, and `last` with the earlier order's state when it shipped to the US; use the state's two-letter code (GA, WA) as ship_region. When an earlier order exists, offer its answers first (its quantities and assembly as choices, its country as `last`) and skip what still holds. Boards come in at least 5 and assembly starts at 2 boards (any number up to the quantity). Bare boards can come with a BOM they order parts with themselves (by manufacturer part number at any distributor). +4. Export from the saved files (a fix made through `kicad_ipc` counts once saved with SaveDocument) into `mfg//`: for each board `/gerbers/` (kicad-cli pcb export gerbers, and kicad-cli pcb export drill with Excellon, mm, PTH and NPTH in separate files, into the same folder), and when it is assembled `/bom.csv` (columns Designator, Quantity, Value, Footprint, MPN, Manufacturer, and LCSC when known; one line per part number) and `/positions.csv` (kicad-cli pcb export pos --format csv --units mm --side both; columns Designator, Mid X, Mid Y, Rotation, Layer); for each mechanical part `/.step`, and for sheet metal also its flat pattern `/.dxf`. Then write `manifest.json` there: {"spec": 1, "title": "", "ship_to": "US", "ship_region": "", "parts": [{"name" (its fab.json name, e.g. Main board), "kind", "qty", "options", "features" (sheet metal: its bends), "files": {"gerbers": "/gerbers", "bom", "positions"} or {"step", "dxf"}, "assemble": }], "files": {"": ""}}, listing every file (sha256sum). +5. Call the backplane tool `order_quote` with the folder (`mfg/<...>`) and end your turn: Backplane shows the person every file it would send and asks them first. Once they send, the files go to the order server and the quote is made (usually 1-2 minutes); meanwhile the thread shows that the quote is on its way. Backplane then posts it with its Buy now link (it opens Stripe) in this thread and you get a message with its total; do not repeat its table. Say in a line or two what it covers, and if it lists problems, what fixes each. If the person writes before the quote comes, call `order_status`: it says whether the files were sent and the quote is being made; never ask them to send or approve again unless it says the files were not sent, and never guess at problems. +Only order_quote ever sends anything: never upload files or contact a manufacturer yourself. The person never deals with the fab: there is no fab website, account or preview for them, so never ask them to check anything there; check what can be checked here (the exported files, the positions file, the renders) and say what you checked. Prices are estimates until paid; the person can always take the mfg folder to any manufacturer themselves. Never name the manufacturer. diff --git a/deploy/skills/fab-spec/SKILL.md b/deploy/skills/fab-spec/SKILL.md new file mode 100644 index 0000000000..f8d4637ab9 --- /dev/null +++ b/deploy/skills/fab-spec/SKILL.md @@ -0,0 +1,32 @@ +--- +name: fab-spec +description: "Use when creating, measuring, or updating a part's .fab.json for fabrication." +--- + +# fab-spec + +Each thing to be ordered has a `.fab.json` beside it (a board's in its folder, a part's beside its STEP in mech/): {"kind": "pcb" | "flex" | "hdi" | "aluminum" | "copper_core" | "rogers" | "ptfe" | "3dp" | "cnc" | "sheetmetal", "name": "Main board", "source": "", "qty": 5, "options": {...}, "features": {...}}; add "order": false for one not to be ordered. Features are measured, never guessed, and kept current whenever the design changes, because Backplane shows the person a price from them: a board's `width_mm` and `height_mm` (its Edge.Cuts box) and `min_drill_mm` (its smallest plated hole, usually a via); a solid's `volume_cm3`, `area_cm2`, `size_x_mm`, `size_y_mm`, `size_z_mm` (FreeCAD: shape.Volume/1000, shape.Area/100, the tightest box, largest first); a sheet part's `flat_x_mm`, `flat_y_mm`, `cut_length_mm`, `holes`, `bends`, `countersinks` (its flat pattern; the last four default to 0). Boards come in kinds: pcb is a rigid FR-4 board; flex a flexible polyimide one; hdi one with microvias and build-up layers; aluminum and copper_core single-layer metal-core boards (LEDs, power); rogers (RO4350B) and ptfe two-layer high-frequency boards. Every board kind is measured and exported the same way; only pcb boards come assembled. + +## Options + +Omitted options take the first value. + +- pcb: layers 1|2|4|6|8|10|12|14|16 (default 2), thickness_mm 1.6|0.4|0.6|0.8|1.0|1.2|2.0, color green|black|white|blue|red|yellow|purple, finish hasl|hasl_lead_free|enig|osp, copper_oz 1|2, castellated, gold_fingers + +- flex: layers 2|1|4, thickness_mm (the total, which sets the substrate and copper; 1 layer: 0.07|0.11|0.12|0.14, 2 layers: 0.11|0.12|0.19|0.2|0.24, 4 layers: 0.2|0.25|0.3|0.35|0.45; left out, the first for its layers), coverlay yellow|black|white, stiffener none|polyimide_0.1|polyimide_0.15|polyimide_0.2|polyimide_0.225|polyimide_0.25|fr4_0.1|fr4_0.2|fr4_0.4|fr4_0.6|fr4_0.8|fr4_1.0|fr4_1.2|fr4_1.6|steel_0.1|steel_0.2|steel_0.3|tape_3m468|tape_tesa8854|tape_3m9077 (mm), emi_shield none|one_side|both_sides, gold_uin 1|2 (its ENIG gold), gold_fingers + +- hdi: layers 4|6|8|10|12|14|16, thickness_mm 1.6 (0.6|0.8|1.0|1.2|1.4|1.6|1.8|2.0|2.5|3.0 as the layers allow), steps 1|2|3 (build-up steps: 1 at 4 layers, up to 2 at 6, up to 3 from 8), laminate np175f|s1000_2m (only s1000_2m from 8 layers), color as pcb, finish hasl|hasl_lead_free|enig|osp (only enig|osp from 6 layers), via_fill plugged|untented|epoxy_filled|copper_filled (only epoxy_filled from 6 layers), castellated, gold_fingers, edge_plating + +- aluminum: thickness_mm 1.6|0.8|1.0|1.2, color white|black, finish hasl|hasl_lead_free + +- copper_core: thickness_mm 1.6|1.0|1.2, color white|black (OSP) + +- rogers: thickness_mm 0.51|0.76|1.52, color green|purple, finish enig|osp, gold_uin 1|2, via_fill tented|untented + +- ptfe: thickness_mm 0.76|1.52, laminate dk2.94|dk3.0|dk2.65|dk2.55 (its dielectric constant), finish enig|osp, gold_uin 1|2, via_fill tented|untented + +- 3dp: process mjf|sla|sls|fdm|slm, material (mjf: pa12|pa11|pa12_glass; sla: standard_resin|black_resin|tough_resin|high_temp_resin|clear_resin; sls: pa12|pa12_glass; fdm: abs|asa|pla|tpu|pa12_cf|pc_abs|peek; slm: stainless_316l|titanium), color, which the material decides (mjf pa12 and pa11: black|gray, pa12_glass: black|white; sla standard_resin: white, black_resin: black, tough_resin: green, high_temp_resin: yellow, clear_resin: translucent|transparent; sls pa12: black, pa12_glass: white; fdm abs and asa: black|white, pla: black|white|red|blue, tpu: black|white|gray|translucent|green, pa12_cf and pc_abs: black, peek: brown; slm: metal) + +- cnc: material aluminum_6061|aluminum_7075|stainless_304|steel_45|steel_q235|brass|copper|abs_black|abs_white|pom_black|pom_white|pmma|nylon|polycarbonate|fr4, finish none|anodize|bead_blast|bead_blast_anodize|hard_anodize|conductive_anodize|brushed|brushed_anodize|laser_mark, tolerance standard|0.1|0.05|0.02 + +- sheetmetal: material aluminum_5052|stainless_304|stainless_201|steel_cold_rolled|steel_galvanized, thickness_mm (0.5 to 6), finish none|powder_coat|anodize|conductive_anodize|hard_anodize. diff --git a/deploy/skills/freecad/SKILL.md b/deploy/skills/freecad/SKILL.md new file mode 100644 index 0000000000..a717241a44 --- /dev/null +++ b/deploy/skills/freecad/SKILL.md @@ -0,0 +1,18 @@ +--- +name: freecad +description: "Use for mechanical modeling, STEP export, assemblies, and fit checks in FreeCAD." +--- + +# freecad + +Model with FreeCAD. Each part is one script in the project's `mech/` folder with its dimensions as named parameters at the top, in millimetres, Z up, the part's front facing -Y; it checks `shape.isValid()`, saves `mech/.FCStd` and exports `mech/.step`. + +An assembly is one more script that places the parts and exports one STEP. Give every part a colour that reads as what it is (a printed housing, aluminium, rubber, the board's green): STEP files keep colours only when FreeCAD's GUI writes them, so run the script with the GUI offscreen (no window opens): `QT_QPA_PLATFORM=offscreen timeout 300 "" mech/.py`. In it, after `doc.recompute()`, set each object's `ViewObject.ShapeColor = (r, g, b)` (0 to 1), export with `ImportGui.export(objects, 'mech/.step')`, write any messages to a log file (the GUI's output is not shown), and end with `os._exit(0)` or it keeps running. + +Bring a board or vendor STEP into an assembly with `ImportGui.insert` so its colours stay. Before the first `ImportGui.insert`, run `App.ParamGet("User parameter:BaseApp/Preferences/Mod/Import").SetInt("ImportMode", 0)` (in memory only: nothing is saved): a person's Import mode of 2 makes `ImportGui.insert` wait forever offscreen. + +The console build, `"" -c "exec(open('mech/.py').read())"`, is quicker for checking geometry but writes STEP without colours. + +Use the GUI and console paths reported in the system prompt. Clear DISPLAY and WAYLAND_DISPLAY on graphical Linux shells before launching offscreen. Inspect the script log and check that the saved files exist before opening the STEP with `viewer_show` (kind `mech`). + +If you need a static check, run the selected Backplane renderer with `--render mech/a.step mech/b.step`. Inspect the isometric image first in `mech/renders/`, which also contains front, top and right views. Report renderer errors. For a fit check, export the KiCad board with `kicad-cli pcb export step --board-only` unless component heights matter. diff --git a/deploy/skills/kicad-ipc/SKILL.md b/deploy/skills/kicad-ipc/SKILL.md new file mode 100644 index 0000000000..725427591e --- /dev/null +++ b/deploy/skills/kicad-ipc/SKILL.md @@ -0,0 +1,12 @@ +--- +name: kicad-ipc +description: "Read only when kicad_edit lacks a required operation and raw KiCad IPC is needed." +--- + +# kicad-ipc + +- Call `kicad_ipc_status` for the installed API, capabilities and command names. Send one command at a time with `kicad_ipc {path, type, message}`. Short types like `GetItems` work. The hub opens the document and manages its named lock. +- Target explicit item IDs. Headless editors have no selection or view state. Wrap mutations in `BeginCommit` and `EndCommit`, then `SaveDocument` at each milestone. Use `EndCommit` with `CMA_DROP` to discard an unfinished commit. Check `GetNotices` after a deferred change. +- If the runtime lacks `footprint-partial-update`, send the full FootprintInstance. If it lacks `symbol-from-libid`, use `LoadAllLibraries`, `GetLibraryStatuses`, then `PlaceSymbolFromLibrary`. +- With `runaction-frame`, set `RunAction.frame` to `FT_SCHEMATIC_EDITOR` or `FT_PCB_EDITOR` for actions shared by both editors, including undo and redo. Older builds can send a shared action to the board editor while it is open. +- Use the hub's IPC connection. If IPC is unavailable, report the tool's reason and follow its supported recovery. Direct file writes are forbidden while KiCad has the project open. diff --git a/deploy/skills/kicad-sim/SKILL.md b/deploy/skills/kicad-sim/SKILL.md new file mode 100644 index 0000000000..0a6dc19a43 --- /dev/null +++ b/deploy/skills/kicad-sim/SKILL.md @@ -0,0 +1,8 @@ +--- +name: kicad-sim +description: "Use for schematic simulation when the selected KiCad runtime exposes sim-run." +--- + +# kicad-sim + +Simulate with the backplane MCP tool `kicad_sim` {path, ops} (KiCad's simulator, ngspice): one call opens the schematic, runs its ops in order and answers numbers. Start with `models` (what would not simulate and why), settle each part with `model`, `exclude` or `import`, add `source`s, then `run` an analysis with the `measures` you need (corner, phase_margin, overshoot, ripple, settling_time and the rest are computed for you: never ask for whole waveforms to measure them yourself), `sweep` a value for a table and `tune` it to a target. Give a whole step as one call. The schematic is the real one, set up as KiCad's Simulator needs it, so the person can open the Simulation tab on the same set-up; sweeps and tunes change nothing unless you ask to write. A part without a model: find its maker's SPICE model by MPN on the maker's own site and give it with `import` (it is kept in the project's sim/models/ with its source and licence line). When the maker has none, or getting it needs a login, a licence acceptance or a purchase, stop and ask the person, naming the part and what you found; never substitute a generic or similar part's model without their word. Never run ngspice or kicad-cli yourself for a simulation, and never write Sim.* fields into the file. diff --git a/deploy/skills/manufacturing-review/SKILL.md b/deploy/skills/manufacturing-review/SKILL.md new file mode 100644 index 0000000000..aafdfb66a5 --- /dev/null +++ b/deploy/skills/manufacturing-review/SKILL.md @@ -0,0 +1,8 @@ +--- +name: manufacturing-review +description: "Follow when asked to review a project for manufacturing or order readiness." +--- + +# manufacturing-review + +When asked to review the project for manufacturing, check what makes a fab ask questions or refuse, not the circuit: DRC against the fab's limits, taken from the backplane tool `fab_profile` (the project's fab, board kind and options: each limit with its source and date), never from memory; `fab_profile` with action "drc" puts them in the project's DRC rules (tracks and gaps, vias, rings, hole and edge clearances, silkscreen: a value under a limit's free value but within the one that costs more is fine but costs more, so say so rather than calling it an error; under both, it must change; where Backplane recommends more than the fab's limit, a design between the two is a note, not a must-change, "meets the fab's 0.2 mm, under the recommended 0.3 mm": fab_profile gives Backplane's recommended value with each limit it has one for, as `recommended`), every BOM line has a manufacturer part number that is in stock (pcbparts tools; prefer basic/preferred parts, name extended ones), parts on one side for the cheaper assembly, footprint rotations sane, an outline that is closed, every part to order has a current fab file; for printed parts walls 1 mm or more (0.8 for SLA), for sheet metal flanges at least 4x the thickness and holes at least the thickness from a bend, for CNC inside corners with radii of 1 mm or more and no undercuts. A part whose fab file has a `sendcutsend` block is made for SendCutSend: check it with the sendcutsend skill (`scs.py dfm `, against SendCutSend's live specs), give each failed rule with its source, and call the check stale when the part file no longer matches its `dfm.source_sha256`. Run every check in the foreground (no background commands, monitors or waits) and keep each one short. Start with the backplane tool `design_review` (scope "order"): its findings are the deterministic part; then `design_review` with scope "judged" and record your datasheet checks with `design_review_judged`. Write the findings to `.backplane/review.md` (per part: what is fine, what must change and why), then call the backplane tool `order_review` with action "record", verdict "ok" when nothing must change or "issues", a one-line summary and issues: what must change, one short line each ("Shade: walls 0.6 mm, need 0.8 for SLA"). Your last message is what the thread that asked hears: make it that list and the link `.backplane/review.md`, then end. Change nothing while reviewing: say what must change; the person decides. Call the manufacturer "the fab", never by name, except SendCutSend for the parts made for it. diff --git a/native/host/src/agents/bundled.rs b/native/host/src/agents/bundled.rs index 7f0453ca84..1b7745fd4b 100644 --- a/native/host/src/agents/bundled.rs +++ b/native/host/src/agents/bundled.rs @@ -10,6 +10,12 @@ const MANIFEST: &str = "{\"name\":\"backplane\",\"description\":\"Backplane's ow /// (path under `/bundled`, contents) pub const FILES: &[(&str, &str)] = &[ + ("skills/backplane-buy/SKILL.md", include_str!("../../../../deploy/skills/backplane-buy/SKILL.md")), + ("skills/manufacturing-review/SKILL.md", include_str!("../../../../deploy/skills/manufacturing-review/SKILL.md")), + ("skills/fab-spec/SKILL.md", include_str!("../../../../deploy/skills/fab-spec/SKILL.md")), + ("skills/kicad-sim/SKILL.md", include_str!("../../../../deploy/skills/kicad-sim/SKILL.md")), + ("skills/freecad/SKILL.md", include_str!("../../../../deploy/skills/freecad/SKILL.md")), + ("skills/kicad-ipc/SKILL.md", include_str!("../../../../deploy/skills/kicad-ipc/SKILL.md")), ("skills/sendcutsend/SKILL.md", include_str!("../../../../deploy/skills/sendcutsend/SKILL.md")), ("skills/sendcutsend/scripts/scs.py", include_str!("../../../../deploy/skills/sendcutsend/scripts/scs.py")), ("skills/sendcutsend/scripts/scs_step.py", include_str!("../../../../deploy/skills/sendcutsend/scripts/scs_step.py")), @@ -112,7 +118,10 @@ mod tests { let t0 = std::fs::metadata(d.join("skills/sendcutsend/SKILL.md")).unwrap().modified().unwrap(); std::thread::sleep(std::time::Duration::from_millis(20)); install(&h).unwrap(); assert_eq!(std::fs::metadata(d.join("skills/sendcutsend/SKILL.md")).unwrap().modified().unwrap(), t0, "an unchanged file is not rewritten"); - let l = list(&d); assert_eq!(l.len(), 2); assert_eq!(l[0].0, "sendcutsend"); assert_eq!(l[1].0, "altium"); assert!(l[1].1.contains("Altium")); assert!(l[0].1.contains("SendCutSend")); assert!(l[0].2.replace('\\', "/").ends_with("bundled/skills/sendcutsend/SKILL.md")); + let l = list(&d); for name in ["backplane-buy", "manufacturing-review", "fab-spec", "kicad-sim", "freecad", "kicad-ipc", "altium", "sendcutsend"] { + let (_, trigger, path) = l.iter().find(|s| s.0 == name).expect(name); + assert!(!trigger.is_empty() && Path::new(path).is_file(), "{name}"); + } let _ = std::fs::remove_dir_all(&h); } diff --git a/native/host/src/agents/inputs.rs b/native/host/src/agents/inputs.rs index 11ebb06c02..7a2360a411 100644 --- a/native/host/src/agents/inputs.rs +++ b/native/host/src/agents/inputs.rs @@ -1,51 +1,7 @@ -//! What a message and a project give an agent besides the prompt: the project's KiCad files, -//! skills and `$skill` mentions, and attached images. +//! What a message and a project give an agent besides the prompt: skills, `$skill` mentions, and attached images. use serde_json::{json, Value}; use std::path::{Path, PathBuf}; -// ---- KiCad project files ---- -#[derive(Clone, Debug, Default, PartialEq)] -pub struct Files { pub pro: String, pub pcb: String, pub sch: String, pub all: String } - -/// A folder's name that says it holds copies. -fn copies(c: &str) -> bool { - let l = c.to_lowercase(); - l.starts_with("archive") || l.starts_with("build") || l.contains("backup") || l == "old" || l == "out" || l.starts_with("output") || l == "tmp" || l == "temp" || l == "staging" || l == "scratch" || l == "renders" || l.starts_with("export") -} -fn walk(root: &Path, rel: &str, depth: usize, out: &mut Vec) { - let Ok(rd) = std::fs::read_dir(root.join(rel)) else { return }; - for e in rd.flatten() { - let name = e.file_name().to_string_lossy().into_owned(); let p = if rel.is_empty() { name.clone() } else { format!("{rel}/{name}") }; - let Ok(t) = e.file_type() else { continue }; - if t.is_dir() { if depth < 4 && !name.starts_with('.') && name != "node_modules" && !name.ends_with("-backups") { walk(root, &p, depth + 1, out) } } - else if name.ends_with(".kicad_pro") && depth >= 1 { out.push(p) } - } -} -/// Files.found: every .kicad_pro four folders deep, paths from the root, shallowest first, folders of copies after the rest, at most 50. -pub fn found(root: &Path) -> Vec { - let mut v = vec![]; walk(root, "", 1, &mut v); - let key = |p: &String| { let parts: Vec<&str> = p.split('/').collect(); let c = parts[..parts.len() - 1].iter().any(|d| copies(d)) as u8; (c, parts.len(), p.clone()) }; - v.sort_by_key(key); v.truncate(50); v -} -fn abs(root: &str, rel: &str) -> String { if rel.is_empty() { String::new() } else if crate::plat::fs::is_abs(rel) { rel.into() } else { format!("{root}/{rel}") } } -fn dir_of(p: &str) -> &str { p.rsplit_once('/').map_or("", |x| x.0) } -fn last(p: &str) -> &str { p.rsplit('/').next().unwrap_or(p) } -fn named(ns: &[String], stem: &str, ext: &str) -> String { let want = format!("{stem}{ext}"); if ns.contains(&want) { want } else { ns.iter().find(|n| n.ends_with(ext)).cloned().unwrap_or_default() } } -/// Files.read: `.backplane.json`'s project/pcb/schematic win; else the .kicad_pro in the root, else the shallowest found. -pub fn read(root: &str) -> Files { - let cfg: Value = std::fs::read_to_string(format!("{root}/.backplane.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null); - let g = |k: &str| cfg.get(k).and_then(Value::as_str).unwrap_or("").to_string(); - let names = |d: &str| -> Vec { let mut v: Vec = std::fs::read_dir(d).map(|r| r.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect()).unwrap_or_default(); v.sort(); v }; - let all = found(Path::new(root)); - let top = names(root).into_iter().find(|n| n.ends_with(".kicad_pro")).unwrap_or_default(); - let pro = if !g("project").is_empty() { g("project") } else if !top.is_empty() { top } else { all.first().cloned().unwrap_or_default() }; - let ns = names(&if dir_of(&pro).is_empty() { root.to_string() } else { abs(root, dir_of(&pro)) }); - let stem = last(&pro).strip_suffix(".kicad_pro").unwrap_or(last(&pro)).to_string(); - let inn = |d: &str, n: &str| if d.is_empty() || n.is_empty() { n.to_string() } else { format!("{d}/{n}") }; - let pick = |k: &str, ext: &str| abs(root, &if g(k).is_empty() { inn(dir_of(&pro), &named(&ns, &stem, ext)) } else { g(k) }); - Files { pro: abs(root, &pro), pcb: pick("pcb", ".kicad_pcb"), sch: pick("schematic", ".kicad_sch"), all: all.join("\n") } -} - // ---- skills ---- #[derive(Clone, Debug, PartialEq)] pub struct USkill { pub name: String, pub description: String, pub path: String, pub model: bool, pub user: bool } @@ -145,22 +101,10 @@ pub fn claude_line_p(text: &str, imgs: &[(String, String)], uuid: &str, now: boo mod tests { use super::*; fn tmp(n: &str) -> crate::plat::tmp::TempDir { crate::plat::tmp::dir(&format!("in-{n}")) } - fn touch(p: &Path) { std::fs::create_dir_all(p.parent().unwrap()).unwrap(); std::fs::write(p, "x").unwrap() } #[test] fn a_steering_line_carries_priority_now_and_a_plain_one_does_not() { let l: Value = serde_json::from_str(&claude_line_p("x", &[], "U", true)).unwrap(); assert_eq!(l["priority"], "now"); let l: Value = serde_json::from_str(&claude_line("x", &[], "U")).unwrap(); assert!(l.get("priority").is_none()); } - #[test] fn kicad_files_prefer_the_root_then_the_shallowest() { - let r = tmp("k1"); touch(&r.join("hw/a/a.kicad_pro")); touch(&r.join("hw/a/a.kicad_pcb")); touch(&r.join("hw/a/a.kicad_sch")); touch(&r.join("archive/old/z.kicad_pro")); touch(&r.join(".hidden/h.kicad_pro")); touch(&r.join("node_modules/n.kicad_pro")); - let f = read(r.to_str().unwrap()); let rs = r.to_str().unwrap(); - assert_eq!(f.pro, format!("{rs}/hw/a/a.kicad_pro")); assert_eq!(f.pcb, format!("{rs}/hw/a/a.kicad_pcb")); assert_eq!(f.sch, format!("{rs}/hw/a/a.kicad_sch")); assert_eq!(f.all, "hw/a/a.kicad_pro\narchive/old/z.kicad_pro"); - touch(&r.join("top.kicad_pro")); assert_eq!(read(rs).pro, format!("{rs}/top.kicad_pro")); - } - #[test] fn backplane_json_wins() { - let r = tmp("k2"); touch(&r.join("a/a.kicad_pro")); touch(&r.join("b/b.kicad_pro")); std::fs::write(r.join(".backplane.json"), r#"{"project":"b/b.kicad_pro","pcb":"b/x.kicad_pcb"}"#).unwrap(); - let f = read(r.to_str().unwrap()); assert!(f.pro.ends_with("b/b.kicad_pro") && f.pcb.ends_with("b/x.kicad_pcb")); assert_eq!(f.sch, ""); - } - #[test] fn none_found_is_empty() { assert_eq!(read(tmp("k3").to_str().unwrap()), Files { pro: "".into(), pcb: "".into(), sch: "".into(), all: "".into() }); } #[test] fn skills_read_their_frontmatter_including_folded_values() { let s = parse_skill("---\nname: pcb-review\ndescription: >\n Review a board\n with care.\nuser-invocable: false\n---\nbody", "dir", "/p"); assert_eq!((s.name.as_str(), s.description.as_str(), s.user, s.model), ("pcb-review", "Review a board with care.", false, true)); diff --git a/native/host/src/agents/mod.rs b/native/host/src/agents/mod.rs index cee632ba43..852a109d23 100644 --- a/native/host/src/agents/mod.rs +++ b/native/host/src/agents/mod.rs @@ -187,12 +187,12 @@ impl Agents { // KiCad's files are the main checkout's, even when this thread's folder is a worktree: // the agent is handed main's real paths, where its code goes, and each document's lock let main = crate::files::kicad::canonical::main_of(&root); - let f = inputs::read(&main); let keys_path = home.join("secrets/api.env"); + let cad = prompt::read_cad(&main); let f = cad.canonical; let keys_path = home.join("secrets/api.env"); let locks: Vec<(String, String)> = [&f.pcb, &f.sch].into_iter().filter(|d| !d.is_empty()).map(|d| (d.clone(), crate::files::kicad::canonical::doc_lock(d))).collect(); let design = if f.pcb.is_empty() && f.sch.is_empty() { String::new() } else { prompt::design_words(&main, code.as_ref().filter(|c| !c.0.is_empty()).map(|c| (c.0.as_str(), c.1.as_str())), &locks) }; let keys = prompt::api_keys(&keys_path.to_string_lossy(), &prompt::key_names(&std::fs::read_to_string(&keys_path).unwrap_or_default())) + &prompt::secrets(&crate::settings::vault::names()); prompt::build(&prompt::PromptEnv { fc: crate::files::kicad::stepglb::told_freecad(&host.home, &host.fc), render: host.render.clone(), kicad: host.kicad.clone(), kicad_ipc: ipc, models: host.models_text(), may_delegate: true, orders_on: orders, routing_plan: plan, - root, pro: f.pro, pcb: f.pcb, sch: f.sch, all: f.all, design, keys, machines, buy, lang, skills: host.bundled.as_deref().map(bundled::list).unwrap_or_default(), kistack: host.kistack.as_deref().map(kistack::describe) }) + root: main, pro: f.pro, pcb: f.pcb, sch: f.sch, all: cad.kicad.join("\n"), altium_projects: cad.altium, design, keys, machines, buy, lang, skills: host.bundled.as_deref().map(bundled::list).unwrap_or_default(), kistack: host.kistack.as_deref().map(kistack::describe) }) }).await.unwrap_or_default() } /// PendingChanged: the number of open asks on a thread, written after an ask opens or closes (`extra` asks counted on top). diff --git a/native/host/src/agents/prompt.rs b/native/host/src/agents/prompt.rs index 4234729a61..17268c5e87 100644 --- a/native/host/src/agents/prompt.rs +++ b/native/host/src/agents/prompt.rs @@ -1,7 +1,4 @@ -//! What an agent is told: src/core/prompt's text assembly, with the -//! literals generated from source (prompt_text.rs, by test/agents/gen_prompt.py) so the words cannot drift. -//! The golden test compares the whole string with the argv the JS hub started a stand-in Claude with -//! (test/agents/fixtures/argv-default.json); names are kept on each fn. +//! Assemble Backplane’s system prompt from runtime facts and skill entry points. use super::prompt_text as T; /// What the host learned of KiCad: status ok|stock|old|broken|checking|missing, the CLI path, version, commit, why it broke. @@ -14,7 +11,7 @@ pub struct PromptEnv { pub fc: String, pub render: String, pub kicad: Kicad, pub kicad_ipc: bool, pub models: String, pub may_delegate: bool, pub orders_on: bool, /// The person turned on Plan before routing (plan/mod.rs `SETTING`). pub routing_plan: bool, - pub root: String, pub pro: String, pub pcb: String, pub sch: String, pub all: String, + pub root: String, pub pro: String, pub pcb: String, pub sch: String, pub all: String, pub altium_projects: Vec, /// Where this thread's design files and code go, and the document locks (`design_words`). pub design: String, pub keys: String, pub machines: String, pub buy: bool, pub lang: String, @@ -25,11 +22,11 @@ pub struct PromptEnv { } impl Default for PromptEnv { fn default() -> Self { PromptEnv { fc: String::new(), render: String::new(), kicad: Kicad { status: "missing".into(), ..Default::default() }, kicad_ipc: true, models: String::new(), may_delegate: true, orders_on: true, routing_plan: false, - root: String::new(), pro: String::new(), pcb: String::new(), sch: String::new(), all: String::new(), design: String::new(), keys: String::new(), machines: String::new(), buy: false, lang: String::new(), skills: vec![], kistack: None } } + root: String::new(), pro: String::new(), pcb: String::new(), sch: String::new(), all: String::new(), altium_projects: vec![], design: String::new(), keys: String::new(), machines: String::new(), buy: false, lang: String::new(), skills: vec![], kistack: None } } } /// Prompt.runtime -pub fn runtime(harness: &str) -> String { let r = T::PROMPT_RUNTIME; format!("{}{}{}{}{}{}", r[0], harness, r[1], r[2], r[3], T::PROMPT_BOARD[0]) } +pub fn runtime(harness: &str) -> String { let r = T::PROMPT_RUNTIME; format!("{}{}{}{}{}", r[0], harness, r[1], r[2], r[3]).trim_end().to_string() } /// Prompt.mech.gui: FreeCAD's GUI program beside its console one. pub fn mech_gui(fc: &str) -> String { @@ -39,33 +36,34 @@ pub fn mech_gui(fc: &str) -> String { } /// Prompt.mech pub fn mech(fc: &str, render: &str) -> String { - let (f, l, m) = (T::PROMPT_MECH_FREECAD, T::PROMPT_MECH_LOOP, T::PROMPT_MECH); - let free = if fc.is_empty() { f[0].to_string() } else { format!("{}{}{}{}{}", f[1], mech_gui(fc), f[2], fc, f[3]) }; - format!("{}{}{}{}{}{}", m[0], free, l[0], render, l[1], m[1]) + let setup = if fc.is_empty() { + "For tasks that require FreeCAD, tell the person it is missing and offer this link on its own line:\n[Open Settings › CAD](backplane://settings/cad)".to_string() + } else { + format!("FreeCAD GUI: `{}`. Console: `{fc}`.", mech_gui(fc)) + }; + let renderer = if render.is_empty() { String::new() } else { format!(" Optional renderer: `{render}` with `--render`.") }; + format!("\nFor mechanical work, use FreeCAD in `mech/` and follow the bundled `freecad` skill.\nShow the saved STEP with `viewer_show` (kind `mech`).{renderer}\n{setup}\n") } -/// Cfg.prompt: what the hub is configured with (Main.config) -pub fn config_prompt(fc: &str, render: &str) -> String { format!("{}\n\n{}", runtime("Backplane"), mech(fc, render)) } -/// Prompt.kicad.basics / fork / k / lead / health -fn kicad_basics(cli: &str) -> String { let b = T::PROMPT_KICAD_BASICS; let mut s = b[0].to_string(); for i in 1..7 { s += cli; s += b[i] } s } -fn kicad_fork(version: &str, commit: &str) -> String { let f = T::PROMPT_KICAD_FORK; format!("{}{}{}{}{}{}{}", f[0], version, f[1], commit, f[2], commit, f[3]) } -fn kicad_k(k: &Kicad, ipc: bool) -> String { - let t = T::PROMPT_KICAD_K; let fb = T::PROMPT_KICAD_FALLBACK[0]; - match (k.status.as_str(), ipc) { - ("ok", true) => kicad_fork(&k.version, &k.commit), - ("ok", false) => format!("{}{}{}{fb}", t[2], k.version, t[3]), - ("stock", _) => format!("{}{}{}{fb}", t[5], k.version, t[6]), - ("old", _) => format!("{}{}{}{}{}{fb}", t[8], k.version, t[9], min_version(), t[10]), - ("broken", _) => format!("{}{}{}{}{}{fb}", t[12], k.cli, t[13], why(&k.why), t[14]), - ("checking", _) => format!("{}{fb}", t[16]), - _ => format!("{}{fb}", t[17]), - } -} -/// KH.min_version / KH.why pub fn min_version() -> &'static str { "10.99.0-bp.4" } pub fn why(text: &str) -> String { text.lines().next().unwrap_or("").trim().chars().take(160).collect() } -fn kicad_lead(k: &Kicad) -> String { match k.status.as_str() { "missing" | "broken" | "checking" => format!("{}{}{}", T::PROMPT_KICAD_LEAD[1], k.cli, T::PROMPT_KICAD_LEAD[2]), _ => kicad_basics(&k.cli) } } -pub fn kicad(k: &Kicad, ipc: bool) -> String { let h = T::PROMPT_KICAD_HEALTH; format!("{}{}{}{}", h[0], kicad_lead(k), kicad_k(k, ipc), h[1]) } + +pub fn kicad(k: &Kicad, ipc: bool) -> String { + let status = match (k.status.as_str(), ipc) { + ("ok", true) => format!("Backplane KiCad {}. Start with `kicad_edit`. If it lacks an operation, read the bundled `kicad-ipc` skill and use `kicad_ipc_status` for live commands.", k.version), + ("ok", false) => "KiCad IPC is turned off. Enable it in Settings for document work.".into(), + ("stock", _) => "Install Backplane KiCad from Settings to use editing IPC.".into(), + ("old", _) => format!("Update Backplane KiCad from Settings for editing IPC (minimum {}).", min_version()), + ("broken", _) => format!("The selected KiCad CLI doesn't run ({}). Repair it in Settings.", why(&k.why)), + ("checking", _) => "Backplane is checking the KiCad runtime.".into(), + _ => "KiCad isn't installed. Install Backplane KiCad from Settings.".into(), + }; + let cli = match k.status.as_str() { + "ok" | "stock" | "old" => format!(" Use the selected CLI `{}` for exports and standalone ERC/DRC (`sch erc`, `pcb drc`). `kicad-cli` on your PATH and `$BACKPLANE_KICAD_CLI` select the same runtime.", k.cli), + _ => String::new(), + }; + format!("{status}{cli}") +} /// Prompt.path / project.k / projects / project fn path(label: &str, p: &str) -> String { if p.is_empty() { String::new() } else { let t = T::PROMPT_PATH; format!("{}{label}{}{p}{}", t[1], t[2], t[3]) } } @@ -74,7 +72,7 @@ pub fn project(root: &str, pro: &str, pcb: &str, sch: &str, all: &str) -> String pub fn project_locked(root: &str, pro: &str, pcb: &str, sch: &str, all: &str, design: &str) -> String { let (p, k, ps) = (T::PROMPT_PROJECT, T::PROMPT_PROJECT_K, T::PROMPT_PROJECTS); let held = if design.is_empty() { String::new() } else { format!(" {design}") }; - let body = if pcb.is_empty() && sch.is_empty() { k[0].to_string() } else { format!("{}{}{}{}{}{held}", k[1], path(&k[2], pro), path(&k[3], pcb), path(&k[4], sch), k[5]) }; + let body = if pro.is_empty() && pcb.is_empty() && sch.is_empty() { k[0].to_string() } else { format!("{}{}{}{}{}{held}", k[1], path(&k[2], pro), path(&k[3], pcb), path(&k[4], sch), k[5]) }; let ls: Vec<&str> = all.lines().collect(); let several = if ls.len() > 1 { let l = T::PROMPT_LIST; format!("{}{}{}", ps[0], ls.iter().map(|x| format!("{}{x}{}", l[1], l[2])).collect::(), ps[1]) } else { String::new() }; format!("{}{root}{}{body}{several}{}", p[0], p[1], p[2]) @@ -126,82 +124,126 @@ pub fn kistack_skills(c: &crate::agents::kistack::Copy) -> String { let l = T::PROMPT_SKILL_LINE; let which = if c.pinned { format!("pinned with this Backplane (KiStack commit {})", &c.rev[..12.min(c.rev.len())]) } else { format!("from BACKPLANE_KISTACK (KiStack {})", if c.rev.is_empty() { "of no recorded commit" } else { &c.rev }) }; let list = c.skills.iter().map(|(n, d, p)| format!("{}{n}{}{d}{}{p}{}", l[0], l[1], l[2], l[3])).collect::>().join("\n"); - format!("KiStack's KiCad skills, {which}, are in `{}`. Before design work one of them covers (schematics, symbols, footprints, layout, BOM, exports, Gerbers, panels, renders), read its SKILL.md completely and follow it, in KiCad or in another CAD tool such as Altium. Where your CLI lists them as skills of its own (Claude: `kistack:`, e.g. `kistack:kicad-schematic`), they are these same files. Use only these copies: any other copy of these skills on this machine (in ~/.agents/skills, ~/.claude/skills, ~/.codex/skills, ~/.skills or a project folder) is older and not to be used.\n{list}", c.dir) + format!("Use KiStack as the default skill set for KiCad work and apply its CAD design rules in Altium. Read the relevant SKILL.md before design work. This copy is {which} at `{}`.\n{list}", c.dir) } /// Where a hardware thread's work goes. `code`: its code worktree and branch when it works in the /// main checkout ("" for a thread still in an older worktree); `locks`: (document, its lock). pub fn design_words(main: &str, code: Option<(&str, &str)>, locks: &[(String, String)]) -> String { let ls = locks.iter().map(|(d, l)| format!("`{}`: `{l}`", d.rsplit('/').next().unwrap_or(d))).collect::>().join(", "); - let one = if ls.is_empty() { String::new() } else { format!(" Document locks ({ls}): a write through kicad_edit or kicad_ipc takes a free one by itself; call lock_acquire only when a tool says to (a direct file write, or to queue for a document another thread holds); while KiCad has the project open, edits through kicad_edit and kicad_ipc need none and land live beside the person's. Never ask the person to close KiCad or wait. Your document locks are released when your turn ends.") }; + let one = if ls.is_empty() { String::new() } else { format!(" Document locks ({ls}): Automatically acquired by IPC and released when your turn ends.") }; match code { Some((wt, branch)) => format!("Design files (KiCad boards, schematics, projects, symbol and footprint libraries, 3D models, mech/, mfg/, fab files) live in the main checkout, `{main}`, your working folder: edit them there. Backplane commits them straight to main at the end of each turn and on each SaveDocument, and pushes when main has an upstream. Code (firmware, src/, scripts, docs, build files) goes in your worktree `{wt}` on branch `{branch}`, never in the main checkout: cd there for code, which lands on main the normal way. That worktree has no design files.{one}"), None => format!("These live once, in the project's main checkout `{main}`: never edit a worktree copy of them; code stays in your worktree.{one}"), } } -/// An Altium Designer project (its .PrjPcb is the project's file): Altium's words replace KiCad's editing and runtime blocks. +/// Case-insensitive because Altium projects commonly use the .PrjPcb spelling. pub fn is_altium(pro: &str) -> bool { pro.to_ascii_lowercase().ends_with(".prjpcb") } -/// Prompt.altium: how an agent works on an Altium project (altium/live.rs; the bundled `altium` skill holds the verified recipes) -/// What an Altium thread reads before each kind of work: KiStack's skill for it, by its file (the skills are written for KiCad; their rules for how -/// a sheet, a symbol, a footprint and a board should look are the same in Altium). Without them the agent drew with the tools alone: a sheet -/// crammed into a corner with text over parts, a board with designators on top of each other. -pub fn altium_kistack(skills: &[(String, String, String)]) -> String { - let path = |n: &str| skills.iter().find(|s| s.0 == n).map(|s| format!("`{}`", s.2)); - let steps: Vec = [("a schematic sheet (placing, wiring, power and ground, labels)", &["kicad-schematic"][..]), ("a symbol", &["kicad-symbol"][..]), ("a footprint", &["kicad-footprint"][..]), ("placing or routing the board", &["layout-placement", "kicad-layout"][..])] - .iter().filter_map(|(what, names)| { let ps: Vec = names.iter().filter_map(|n| path(n)).collect(); (!ps.is_empty()).then(|| format!("before {what}, {}", ps.join(" and "))) }).collect(); - if steps.is_empty() { return " KiStack's skills (below) are written for KiCad: their design rules apply here too; do their steps with Altium's means.".into() } - format!(" How the design should look is KiStack's (below), not this block's: these tools only reach Altium. Read KiStack's skill for each step completely before you do it, even though it is written for KiCad: {}. Keep its rules (signal left to right, power ports up and ground down instead of labels for supplies, wires between nearby pins, parts spread over the sheet with no text over another, designators readable on the board) and do its steps with altium_write and altium_script instead of KiCad's tools; skip a KiCad-only step and say so. Then show the result with viewer_show and fix what that skill's checks would flag.", steps.join("; ")) + +pub struct CadProjects { + pub canonical: crate::files::kicad::project::Files, + pub kicad: Vec, + pub altium: Vec, } -pub fn altium(windows: bool, kistack: &[(String, String, String)]) -> String { + +pub fn read_cad(root: &str) -> CadProjects { + use crate::files::kicad::project; + let canonical = project::read(root); + let kicad = if project::is_altium(&canonical) { project::found(std::path::Path::new(root)) } else { canonical.all.clone() }; + let altium = project::altium_found(std::path::Path::new(root)); + CadProjects { canonical, kicad, altium } +} + +pub fn altium(windows: bool) -> String { let write = "New footprints (.PcbLib), symbols (.SchLib) and schematic sheets, and parts, wires, labels and power ports added to a sheet, are written with the backplane tool altium_write: a JSON spec, no Altium needed, the result read back."; let reach = if windows { format!("{write} Everything else goes through the person's running Altium Designer with the backplane tools altium_status (what Altium has open; call it first) and altium_script (a DelphiScript run inside Altium: Emit(S) prints a line; errors come back as results). If Altium is not running, either tool starts it and waits for it (about a minute): never ask the person to open Altium. Altium's own dialogs that a recipe opens are worked by the hub (BpExpect); any other box is left for the person and named in the result's `dialogs`: say what it is, and ask the person only when your script cannot avoid it. Before either, read the bundled `altium` skill's SKILL.md completely: its recipes are tested against Altium and show how to open a project and documents by path, read and edit schematics and boards, run ERC and DRC, and save.") } else { format!("{write} Read the bundled `altium` skill's SKILL.md first. Altium Designer itself runs on Windows and this hub is not on Windows, so altium_script cannot reach it here: board edits, ERC and DRC need Altium on a Windows machine; say so when a change needs it.") }; - format!("This is an Altium Designer project: its .PrjPcb lists the schematic sheets (.SchDoc) and the board (.PcbDoc); libraries are .SchLib/.PcbLib/.IntLib. These are binary files: never write them with scripts of your own or any other tool than altium_write, and never ask the person to close Altium. {reach} Address every document by its full path (never the focused document: the person may be working in another), wrap edits in PreProcess/PostProcess so the person can undo them in Altium, and save each document right after each change that matters (the ECO, placement, routing), before any other step: unsaved work is lost if a box or a closed document interrupts (Backplane's Board and Schematic viewers draw the saved files, and Backplane commits them to main at each turn's end); then show it with viewer_show. Update the board from the schematic yourself with the skill's pcb_update_from_sch.pas recipe: never ask the person to run Update PCB or redo any step a script can do; ask them only for what no script can reach, such as online part downloads. Keep each script small: inspect, change, verify by reading back. The KiCad tools (kicad_edit, kicad_ipc, kicad-cli) do not apply to this project.{ks}", ks = if kistack.is_empty() { String::new() } else { altium_kistack(kistack) }) + format!("Use Altium tools for .PrjPcb, .SchDoc and .PcbDoc files. The .PrjPcb lists the schematic sheets (.SchDoc) and the board (.PcbDoc); libraries are .SchLib/.PcbLib/.IntLib. These are binary files: never write them with scripts of your own or any other tool than altium_write, and never ask the person to close Altium. {reach} Address every document by its full path (never the focused document: the person may be working in another), wrap edits in PreProcess/PostProcess so the person can undo them in Altium, and save each document right after each change that matters (the ECO, placement, routing), before any other step: unsaved work is lost if a box or a closed document interrupts (Backplane's Board and Schematic viewers draw the saved files, and Backplane commits them to main at each turn's end); then show it with viewer_show. Update the board from the schematic yourself with the skill's pcb_update_from_sch.pas recipe: never ask the person to run Update PCB or redo any step a script can do; ask them only for what no script can reach, such as online part downloads. Keep each script small: inspect, change, verify by reading back. ") } /// Hub.prompt.base then Prompt.lang.add pub fn build(e: &PromptEnv) -> String { - let orch = orchestration(e.may_delegate, &e.models); - let alt = is_altium(&e.pro); - let has_kistack = e.kistack.as_ref().is_some_and(|k| !k.skills.is_empty()); - let orch = match &e.kistack { Some(k) if !k.skills.is_empty() => orch, _ => orch.replace(" (KiStack's KiCad skills and the person's)", " (the person's)") }; // KiStack is claimed only when the agent has it - let base = if alt { config_prompt(&e.fc, &e.render).replace(T::PROMPT_BOARD[0], "") } else { config_prompt(&e.fc, &e.render) }; - let ks: &[(String, String, String)] = match &e.kistack { Some(k) if has_kistack => &k.skills, _ => &[] }; - let cad = if alt { altium(cfg!(windows), ks) } else { kicad(&e.kicad, e.kicad_ipc) }; - let mut s = [base, cad, project_locked(&e.root, &e.pro, &e.pcb, &e.sch, &e.all, &e.design), orch, background().to_string(), order_project(e.orders_on)].join("\n\n"); + let canonical_altium = is_altium(&e.pro); + let alt = canonical_altium || !e.altium_projects.is_empty(); + let kicad_board = e.pcb.ends_with(".kicad_pcb"); + let kicad_schematic = e.sch.ends_with(".kicad_sch"); + let has_kicad = !alt || !e.all.is_empty() || e.pro.ends_with(".kicad_pro") || kicad_board || kicad_schematic; + + let mut blocks = vec![runtime("Backplane")]; + if has_kicad { blocks.push(T::PROMPT_BOARD[0].into()); } + blocks.push(mech(&e.fc, &e.render)); + if has_kicad { blocks.push(kicad(&e.kicad, e.kicad_ipc)); } + if alt { + blocks.push(altium(cfg!(windows))); + let canonical = if canonical_altium { + format!(" Canonical project: `{}` (Altium).{}{}", e.pro, path("board", &e.pcb), path("schematic", &e.sch)) + } else { String::new() }; + let files = e.altium_projects.iter().map(|p| format!("`{p}`")).collect::>().join(", "); + let files = if files.is_empty() { String::new() } else { format!(" Altium project files: {files}.") }; + blocks.push(format!("Main checkout: `{}`.{canonical}{files}{}", e.root, + if has_kicad { " Use KiCad tools for .kicad_* files and Altium tools for .PrjPcb, .SchDoc and .PcbDoc files." } else { "" })); + } + if has_kicad && !canonical_altium { + blocks.push(project_locked(&e.root, &e.pro, &e.pcb, &e.sch, &e.all, &e.design)); + } else if has_kicad && !e.all.is_empty() { + blocks.push(format!("Additional KiCad project files (relative to the main checkout):\n{}", e.all)); + } + blocks.extend([orchestration(e.may_delegate, &e.models), background().into(), order_project(e.orders_on)]); + let mut s = blocks.join("\n\n"); if let Some(k) = e.kistack.as_ref().filter(|k| !k.skills.is_empty()) { s += "\n\n"; s += &kistack_skills(k) } if !e.skills.is_empty() { s += "\n\n"; s += &bundled_skills(&e.skills) } if !e.keys.is_empty() { s += "\n\n"; s += &e.keys } if !e.machines.is_empty() { s += "\n\n"; s += &e.machines } - // a board on Backplane KiCad: plan before copper when the person turned it on, else route as asked (plan/mod.rs) - if !e.pcb.is_empty() && !alt && crate::plan::plans(&e.kicad.status, &e.kicad.version, &crate::files::kicad::ipc::read_runtime(std::path::Path::new(&e.kicad.cli)).caps) { s += "\n\n"; s += &if e.routing_plan { crate::plan::guidance() } else { crate::plan::guidance_off().to_string() } } - // RunAction's target editor (bp.13 batch 6, runaction-frame): what an agent's kicad_ipc may name, or where a shared action goes without it - if e.kicad.status == "ok" && e.kicad_ipc && !alt { s += "\n\n"; s += crate::files::kicad::ipc::runaction_guidance(&crate::files::kicad::ipc::read_runtime(std::path::Path::new(&e.kicad.cli)).caps) } - // simulation, where the runtime has it (kicad/ksim.rs) - if e.kicad.status == "ok" && e.kicad_ipc && !e.sch.is_empty() && !alt && crate::files::kicad::ipc::read_runtime(std::path::Path::new(&e.kicad.cli)).caps.iter().any(|c| c == crate::files::kicad::ksim::CAP) { s += "\n\n"; s += T::PROMPT_SIM } - if e.buy { s += "\n\n"; s += &T::ORDER_PROMPT_BUY.concat() } // every piece: the opening line alone ([0]) left a buy thread without its steps + if has_kicad && e.kicad.status == "ok" && e.kicad_ipc { + let runtime = crate::files::kicad::ipc::read_runtime(std::path::Path::new(&e.kicad.cli)); + if kicad_board && crate::plan::plans(&e.kicad.status, &e.kicad.version, &runtime.caps) { + s += "\n\n"; + s += &if e.routing_plan { crate::plan::guidance() } else { crate::plan::guidance_off().to_string() }; + } + if kicad_schematic && runtime.caps.iter().any(|c| c == crate::files::kicad::ksim::CAP) { + s += "\n\n"; + s += T::PROMPT_SIM; + } + } + if e.buy { s += "\n\n"; s += T::ORDER_PROMPT_BUY[0]; } let l = lang_line(&e.lang); if l.is_empty() { s } else { s + "\n" + l } } #[cfg(test)] pub(crate) mod tests { use super::*; - #[test] fn an_altium_project_gets_altiums_words_not_kicads() { - let mut e = PromptEnv::default(); e.root = "/p".into(); e.pro = "/p/Board.PrjPcb".into(); e.pcb = "/p/Board.PcbDoc".into(); e.sch = "/p/Top.SchDoc".into(); + #[test] fn mixed_cad_discovery_agrees_with_the_canonical_viewer() { + let r = crate::plat::tmp::dir("in-mixed-cad"); + let touch = |p: std::path::PathBuf| { std::fs::create_dir_all(p.parent().unwrap()).unwrap(); std::fs::write(p, "x").unwrap() }; + touch(r.join("boards/modern/Board.kicad_pro")); + touch(r.join("boards/modern/Board.kicad_pcb")); + touch(r.join("legacy/Board.PrjPcb")); + touch(r.join(".backplane/worktrees/shadow/Shadow.PrjPcb")); + let root = r.to_str().unwrap(); + let f = read_cad(root); + assert!(f.canonical.pro.ends_with("Board.kicad_pro")); + assert_eq!(f.kicad, ["boards/modern/Board.kicad_pro"]); + assert_eq!(f.altium, ["legacy/Board.PrjPcb"]); + std::fs::write(r.join(".backplane.json"), r#"{"project":"legacy/Board.PrjPcb"}"#).unwrap(); + let f = read_cad(root); + assert!(f.canonical.pro.ends_with("Board.PrjPcb")); + assert_eq!(f.kicad, ["boards/modern/Board.kicad_pro"]); + assert_eq!(f.altium, ["legacy/Board.PrjPcb"]); + } + #[test] fn cad_guidance_follows_the_project_formats() { + let mut e = PromptEnv { root: "/project".into(), pro: "/project/Board.PrjPcb".into(), pcb: "/project/Board.PcbDoc".into(), ..Default::default() }; let s = build(&e); - assert!(s.contains("") && !s.contains("") && !s.contains(""), "{s}"); - e.pro = "/p/b.kicad_pro".into(); let k = build(&e); - assert!(!k.contains("") && k.contains("")); - assert!(altium(true, &[]).contains("altium_script") && altium(false, &[]).contains("not on Windows") && altium(false, &[]).contains("altium_write")); - assert!(s.contains("pcb_update_from_sch.pas") && s.contains("never ask the person to run Update PCB") && s.contains("right after each change"), "{s}"); - assert!(s.contains("(kicad_edit, kicad_ipc, kicad-cli) do not apply") && !s.contains("") && !s.contains("KiStack"), "no copy, no claim"); - e.pro = "/p/Board.PrjPcb".into(); e.kistack = Some(crate::agents::kistack::Copy { dir: "/h/kistack".into(), rev: crate::agents::kistack::REV.into(), pinned: true, - skills: vec![("kicad-schematic".into(), "Draw schematics.".into(), "/h/kistack/skills/schematic/SKILL.md".into())] }); - let a = build(&e); - assert!(a.contains("") && a.contains("(KiStack's KiCad skills and the person's)") && a.contains("in KiCad or in another CAD tool such as Altium"), "{a}"); - // the Altium block names the schematic skill's file at the step it is for, and asks for it to be read first - let blk = &a[a.find("").unwrap()..a.find("").unwrap()]; - assert!(blk.contains("before a schematic sheet (placing, wiring, power and ground, labels), `/h/kistack/skills/schematic/SKILL.md`") && blk.contains("Read KiStack's skill for each step completely before you do it"), "{blk}"); - assert!(!blk.contains("before a footprint"), "a skill the copy lacks is not named"); - assert!(a.contains("") && !a.contains("") && !a.contains(""), "KiCad's tool blocks stay out"); + assert!(s.contains("") && !s.contains("")); + assert!(s.contains("Canonical project: `/project/Board.PrjPcb`")); + e.all = "boards/Board.kicad_pro".into(); + let s = build(&e); + assert!(s.contains("") && s.contains("")); + assert!(s.contains("Additional KiCad project files") && s.contains("Canonical project: `/project/Board.PrjPcb`")); + e.pro = "/project/boards/Board.kicad_pro".into(); + e.altium_projects = vec!["legacy/Board.PrjPcb".into()]; + let s = build(&e); + assert!(s.contains("") && s.contains("")); + assert!(s.contains("project: `/project/boards/Board.kicad_pro`") && s.contains("`legacy/Board.PrjPcb`")); + e.altium_projects.clear(); + assert!(!build(&e).contains("")); } const GOLD: &str = include_str!("../../../../test/agents/fixtures/argv-default.json"); pub fn gold() -> (String, serde_json::Value) { let a: Vec = serde_json::from_str(GOLD).unwrap(); let i = a.iter().position(|x| x == "--append-system-prompt").unwrap(); (a[i + 1].clone(), serde_json::json!(a)) } @@ -211,17 +253,17 @@ pub(crate) mod tests { models: "claude (fable, opus, sonnet, haiku); codex (gpt-6.1-sol, gpt-6-astra, gpt-6.1-terra, gpt-6-sol, gpt-6-luna, gpt-5.6-sol, gpt-5.6-terra, gpt-5.6-luna)".into(), root: "/home/h/Documents/i2cjak/backplane-gpui/build/gpui/results/agents/argv2/work/fixroot".into(), keys: secrets(&[]), ..Default::default() } } - #[test] fn the_prompt_equals_the_one_the_js_hub_gave_a_stand_in_claude() { + #[test] fn assembled_prompt_matches_the_golden_fixture() { let (want, _) = gold(); let got = build(&gold_env()); - if got != want { let i = got.chars().zip(want.chars()).position(|(a, b)| a != b).unwrap_or(got.len().min(want.len())); panic!("differs at {i} (rust {} chars, js {}):\nrust …{}\njs …{}", got.len(), want.len(), got.chars().skip(i.saturating_sub(40)).take(120).collect::(), want.chars().skip(i.saturating_sub(40)).take(120).collect::()) } + if got != want { let i = got.chars().zip(want.chars()).position(|(a, b)| a != b).unwrap_or(got.len().min(want.len())); panic!("differs at {i} (assembled {} bytes, fixture {}):\nassembled …{}\nfixture …{}", got.len(), want.len(), got.chars().skip(i.saturating_sub(40)).take(120).collect::(), want.chars().skip(i.saturating_sub(40)).take(120).collect::()) } } #[test] fn kicad_words_follow_the_status() { let k = |s: &str| Kicad { status: s.into(), cli: "/k".into(), version: "1".into(), commit: "abc".into(), why: "no\nmore".into() }; - assert!(kicad(&k("ok"), true).contains("blob/abc/BACKPLANE_IPC.md")); assert!(kicad(&k("ok"), false).contains("turned off")); assert!(kicad(&k("broken"), true).contains("doesn't run (no)")); + assert!(kicad(&k("ok"), true).contains("`kicad_ipc_status`")); assert!(kicad(&k("ok"), false).contains("turned off")); assert!(kicad(&k("broken"), true).contains("doesn't run (no)")); { let mut e = PromptEnv { pcb: "/p/b.kicad_pcb".into(), ..Default::default() }; e.kicad.status = "ok".into(); e.kicad.version = "10.99.0-bp.11".into(); assert!(build(&e).contains("")); assert!(build(&e).contains("Plan before routing is off") && !build(&e).contains("plan_approve"), "off unless the person turns it on: route as asked"); e.routing_plan = true; assert!(build(&e).contains("plan_approve") && !build(&e).contains("is off")); e.routing_plan = false; e.kicad.version = "10.99.0-bp.10".into(); assert!(!build(&e).contains(""), "the plan API came with bp.11"); e.kicad.status = "stock".into(); assert!(!build(&e).contains(""), "stock KiCad has no plan API"); } - assert!(kicad(&k("missing"), true).contains("isn't installed") && kicad(&k("missing"), true).starts_with("The selected KiCad CLI path is `/k`.")); assert!(kicad(&k("old"), true).contains(min_version())); + assert!(kicad(&k("missing"), true).contains("isn't installed")); assert!(kicad(&k("old"), true).contains(min_version())); } #[test] fn project_lists_the_files_it_has() { let p = project("/r", "a.kicad_pro", "a.kicad_pcb", "", "a.kicad_pro\nb/b.kicad_pro"); @@ -238,31 +280,25 @@ pub(crate) mod tests { let s = build(&e); assert!(s.contains("Backplane's own skills, for every agent whatever its provider: before work one of them covers, read its SKILL.md completely and follow it.\n- sendcutsend: Design parts for SendCutSend. Read \"/h/bundled/skills/sendcutsend/SKILL.md\""), "{s}"); assert!(!build(&gold_env()).contains("")); - assert!(order_project(true).contains("`sendcutsend` block") && !order_project(false).contains("sendcutsend"), "the review knows SendCutSend's check"); + assert!(order_project(true).contains("`manufacturing-review`")); } #[test] fn kistack_is_named_with_its_files_only_when_the_agent_has_it() { let e = gold_env(); let s = build(&e); - assert!(!s.contains("") && !s.contains("KiStack's KiCad skills and") && s.contains("the same skills as you (the person's)"), "no copy, no claim"); - let mut e = gold_env(); e.kistack = Some(crate::agents::kistack::Copy { dir: "/h/kistack".into(), rev: crate::agents::kistack::REV.into(), pinned: true, - skills: vec![("kicad-schematic".into(), "Draw schematics.".into(), "/h/kistack/skills/schematic/SKILL.md".into())] }); + assert!(!s.contains("")); + let mut e = e; + e.kistack = Some(crate::agents::kistack::Copy { dir: "/skills/kistack".into(), rev: crate::agents::kistack::REV.into(), pinned: true, + skills: vec![("kicad-schematic".into(), "Draw schematics.".into(), "/skills/kistack/schematic/SKILL.md".into())] }); let s = build(&e); - assert!(s.contains(&format!("KiStack's KiCad skills, pinned with this Backplane (KiStack commit {}), are in `/h/kistack`.", &crate::agents::kistack::REV[..12])), "{s}"); - assert!(s.contains("- kicad-schematic: Draw schematics. Read \"/h/kistack/skills/schematic/SKILL.md\"") && s.contains("is older and not to be used")); - assert!(s.contains("the same skills as you (KiStack's KiCad skills and the person's)")); - e.kistack.as_mut().unwrap().skills.clear(); assert!(!build(&e).contains(""), "an empty copy is no copy"); + assert!(s.contains("Use KiStack as the default skill set") && s.contains("/skills/kistack/schematic/SKILL.md")); } - #[test] fn language_and_buy_blocks_are_added_after() { let mut e = gold_env(); e.lang = "en".into(); e.buy = true; let s = build(&e); assert!(s.ends_with("Keep code, commands, paths and identifiers as they are.")); assert!(s.contains("")); e.lang = "es".into(); assert!(build(&e).contains("Reply in Spanish")); e.lang = "fr".into(); assert!(!build(&e).contains("Reply in")); } - /// e2e n1110: Buy it started a thread that exported Gerbers, guessed at a manifest and gave up ("I don't know the format it expects"): its prompt was the - /// block's opening line only. The whole block is there: the gate, the questions, the export layout, the quote and the closing rules. - #[test] fn a_buy_thread_gets_every_step_of_its_instructions() { - let mut e = gold_env(); e.buy = true; let s = build(&e); - let block = &s[s.find("").unwrap()..]; - assert!(block.ends_with(""), "the block is closed: {}", &block[block.len().saturating_sub(120)..]); - for step in ["1. Read `.backplane/intent.md`", "2. Call the backplane tool `order_review`", "3. Ask only what is missing", "`order_ask`", "4. Export from the saved files", "manifest.json", "5. Call the backplane tool `order_quote`", "Only order_quote ever sends anything"] { - assert!(block.contains(step), "the buy instructions have {step:?}"); - } - assert_eq!(block, T::ORDER_PROMPT_BUY.concat(), "the pieces in order, nothing between them (each ends its own line)"); - e.buy = false; assert!(!build(&e).contains(""), "only a buy thread has it"); + #[test] fn buy_workflow_is_loaded_on_demand() { + let mut e = gold_env(); + assert!(!build(&e).contains("")); + e.buy = true; + e.lang = "en".into(); + let s = build(&e); + assert!(s.contains(T::ORDER_PROMPT_BUY[0]) && !s.contains("manifest.json")); + assert!(s.ends_with("Keep code, commands, paths and identifiers as they are.")); } #[test] fn api_key_names_are_read_from_the_file_and_the_block_never_holds_a_value() { let names = key_names("# c\nOPENAI_API_KEY='sk-secret'\n\nbad name=1\n1X=2\nLONE\nGH_TOKEN='a=b'\n"); assert_eq!(names, ["OPENAI_API_KEY", "GH_TOKEN"]); diff --git a/native/host/src/agents/prompt_text.rs b/native/host/src/agents/prompt_text.rs index e04327d91b..0d7bd8d4e8 100644 --- a/native/host/src/agents/prompt_text.rs +++ b/native/host/src/agents/prompt_text.rs @@ -1,4 +1,4 @@ -// Generated by test/agents/gen_prompt.py from src/core/prompt, order, secret, apikeys. Do not edit. +// Static text for the agent system prompt. Assembly lives in prompt.rs. #![allow(dead_code)] pub const PROMPT_LANG_K: &[&str] = &["Reply in Japanese (日本語) unless the person writes in another language or asks otherwise. Keep code, commands, paths and identifiers as they are.", "Reply in English unless the person writes in another language or asks otherwise. Keep code, commands, paths and identifiers as they are.", ""]; @@ -9,38 +9,25 @@ pub const PROMPT_SKILL_LINE: &[&str] = &["- ", ": ", " Read \"", "\""]; pub const PROMPT_LINES: &[&str] = &[]; pub const PROMPT_SKILLS: &[&str] = &["\n"]; pub const PROMPT_BUNDLED: &[&str] = &["Backplane's own skills, for every agent whatever its provider: before work one of them covers, read its SKILL.md completely and follow it.\n", ""]; -pub const PROMPT_BOARD: &[&str] = &["KiCad always means main's canonical copy: the board/schematic named by the project's .backplane.json have exactly one real copy, in the project's main folder (its board and schematic sit beside the named .kicad_pro, in a subfolder like boards// as often as in the root) — never edit a thread worktree's copy, whatever thread you are in; your worktree holds code, firmware and docs only. Backplane routes kicad_ipc and its file tools to that canonical copy and commits design files to main at each turn's end and on each save. The person may be editing the same board or schematic in KiCad while you work, and other agents too: edit it live through kicad_edit (or kicad_ipc), which reach the open editor. Never ask the person to close KiCad, save, revert, stop editing or wait for you, and never write a .kicad_pcb, .kicad_sch, .kicad_pro or .kicad_dru file directly while KiCad has the project open: change design rules with kicad_edit's rule op (it adds, changes or removes rules by name and keeps everyone else's), net classes with its netclass op, and board setup through kicad_ipc. An update or delete answered ISC_DEFERRED or IDS_DEFERRED touches what the person is editing right now: it is applied when they finish, merged with their edit; GetNotices tells you how it went. Your edits land live, as the person's do, and they undo any of them from KiCad's Agents panel: never hold a batch of changes for the person to accept or review. Each live kicad_edit or kicad_ipc result may carry `person`: what the person selected and changed in KiCad in the last two minutes. When your next change touches those items or their area, ask the person first in one short question (\"I see you're in the RF switch area: want me to wait, or take U3?\") and carry on with other work meanwhile; otherwise just edit. Never start your own kicad-cli api-server or another KiCad on a project the person has open, and never edit its design files with scripts: kicad_edit and kicad_ipc are the one way in. A document's named lock is taken for you when your edit needs it and nobody holds it, and released when your turn ends; call lock_acquire only when a tool says to (a direct file write, or to queue for a document another thread holds). A parallel board experiment is an explicit, labelled copy, never a silent switch of the canonical one. For KiCad board and schematic work, keep those exact paths, including referenced schematic sheets. Save each meaningful milestone, INCLUDING unfinished work, to the exact edited document (kicad_edit saves by itself; after raw kicad_ipc edits send SaveDocument; a script's --save); never wait for only a final copy. Read back the saved path and show the canonical file with viewer_show then verify the viewer and history refer to that saved file; report any mismatch instead of assuming a save refreshed them. Preserve existing history and any .backplane.json companion metadata. Keep backups and intermediate outputs in a separate backup/build directory. If a tool writes a staging file, validate it and promote it back to the canonical path with a backup before continuing; never leave progress only in memory or silently switch the active filename. Use alternate boards/sheets only for an explicitly requested experiment, labeled clearly. Other agents may be editing the same document: keep your changes to what your task needs and re-read items before you change them."]; +pub const PROMPT_BOARD: &[&str] = &["\n- Use the named KiCad design in the main checkout, including referenced sheets. Use the canonical files by default. Backplane routes design tools there and commits saves to main. Use your thread worktree for code, firmware and docs. Create a labeled alternate board only for an experiment the person requests.\n- Always use IPC to inspect and edit KiCad documents. Start with `kicad_edit {path, ops}`: it batches operations into one commit, takes a free document lock, saves and returns the ERC/DRC delta. Use references and millimetres. Use `rule` and `netclass` for rules and net classes. Use raw `kicad_ipc` only for operations it lacks. Never write .kicad_pcb, .kicad_sch, .kicad_pro or .kicad_dru directly or through scripts while KiCad is open.\n- Edits land live and can be undone in KiCad’s Agents panel. Keep the person’s editor open. The result's `person` field shows selections and edits from the last two minutes. Ask before touching those items or their area and continue elsewhere meanwhile. `ISC_DEFERRED` and `IDS_DEFERRED` edits merge after the person finishes their edit. Check `GetNotices` for the result.\n- Backplane releases document locks when your turn ends. Call `lock_acquire` only when a tool directs you. Keep changes scoped and re-read shared items before changing them.\n- Save every meaningful milestone, including unfinished work. `kicad_edit` saves automatically. For raw IPC, send `SaveDocument`. Read back the saved path, open it with `viewer_show` and verify viewer and history match. Preserve companion .backplane.json metadata and report mismatches.\n"]; pub const PROMPT_RUNTIME: &[&str] = &["In case you're asked: you are running in Backplane through the ", " harness. Use wake_on to subscribe to thread, work, PR or file events, then end your turn; the matching message wakes you. No need to mention this otherwise. You can embed images and videos in your response using Markdown with absolute file paths.\n\n", "To show the user an image (a board render, plot, screenshot or photo), save it as PNG or JPEG and write its absolute path on its own, e.g. /home/h/x.png (no spaces in the path); it's drawn under your message. Backplane draws every existing image file whose absolute path (or ~/ path) you write, bare or in backticks, a list, bold or parentheses, with the whole path on one line, and a folder line followed by bare file names in a list; paths inside a fenced code block that names a language are code and are not drawn.\n\n", "Backplane hosts a web browser for you: the backplane MCP server's preview_* tools (preview_open, preview_navigate, preview_snapshot, preview_click, preview_type, preview_press, preview_scroll, preview_evaluate, preview_wait_for). The user watches it live in the app's Browser tab. Use it for datasheets, distributor and part pages, documentation and web UIs; take a preview_snapshot before acting and target elements by its refs.\n\n"]; -pub const PROMPT_MECH_GUI_POSIX: &[&str] = &["/Resources/bin/freecadcmd", "/MacOS/FreeCAD", "freecadcmd", "freecad", "FreeCADCmd", "FreeCAD"]; -pub const PROMPT_MECH_GUI: &[&str] = &["FreeCADCmd.exe", "freecadcmd.exe", "FreeCAD.exe"]; -pub const PROMPT_MECH_FREECAD: &[&str] = &["FreeCAD is not installed on this machine. When a task needs a part modelled, changed or exported, do not try to install it yourself: tell the user in one sentence that FreeCAD is missing, and put this link on a line of its own, exactly as written: [Open Settings › CAD](backplane://settings/cad). Backplane downloads FreeCAD there with one press, or takes the path of one they already have. Then stop and wait for them; meanwhile you can still render and inspect existing STEP files.", "Model with FreeCAD. Each part is one script in the project's `mech/` folder with its dimensions as named parameters at the top, in millimetres, Z up, the part's front facing -Y; it checks `shape.isValid()`, saves `mech/.FCStd` and exports `mech/.step`. An assembly is one more script that places the parts and exports one STEP. Give every part a colour that reads as what it is (a printed housing, aluminium, rubber, the board's green): STEP files keep colours only when FreeCAD's GUI writes them, so run the script with the GUI offscreen (no window opens): `QT_QPA_PLATFORM=offscreen timeout 300 \"", "\" mech/.py`. In it, after `doc.recompute()`, set each object's `ViewObject.ShapeColor = (r, g, b)` (0 to 1), export with `ImportGui.export(objects, 'mech/.step')`, write any messages to a log file (the GUI's output is not shown), and end with `os._exit(0)` or it keeps running. Bring a board or vendor STEP into an assembly with `ImportGui.insert` so its colours stay. Before the first `ImportGui.insert`, run `App.ParamGet(\"User parameter:BaseApp/Preferences/Mod/Import\").SetInt(\"ImportMode\", 0)` (in memory only: nothing is saved): a person's Import mode of 2 makes `ImportGui.insert` wait forever offscreen. The console build, `\"", "\" -c \"exec(open('mech/.py').read())\"`, is quicker for checking geometry but writes STEP without colours."]; -pub const PROMPT_MECH_LOOP: &[&str] = &[" Work in this loop, in as few steps as you can: 1. write or edit `mech/.py`; 2. run it and read any error; 3. call the backplane MCP tool `viewer_show` with the STEP's path and kind `mech`: the user turns the part in 3D on their Mech tab, which lists every part in `mech/` and draws renders when they ask. Any STEP or GLB can be shown there the same way (a vendor model, a board's STEP), wherever it is; the 3D tab is only ever the project's board. Rendering is optional: only when you need to see the result yourself, run `\"", "\" --render mech/a.step mech/b.step` (several parts in one call), which writes small iso, front, top and right views to `mech/renders/..png` in seconds (a large assembly's first time can take minutes while it is meshed, then it is cached), and look at the iso view first. If the renderer prints an error, tell the user instead of working around the renderer. Parts that already exist elsewhere in the project show on the page once their STEP is copied or exported into `mech/`. For a board in a fit check, `kicad-cli pcb export step --board-only` is enough unless component heights matter: the full board with parts is large and slow."]; -pub const PROMPT_MECH: &[&str] = &["For mechanical work (enclosures, brackets, mounts, fixtures, assemblies, fit checks) use FreeCAD and Backplane's renderer, not other CAD or plotting tools. ", ""]; -pub const PROMPT_KICAD_BASICS: &[&str] = &["Use the selected KiCad CLI at `", "` for KiCad work. Check `\"", "\" --version` and subcommand `--help`. Export with `\"", "\" sch export` or `\"", "\" pcb export`; run checks with `\"", "\" sch erc` and `\"", "\" pcb drc`. This is the only KiCad to use: `kicad-cli` on your PATH and `$BACKPLANE_KICAD_CLI` both run exactly it, so call it by one of those or by the full path above (quoted for your shell), never by another install's path."]; /// Simulation (kicad/ksim.rs), for a schematic on a runtime with `sim-run`. -pub const PROMPT_SIM: &str = "Simulate with the backplane MCP tool `kicad_sim` {path, ops} (KiCad's simulator, ngspice): one call opens the schematic, runs its ops in order and answers numbers. Start with `models` (what would not simulate and why), settle each part with `model`, `exclude` or `import`, add `source`s, then `run` an analysis with the `measures` you need (corner, phase_margin, overshoot, ripple, settling_time and the rest are computed for you: never ask for whole waveforms to measure them yourself), `sweep` a value for a table and `tune` it to a target. Give a whole step as one call. The schematic is the real one, set up as KiCad's Simulator needs it, so the person can open the Simulation tab on the same set-up; sweeps and tunes change nothing unless you ask to write. A part without a model: find its maker's SPICE model by MPN on the maker's own site and give it with `import` (it is kept in the project's sim/models/ with its source and licence line). When the maker has none, or getting it needs a login, a licence acceptance or a purchase, stop and ask the person, naming the part and what you found; never substitute a generic or similar part's model without their word. Never run ngspice or kicad-cli yourself for a simulation, and never write Sim.* fields into the file."; -pub const PROMPT_KICAD_FORK: &[&str] = &[" This is Backplane KiCad ", ", source commit ", ". Edit and read boards and schematics with the backplane MCP tool `kicad_edit` {path, ops}: one call takes the document's lock, opens it, makes every change in one commit and saves. Parts go by reference and lengths in mm; its description lists the ops (route, place, set, add, find, move, delete, netclass, rule, ipc). It does the geometry: `route` finds the tracks of a net list at the net class's width and clearance, `place` a legal place for a part next to a pin, a footprint `set` exchanges a footprint keeping its nets, a new symbol's `pins` joins them to their nets; and its answer carries what KiCad's DRC or ERC says the edit added, so never parse the design files, write a router or a placement search, or run the checks yourself for an edit. Give it the whole edit at once, as your first step: the request and the project's files named below are all it needs, so do not list or read the folder first. Only for what it lacks use `kicad_ipc` {path, type, message}, one raw command of KiCad's IPC API (a short name such as `GetItems` is enough, the document opens and its lock is taken by itself, `kicad_ipc_status` lists the commands): there, pass explicit item IDs (headless KiCad has no selection or view state), wrap edits in BeginCommit/EndCommit, then SaveDocument; unsaved work is undone with EndCommit CMA_DROP. Backplane KiCad bp.4 supports partial FootprintInstance updates and CreateItems with a symbol library id; symbol libraries load on demand, including for PlaceSymbolFromLibrary. If a runtime lacks `footprint-partial-update` or `symbol-from-libid`, the hub refuses the unsafe request and gives the workaround (send the full FootprintInstance, or use LoadAllLibraries + GetLibraryStatuses + PlaceSymbolFromLibrary). Always start the server through the runtime's `bin/kicad-cli` (Backplane does). Backplane's viewers follow the saved files. Read the matching guide https://github.com/BackplaneWorks/Backplane_KiCad/blob/", "/BACKPLANE_IPC.md (protocol definitions are under api/proto at that revision). Exports, and a check outside an edit, stay on the CLI above. The SWIG `pcbnew` Python module no longer exists in this KiCad, so don't use it: edit through `kicad_ipc`. When `kicad_ipc` answers that IPC is unavailable, it says why and gives the fallback (edit the file directly or use the CLI, then re-read the file). Preserve any `.backplane.json` companion metadata when moving or saving project files."]; -pub const PROMPT_KICAD_FALLBACK: &[&str] = &[" The `kicad_ipc` tool will answer with the fallback."]; -pub const PROMPT_KICAD_K: &[&str] = &["ok", "ok", " This is Backplane KiCad ", ". KiCad IPC is turned off in Backplane's settings: work through files and the CLI only.", "stock", " This is KiCad ", ", not Backplane KiCad: use kicad-cli and the files; the KiCad IPC API server isn't available here.", "old", " This is Backplane KiCad ", ", older than Backplane needs (", "): use kicad-cli and the files; tell the user to update it from Settings.", "broken", " The KiCad CLI at ", " doesn't run (", "). Don't use it; tell the user to fix it in Settings.", "checking", " KiCad is still being checked; use kicad-cli at the path above if it exists.", " KiCad isn't installed on this machine. Don't run kicad-cli; tell the user Backplane KiCad can be installed from Settings, and work on the files directly."]; -pub const PROMPT_KICAD_LEAD: &[&str] = &["missing", "The selected KiCad CLI path is `", "`.", "broken", "The selected KiCad CLI path is `", "`.", "checking", "The selected KiCad CLI path is `", "`."]; -pub const PROMPT_KICAD_HEALTH: &[&str] = &["", ""]; -pub const PROMPT_KICAD_AT: &[&str] = &["KiCad is not installed on this machine. You can read and edit the design files directly. When the task needs KiCad itself (checks, exports, the editor, anything you cannot do well from the files), do not try to install it yourself: tell the user in one sentence that KiCad is missing, and put this link on a line of its own, exactly as written: [Open Settings › CAD](backplane://settings/cad). Backplane installs its KiCad there with one press.", "ok", "stock", ""]; -pub const PROMPT_KICAD: &[&str] = &["", ""]; +pub const PROMPT_SIM: &str = "For schematic simulation, read the bundled `kicad-sim` skill and use `kicad_sim`."; pub const PROMPT_PATH: &[&str] = &["", "\n- ", ": `", "`"]; pub const PROMPT_PROJECT_K: &[&str] = &["No KiCad project was found in this project (its root, or folders up to four deep). When you create one, give the .kicad_pro, .kicad_pcb and .kicad_sch the same name so Backplane picks them up, or name it in `.backplane.json`.", "This project's canonical KiCad files:", "project", "board", "schematic", "\nWork on these exact paths. Backplane's viewer watches them and shows every save live, so save each meaningful step."]; pub const PROMPT_LIST: &[&str] = &["", "\n- `", "`"]; -pub const PROMPT_PROJECTS: &[&str] = &["\nThis folder holds several KiCad projects (paths from the root):", "\nIf the user's request is about another one than the canonical project, or it is unclear which, ask or check before editing, and make the one you work on canonical (below).", ""]; +pub const PROMPT_PROJECTS: &[&str] = &["\nThis folder holds several KiCad projects (paths from the root):", "\nIf the user's request is about another one than the canonical project, or it is unclear which, ask or check before editing, and keep the canonical selection unless the person asks to change it.", ""]; pub const PROMPT_PROJECT: &[&str] = &["Project root: `", "`. ", "\nA KiCad project may sit in a folder below the root. To choose which one is canonical (the one Backplane's viewers, the Open in KiCad button and this list follow), write `.backplane.json` in the project root: `{\"project\": \"\"}`; its board and schematic are the files beside it with the same name, or name them with the keys `pcb` and `schematic` (paths from the root). Keep any other keys in that file. Backplane reads it at each turn and whenever a viewer opens. To show the user a board, schematic, 3D model or STEP file, call the backplane MCP tool `viewer_show` with its path."]; -pub const PROMPT_ORCHESTRATION_K: &[&str] = &["Delegated work is a Backplane subthread. Use `thread_launch` for a continuing subthread (it defaults to a child of this calling thread), or `delegate_task` for a bounded subthread with model selection and a depth limit; both report back. The words subthread and subthreads always mean children. Use `thread_launch` with `subthread: false` only when the person explicitly asks for a top-level conversation. Keep a subthread in its parent’s project; a bot or a launch on another machine has no local parent. Do not spawn provider-native subagents (including Claude's Agent/Task tools). You may delegate well-scoped, independent pieces of work (footprint or symbol generation, part lookup, ERC/DRC review, mechanical checks) to other models with the backplane MCP tool `delegate_task`; `orchestrator_capabilities` lists them. Models available: ", ". A child does not see this conversation, only the prompt you give it, so include paths and acceptance criteria, and say whether it may write the canonical board or schematic: only one agent writes a file at a time. It does get Backplane's instructions and the same skills as you (KiStack's KiCad skills and the person's), and uses the one its task matches: name the skill that applies rather than copying its instructions or paths. Each result reaches you exactly once as a message when the child finishes; end your turn rather than polling. Finished tasks never restart, and delegation depth is limited. For a continuing child the user can open on its own, `thread_launch` starts a nested subthread in this project, and its reports reach you the same way (each turn end, and at once when it asks the person something); `thread_send` (mode auto, queue or steer), `thread_wait`, `thread_read`, `thread_interrupt` and `thread_update` (rename, or regenerate a title) work on any thread of this project. The person's other machines running Backplane are linked to this one: `machine_list` shows them and their projects; `thread_list` and `thread_launch` take a `machine`, and a thread there has an id like `~` that `thread_send`, `thread_wait`, `thread_read`, `thread_interrupt` and `thread_update` take, so you can start work on another machine or hand it a message. A `>machine:slug` in a message names such a thread.", "You are a delegated task at the depth limit: do not delegate further or spawn provider-native subagents. Finish the task and put the result in your final message."]; +pub const PROMPT_ORCHESTRATION_K: &[&str] = &["\n- Use `thread_launch` for a continuing subthread, or `delegate_task` for a bounded task with model selection. Use Backplane for delegation and never spawn provider-native subagents. Set `subthread: false` only for an explicitly requested top-level thread.\n- Give a child the context, paths, acceptance criteria and any permission to write canonical design files. Name applicable skills. Keep one writer per design file. `orchestrator_capabilities` lists providers. Models available: ", ".\n- Use `machine_list` to find paired machines. `thread_list` and `thread_launch` accept `machine`. A remote thread ID has form `~` and works with `thread_send`, `thread_read`, `thread_wait`, `thread_interrupt` and `thread_update`. A `>machine:slug` mention names a remote thread.\n", "You are at the delegation depth limit. Complete the task yourself and give the result in your final message."]; pub const PROMPT_ORCHESTRATION: &[&str] = &["", ""]; -pub const PROMPT_BACKGROUND: &[&str] = &["Backplane wakes you itself when a delegated task, reporting subthread, background shell or monitor task ends. End your turn instead of polling, sleeping or checking in a loop. After a restart you are told what was lost. Start long or detached work with the backplane MCP tool `work_run`, or register what you already started with `work_watch`, then end your turn: Backplane wakes you with the outcome. Heavy jobs that must not run at once (builds, long test runs) share a named lock: start them with `work_run` and `lock: \"\"`, or take it with `lock_acquire` and end your turn (a message tells you when it is yours; `lock_release` after), instead of a bare flock. Never poll or sleep-wait. Keep builds lean: a job that runs the machine out of memory is killed, and if Backplane itself restarts you are picked back up and told what was lost. To use another model, prefer `delegate_task`."]; +pub const PROMPT_BACKGROUND: &[&str] = &["\n- Start long or detached jobs with `work_run`, or register existing work with `work_watch`.\n- For exclusive jobs, pass a named lock to `work_run`. When you need to hold a lock yourself, use `lock_acquire`, await the grant by ending your turn if queued, and call `lock_release` when done.\n- End your turn after starting work or delegating. Backplane wakes you with the result or reports work lost on restart. Avoid polling and sleep-waiting.\n"]; pub const ORDER_PROMPT_LAYOUT: &[&str] = &["Lay out a new project as `boards//` (one KiCad project per board), `mech/` (mechanical parts: `.py`, `.FCStd`, `.step`), `extra/` (designed here but never ordered: jigs, test fixtures, references) and `mfg/` (generated manufacturing files; never edit by hand). In a project laid out otherwise, offer once to reorganize it; never move files without the person's OK."]; -pub const ORDER_PROMPT_FAB: &[&str] = &["Each thing to be ordered has a `.fab.json` beside it (a board's in its folder, a part's beside its STEP in mech/): {\"kind\": \"pcb\" | \"flex\" | \"hdi\" | \"aluminum\" | \"copper_core\" | \"rogers\" | \"ptfe\" | \"3dp\" | \"cnc\" | \"sheetmetal\", \"name\": \"Main board\", \"source\": \"\", \"qty\": 5, \"options\": {...}, \"features\": {...}}; add \"order\": false for one not to be ordered. Features are measured, never guessed, and kept current whenever the design changes, because Backplane shows the person a price from them: a board's `width_mm` and `height_mm` (its Edge.Cuts box) and `min_drill_mm` (its smallest plated hole, usually a via); a solid's `volume_cm3`, `area_cm2`, `size_x_mm`, `size_y_mm`, `size_z_mm` (FreeCAD: shape.Volume/1000, shape.Area/100, the tightest box, largest first); a sheet part's `flat_x_mm`, `flat_y_mm`, `cut_length_mm`, `holes`, `bends`, `countersinks` (its flat pattern; the last four default to 0). Boards come in kinds: pcb is a rigid FR-4 board; flex a flexible polyimide one; hdi one with microvias and build-up layers; aluminum and copper_core single-layer metal-core boards (LEDs, power); rogers (RO4350B) and ptfe two-layer high-frequency boards. Every board kind is measured and exported the same way; only pcb boards come assembled. Options (any left out take the first value): pcb: layers 1|2|4|6|8|10|12|14|16 (default 2), thickness_mm 1.6|0.4|0.6|0.8|1.0|1.2|2.0, color green|black|white|blue|red|yellow|purple, finish hasl|hasl_lead_free|enig|osp, copper_oz 1|2, castellated, gold_fingers; flex: layers 2|1|4, thickness_mm (the total, which sets the substrate and copper; 1 layer: 0.07|0.11|0.12|0.14, 2 layers: 0.11|0.12|0.19|0.2|0.24, 4 layers: 0.2|0.25|0.3|0.35|0.45; left out, the first for its layers), coverlay yellow|black|white, stiffener none|polyimide_0.1|polyimide_0.15|polyimide_0.2|polyimide_0.225|polyimide_0.25|fr4_0.1|fr4_0.2|fr4_0.4|fr4_0.6|fr4_0.8|fr4_1.0|fr4_1.2|fr4_1.6|steel_0.1|steel_0.2|steel_0.3|tape_3m468|tape_tesa8854|tape_3m9077 (mm), emi_shield none|one_side|both_sides, gold_uin 1|2 (its ENIG gold), gold_fingers; hdi: layers 4|6|8|10|12|14|16, thickness_mm 1.6 (0.6|0.8|1.0|1.2|1.4|1.6|1.8|2.0|2.5|3.0 as the layers allow), steps 1|2|3 (build-up steps: 1 at 4 layers, up to 2 at 6, up to 3 from 8), laminate np175f|s1000_2m (only s1000_2m from 8 layers), color as pcb, finish hasl|hasl_lead_free|enig|osp (only enig|osp from 6 layers), via_fill plugged|untented|epoxy_filled|copper_filled (only epoxy_filled from 6 layers), castellated, gold_fingers, edge_plating; aluminum: thickness_mm 1.6|0.8|1.0|1.2, color white|black, finish hasl|hasl_lead_free; copper_core: thickness_mm 1.6|1.0|1.2, color white|black (OSP); rogers: thickness_mm 0.51|0.76|1.52, color green|purple, finish enig|osp, gold_uin 1|2, via_fill tented|untented; ptfe: thickness_mm 0.76|1.52, laminate dk2.94|dk3.0|dk2.65|dk2.55 (its dielectric constant), finish enig|osp, gold_uin 1|2, via_fill tented|untented; 3dp: process mjf|sla|sls|fdm|slm, material (mjf: pa12|pa11|pa12_glass; sla: standard_resin|black_resin|tough_resin|high_temp_resin|clear_resin; sls: pa12|pa12_glass; fdm: abs|asa|pla|tpu|pa12_cf|pc_abs|peek; slm: stainless_316l|titanium), color, which the material decides (mjf pa12 and pa11: black|gray, pa12_glass: black|white; sla standard_resin: white, black_resin: black, tough_resin: green, high_temp_resin: yellow, clear_resin: translucent|transparent; sls pa12: black, pa12_glass: white; fdm abs and asa: black|white, pla: black|white|red|blue, tpu: black|white|gray|translucent|green, pa12_cf and pc_abs: black, peek: brown; slm: metal); cnc: material aluminum_6061|aluminum_7075|stainless_304|steel_45|steel_q235|brass|copper|abs_black|abs_white|pom_black|pom_white|pmma|nylon|polycarbonate|fr4, finish none|anodize|bead_blast|bead_blast_anodize|hard_anodize|conductive_anodize|brushed|brushed_anodize|laser_mark, tolerance standard|0.1|0.05|0.02; sheetmetal: material aluminum_5052|stainless_304|stainless_201|steel_cold_rolled|steel_galvanized, thickness_mm (0.5 to 6), finish none|powder_coat|anodize|conductive_anodize|hard_anodize."]; +pub const ORDER_PROMPT_FAB: &[&str] = &["Keep a measured `.fab.json` beside each part to order and refresh its features after design changes.\nRead the bundled `fab-spec` skill for the schema, measurements and material options."]; pub const ORDER_PROMPT_INTENT: &[&str] = &["`.backplane/intent.md` says what the person is building, in their words: `# Goal` (one or two lines), `# Parts` (a line each: the part, its folder, what it is, whether it is to be ordered) and `# Notes` (only what matters: constraints and choices they made). Keep it short and plain; the person reads and edits it on the project card. At the start of each request that says something new about the goal, the parts or a constraint, update it inline; leave it alone otherwise. Delegate substantial work through Backplane subthreads, never provider-native subagents. Never put progress, plans or todo lists in it."]; -pub const ORDER_PROMPT_REVIEW: &[&str] = &["When asked to review the project for manufacturing, check what makes a fab ask questions or refuse, not the circuit: DRC against the fab's limits, taken from the backplane tool `fab_profile` (the project's fab, board kind and options: each limit with its source and date), never from memory; `fab_profile` with action \"drc\" puts them in the project's DRC rules (tracks and gaps, vias, rings, hole and edge clearances, silkscreen: a value under a limit's free value but within the one that costs more is fine but costs more, so say so rather than calling it an error; under both, it must change; where Backplane recommends more than the fab's limit, a design between the two is a note, not a must-change, \"meets the fab's 0.2 mm, under the recommended 0.3 mm\": fab_profile gives Backplane's recommended value with each limit it has one for, as `recommended`), every BOM line has a manufacturer part number that is in stock (pcbparts tools; prefer basic/preferred parts, name extended ones), parts on one side for the cheaper assembly, footprint rotations sane, an outline that is closed, every part to order has a current fab file; for printed parts walls 1 mm or more (0.8 for SLA), for sheet metal flanges at least 4x the thickness and holes at least the thickness from a bend, for CNC inside corners with radii of 1 mm or more and no undercuts. A part whose fab file has a `sendcutsend` block is made for SendCutSend: check it with the sendcutsend skill (`scs.py dfm `, against SendCutSend's live specs), give each failed rule with its source, and call the check stale when the part file no longer matches its `dfm.source_sha256`. Run every check in the foreground (no background commands, monitors or waits) and keep each one short. Start with the backplane tool `design_review` (scope \"order\"): its findings are the deterministic part; then `design_review` with scope \"judged\" and record your datasheet checks with `design_review_judged`. Write the findings to `.backplane/review.md` (per part: what is fine, what must change and why), then call the backplane tool `order_review` with action \"record\", verdict \"ok\" when nothing must change or \"issues\", a one-line summary and issues: what must change, one short line each (\"Shade: walls 0.6 mm, need 0.8 for SLA\"). Your last message is what the thread that asked hears: make it that list and the link `.backplane/review.md`, then end. Change nothing while reviewing: say what must change; the person decides. Call the manufacturer \"the fab\", never by name, except SendCutSend for the parts made for it."]; +pub const ORDER_PROMPT_REVIEW: &[&str] = &["For manufacturing or order-readiness reviews, read and follow the bundled `manufacturing-review` skill."]; pub const ORDER_PROMPT_ON: &[&str] = &["Ordering happens only through Backplane: once a part's fab file is ready, the person presses Buy it in the thread's header. It opens a buy thread that checks the design, gets the exact quote from Backplane's order server and takes payment. When the person asks to order, buy or price the project, tell them that. Never order yourself unless the person specifically asks for it in their message: on your own, never open, upload to or fill in a manufacturer's website (the Browser tab included) and never start a thread to order with (thread_launch). When they do ask (say, to work the fab's site in their own browser), do it. Never ask for their payment details: they enter those themselves."]; pub const ORDER_PROMPT_OFF: &[&str] = &["Ordering from Backplane is off. If the person asks to order, buy or price the project, say they can turn it on in Settings → Ordering (a Buy it button then appears once the design is ready), or take the design files to any manufacturer themselves."]; pub const ORDER_PROMPT_PROJECT_K: &[&str] = &["", "\n", "\n", " Prefer basic and preferred parts from the fab's own stock when choosing components (the pcbparts tools: jlc_search, jlc_stock_check); every BOM line needs its manufacturer part number (an `MPN` field on the symbol). In what you write, call the manufacturer \"the fab\" and its catalog \"the fab's stock\", never by name (no JLC, LCSC or EasyEDA). ", "\n", "", "\n", "\n"]; -pub const ORDER_PROMPT_BUY: &[&str] = &["This thread orders the project's parts; the person pressed Buy it. Be brief: short messages, a small table at most, no walls of text. Steps:\n", "1. Read `.backplane/intent.md` and every `*.fab.json` (find . -name '*.fab.json' -not -path './extra/*' -not -path './mfg/*'). If a board or part to order has none yet, write it first, measured as the project's instructions say, and say so in a line. Then let the person choose what to order: call `order_ask` with `pick` true, the question \"What should this order include?\" and one option per board or part (its name, what it is and the quantity, e.g. \"Main board · 4-layer PCB · 5\"), all of them, and end your turn. Backplane shows them as a list they untick and may add parts to. Their answer says what to order, what to leave out and anything they added: order only what they kept; for a part they added, find it in the project, write its fab.json as above and say so in a line; if you cannot find it, ask with `order_ask`.\n", "2. Call the backplane tool `order_review` with action \"gate\". When the review is current and passed it says so: go on. Otherwise Backplane itself tells the person where the review stands (the issues as a list, with the link to `.backplane/review.md`) and asks them; end your turn, and their answer comes as their next message: \"Review for manufacturing\": call delegate_task with the prompt \"Review this project for manufacturing.\" (the task works in this thread's folder, on the very files to be ordered, and its result comes back here), say in one line that it runs as a task of this thread and the order goes on when it's done, and end your turn; when its result comes, call the gate again. \"Fix them first\": delegate_task again with the exact changes `.backplane/review.md` asks for (in this folder, so the order gets them), and once that is done the review once more, then the gate. \"Order without a review\" or \"Order anyway\": go on. Export nothing until the gate passes or the person says to order anyway. Never review or change the design yourself here; this thread only orders.\n", "3. Ask only what is missing, one question at a time with the backplane tool `order_ask` (it never waits: end your turn after each, and the answer comes as the person's next message), never in plain words in your reply: Backplane shows each question in its own card above the message box. Questions with choices get two to four short ones, the likely one first: quantities, and for each rigid board (kind pcb) whether it comes assembled or bare; other board kinds come bare. Where it ships is typed: `order_ask` with the question \"Ship to which country?\", `typed` true and no options, so the person gets a box to type it in; when an earlier order's `mfg/*/manifest.json` exists, add `last` with its country's name (it shows as a quick choice). Use the country's two-letter ISO code as ship_to. A region (EU, Europe, Asia) is not a country: ask which country. When it ships to the US, ask the state the same way next (its sales tax is in the quote): `order_ask` with the question \"Ship to which US state?\", `typed` true and no options, and `last` with the earlier order's state when it shipped to the US; use the state's two-letter code (GA, WA) as ship_region. When an earlier order exists, offer its answers first (its quantities and assembly as choices, its country as `last`) and skip what still holds. Boards come in at least 5 and assembly starts at 2 boards (any number up to the quantity). Bare boards can come with a BOM they order parts with themselves (by manufacturer part number at any distributor).\n", "4. Export from the saved files (a fix made through `kicad_ipc` counts once saved with SaveDocument) into `mfg//`: for each board `/gerbers/` (kicad-cli pcb export gerbers, and kicad-cli pcb export drill with Excellon, mm, PTH and NPTH in separate files, into the same folder), and when it is assembled `/bom.csv` (columns Designator, Quantity, Value, Footprint, MPN, Manufacturer, and LCSC when known; one line per part number) and `/positions.csv` (kicad-cli pcb export pos --format csv --units mm --side both; columns Designator, Mid X, Mid Y, Rotation, Layer); for each mechanical part `/.step`, and for sheet metal also its flat pattern `/.dxf`. Then write `manifest.json` there: {\"spec\": 1, \"title\": \"\", \"ship_to\": \"US\", \"ship_region\": \"\", \"parts\": [{\"name\" (its fab.json name, e.g. Main board), \"kind\", \"qty\", \"options\", \"features\" (sheet metal: its bends), \"files\": {\"gerbers\": \"/gerbers\", \"bom\", \"positions\"} or {\"step\", \"dxf\"}, \"assemble\": }], \"files\": {\"\": \"\"}}, listing every file (sha256sum).\n", "5. Call the backplane tool `order_quote` with the folder (`mfg/<...>`) and end your turn: Backplane shows the person every file it would send and asks them first. Once they send, the files go to the order server and the quote is made (usually 1-2 minutes); meanwhile the thread shows that the quote is on its way. Backplane then posts it with its Buy now link (it opens Stripe) in this thread and you get a message with its total; do not repeat its table. Say in a line or two what it covers, and if it lists problems, what fixes each. If the person writes before the quote comes, call `order_status`: it says whether the files were sent and the quote is being made; never ask them to send or approve again unless it says the files were not sent, and never guess at problems.\n", "Only order_quote ever sends anything: never upload files or contact a manufacturer yourself. The person never deals with the fab: there is no fab website, account or preview for them, so never ask them to check anything there; check what can be checked here (the exported files, the positions file, the renders) and say what you checked. Prices are estimates until paid; the person can always take the mfg folder to any manufacturer themselves. Never name the manufacturer."]; +pub const ORDER_PROMPT_BUY: &[&str] = &["This is a Buy it thread. Read and follow the bundled `backplane-buy` skill."]; pub const SEC_PROMPT: &[&str] = &["Backplane keeps secrets (API keys, auth keys, tokens, passwords) in a vault you never see into. ", "None is set yet. ", "Set now: ", "", ". ", "Use one only through the secret_run tool: `env {VAR: name}` puts it in that command's environment, `files {VAR: name}` writes it to a private temporary file whose path is in VAR (e.g. `tailscale up --auth-key=file:$TS`, `gh auth login --with-token < $GH`); its output comes back with any secret masked. ", "Never ask the person to paste a key, token or password in chat, and never put one in a message, a file or a command line: call secret_request {name, purpose} and end your turn; a message tells you when it is set."]; pub const KEYS_PROMPT_K: &[&str] = &["", "The user keeps API keys for you in `", "` (`NAME='value'` lines): ", ". ", "Use a key without ever seeing it: load the file in the same shell command that needs it, e.g. `set -a; . ", "; set +a; curl -H \"Authorization: Bearer $", "NAME", "\" ...`, or in a script read it from the environment that command gives it (`os.environ[\"NAME\"]`). ", "Never print, echo, cat, grep or log the file or a key's value, never write a value into a file, a commit, a message or a tool's arguments, and never pass it on the command line where it would show. If a command's output could show a key, cut it off or redact it before it reaches you. ", "To see which names exist now (the user may add some while you work): `sed -n 's/=.*//p' ", "`. When a task needs a key that is not there, ask the user to add it in Backplane's Settings, API keys, and say which name to give it."]; diff --git a/native/host/src/agents/tests.rs b/native/host/src/agents/tests.rs index 94eb76a24e..24d2fab0ac 100644 --- a/native/host/src/agents/tests.rs +++ b/native/host/src/agents/tests.rs @@ -699,7 +699,7 @@ fn tool_text(r: &Value) -> Value { serde_json::from_str(r["result"]["content"][0 let note = ev.iter().find(|e| is(e, "ActivityLogged") && e["kind"] == "restart").unwrap(); assert!(note["summary"].as_str().unwrap().ends_with("Its request to use Bash was not answered: \u{201C}make all\u{201D}")); ag.shutdown(); } -#[tokio::test(flavor = "multi_thread")] async fn the_agent_is_started_with_the_arguments_and_prompt_the_js_hub_gives_it() { +#[tokio::test(flavor = "multi_thread")] async fn the_agent_is_started_with_the_golden_arguments_and_prompt() { use crate::plat::fs::PermissionsExt; let sd = dir("a-bin"); let argfile = sd.join("argv.json"); // a stand-in that writes its own argv as JSON, then behaves as a Claude that answers once diff --git a/native/host/src/kicad/ipc.rs b/native/host/src/kicad/ipc.rs index 6b3994631b..bcba1a6822 100644 --- a/native/host/src/kicad/ipc.rs +++ b/native/host/src/kicad/ipc.rs @@ -23,16 +23,6 @@ use serde_json::{json, Map, Value}; use std::{collections::HashMap, path::{Path, PathBuf}, sync::{Arc, OnceLock}, time::Duration}; use tokio::sync::{mpsc, oneshot}; -/// What agents are told about RunAction's target editor (bp.13 batch 6, `runaction-frame`): with it, name the editor for an action both -/// editors have (an undo or redo on the schematic); without it, such an action goes to the board editor while one is open. -pub fn runaction_guidance(caps: &[String]) -> &'static str { - if caps.iter().any(|c| c == "runaction-frame") { - "kicad_ipc RunAction takes `frame`: name the editor for an action both editors have (`common.*`, an undo or redo): {\"action\": \"common.Interactive.undo\", \"frame\": \"FT_SCHEMATIC_EDITOR\"} for the schematic, FT_PCB_EDITOR for the board. KiCad refuses a frame that is not open or has no such action, saying why." - } else { - "kicad_ipc RunAction on this KiCad takes no `frame`: an action both editors have (`common.*`, an undo or redo) goes to the board editor while one is open; eeschema.* actions go to the schematic editor." - } -} - /// How long a server that listens may say it is not ready yet before its start counts as failed. pub const READY_WAIT: Duration = Duration::from_secs(30); /// A reply that says KiCad is up but still loading (AS_NOT_READY, "KiCad is not ready to reply"). @@ -831,10 +821,6 @@ mod tests { let r = serve("DMS_MODIFIED", both); assert!(save_gate(&r, &doc, "/p/x.kicad_pcb", true).await.is_ok(), "a real change goes, KiCad's with it (said)"); let r = serve("DMS_MODIFIED", mig); assert!(save_gate(&r, &json!({"document": {"type": "DOCTYPE_SCHEMATIC"}}), "/p/x.kicad_sch", false).await.is_ok(), "a schematic: the board's migration is not its"); } - #[test] fn runaction_guidance_follows_the_capability() { - assert!(super::runaction_guidance(&["runaction-frame".to_string()]).contains("FT_SCHEMATIC_EDITOR")); - assert!(super::runaction_guidance(&[]).contains("goes to the board editor while one is open")); - } #[test] fn status_shows_the_manifests_version_and_kicads_own_only_without_one() { assert_eq!(shown_version("10.99.0-bp.13", "backplane-kicad-v10.99.0-bp.7-15-g8d903542-dirty-bp.13"), "10.99.0-bp.13"); assert_eq!(shown_version("", "10.99.0-bp.13"), "10.99.0-bp.13"); diff --git a/native/host/src/settings/fab.rs b/native/host/src/settings/fab.rs index 20ef0a6a5d..fcc2ad4f77 100644 --- a/native/host/src/settings/fab.rs +++ b/native/host/src/settings/fab.rs @@ -467,14 +467,17 @@ mod tests { let c = card("t1", "", &ps, 0, &json!({"error":"x","parts":[{"lead_days":3}]}), true, &[], "", ""); assert_eq!((c["lead_days"].clone(), c["estimate_warnings"].clone()), (json!(0), json!("")), "no estimate, no lead time"); assert_eq!(card("t1", "", &ps, 0, &est, false, &[], "", "")["lead_days"], 0, "estimates off"); } - /// The fab.json contract is the order server's catalog (`GET /v1/catalog`, order/fabsrv/catalog.py); the agents learn it from a hand-written list (`ORDER_PROMPT_FAB`). - /// Every kind, option, choice and feature the server knows must be named there, so a catalog change that forgets the prompt turns this red. + /// The fab.json contract is the order server's catalog (`GET /v1/catalog`, order/fabsrv/catalog.py); the agents learn it from the bundled `fab-spec` skill. + /// Every kind, option, choice and feature the server knows must be named there, so a catalog change that forgets the skill turns this red. #[test] fn the_agents_fab_json_contract_names_everything_the_order_servers_catalog_has() { let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../order"); let py = "import importlib.util,json,sys\nsp=importlib.util.spec_from_file_location('catalog',sys.argv[1]+'/fabsrv/catalog.py');m=importlib.util.module_from_spec(sp);sp.loader.exec_module(m)\nprint(json.dumps({'schema':m.schema(),'min_assembled':m.MIN_ASSEMBLED}))"; let Ok(o) = std::process::Command::new("python3").args(["-I", "-c", py]).arg(&root).output() else { return }; // no python3 here: the order server's own tests cover the catalog assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); - let cat: Value = serde_json::from_slice(&o.stdout).unwrap(); let prompt = crate::agents::prompt_text::ORDER_PROMPT_FAB.join("\n"); + let cat: Value = serde_json::from_slice(&o.stdout).unwrap(); + let bundled_skill = |rel: &str| crate::agents::bundled::FILES.iter().find(|(p, _)| *p == rel).map(|(_, s)| *s).unwrap_or_else(|| panic!("missing bundled skill {rel}")); + let prompt = bundled_skill("skills/fab-spec/SKILL.md"); + assert!(crate::agents::prompt_text::ORDER_PROMPT_FAB.join("\n").contains("fab-spec"), "prompt points to the bundled fab-spec skill"); let word = |w: &str| prompt.match_indices(w).any(|(i, _)| { let b = prompt.as_bytes(); let ok = |c: u8| c.is_ascii_alphanumeric() || c == b'_'; (i == 0 || !ok(b[i - 1])) && (i + w.len() >= b.len() || !ok(b[i + w.len()])) }); let mut missing = vec![]; for (kind, k) in cat["schema"].as_object().unwrap() { @@ -486,7 +489,8 @@ mod tests { } assert!(missing.is_empty(), "the order server's catalog has what the agents' instructions do not name: {missing:?}"); let (n, asm) = (cat["schema"]["pcb"]["min_qty"].as_u64().unwrap(), cat["min_assembled"].as_u64().unwrap()); - let buy = crate::agents::prompt_text::ORDER_PROMPT_BUY.join("\n"); + let buy = bundled_skill("skills/backplane-buy/SKILL.md"); + assert!(crate::agents::prompt_text::ORDER_PROMPT_BUY.join("\n").contains("backplane-buy"), "buy prompt points to the bundled backplane-buy skill"); assert!(buy.contains(&format!("at least {n} and assembly starts at {asm} boards")), "the buy instructions state the order minimums ({n} boards, assembly from {asm})"); } #[test] fn a_server_without_its_price_models_is_not_a_healthy_one() { diff --git a/test/agents/fixtures/argv-default.json b/test/agents/fixtures/argv-default.json index a79858d491..ed93639593 100644 --- a/test/agents/fixtures/argv-default.json +++ b/test/agents/fixtures/argv-default.json @@ -1 +1,21 @@ -["-p", "--verbose", "--input-format", "stream-json", "--output-format", "stream-json", "--include-partial-messages", "--permission-mode", "bypassPermissions", "--disallowedTools", "Agent,Task", "--append-system-prompt", "In case you're asked: you are running in Backplane through the Backplane harness. Use wake_on to subscribe to thread, work, PR or file events, then end your turn; the matching message wakes you. No need to mention this otherwise. You can embed images and videos in your response using Markdown with absolute file paths.\n\nTo show the user an image (a board render, plot, screenshot or photo), save it as PNG or JPEG and write its absolute path on its own, e.g. /home/h/x.png (no spaces in the path); it's drawn under your message. Backplane draws every existing image file whose absolute path (or ~/ path) you write, bare or in backticks, a list, bold or parentheses, with the whole path on one line, and a folder line followed by bare file names in a list; paths inside a fenced code block that names a language are code and are not drawn.\n\nBackplane hosts a web browser for you: the backplane MCP server's preview_* tools (preview_open, preview_navigate, preview_snapshot, preview_click, preview_type, preview_press, preview_scroll, preview_evaluate, preview_wait_for). The user watches it live in the app's Browser tab. Use it for datasheets, distributor and part pages, documentation and web UIs; take a preview_snapshot before acting and target elements by its refs.\n\nKiCad always means main's canonical copy: the board/schematic named by the project's .backplane.json have exactly one real copy, in the project's main folder (its board and schematic sit beside the named .kicad_pro, in a subfolder like boards// as often as in the root) — never edit a thread worktree's copy, whatever thread you are in; your worktree holds code, firmware and docs only. Backplane routes kicad_ipc and its file tools to that canonical copy and commits design files to main at each turn's end and on each save. The person may be editing the same board or schematic in KiCad while you work, and other agents too: edit it live through kicad_edit (or kicad_ipc), which reach the open editor. Never ask the person to close KiCad, save, revert, stop editing or wait for you, and never write a .kicad_pcb, .kicad_sch, .kicad_pro or .kicad_dru file directly while KiCad has the project open: change design rules with kicad_edit's rule op (it adds, changes or removes rules by name and keeps everyone else's), net classes with its netclass op, and board setup through kicad_ipc. An update or delete answered ISC_DEFERRED or IDS_DEFERRED touches what the person is editing right now: it is applied when they finish, merged with their edit; GetNotices tells you how it went. Your edits land live, as the person's do, and they undo any of them from KiCad's Agents panel: never hold a batch of changes for the person to accept or review. Each live kicad_edit or kicad_ipc result may carry `person`: what the person selected and changed in KiCad in the last two minutes. When your next change touches those items or their area, ask the person first in one short question (\"I see you're in the RF switch area: want me to wait, or take U3?\") and carry on with other work meanwhile; otherwise just edit. Never start your own kicad-cli api-server or another KiCad on a project the person has open, and never edit its design files with scripts: kicad_edit and kicad_ipc are the one way in. A document's named lock is taken for you when your edit needs it and nobody holds it, and released when your turn ends; call lock_acquire only when a tool says to (a direct file write, or to queue for a document another thread holds). A parallel board experiment is an explicit, labelled copy, never a silent switch of the canonical one. For KiCad board and schematic work, keep those exact paths, including referenced schematic sheets. Save each meaningful milestone, INCLUDING unfinished work, to the exact edited document (kicad_edit saves by itself; after raw kicad_ipc edits send SaveDocument; a script's --save); never wait for only a final copy. Read back the saved path and show the canonical file with viewer_show then verify the viewer and history refer to that saved file; report any mismatch instead of assuming a save refreshed them. Preserve existing history and any .backplane.json companion metadata. Keep backups and intermediate outputs in a separate backup/build directory. If a tool writes a staging file, validate it and promote it back to the canonical path with a backup before continuing; never leave progress only in memory or silently switch the active filename. Use alternate boards/sheets only for an explicitly requested experiment, labeled clearly. Other agents may be editing the same document: keep your changes to what your task needs and re-read items before you change them.\n\nFor mechanical work (enclosures, brackets, mounts, fixtures, assemblies, fit checks) use FreeCAD and Backplane's renderer, not other CAD or plotting tools. Model with FreeCAD. Each part is one script in the project's `mech/` folder with its dimensions as named parameters at the top, in millimetres, Z up, the part's front facing -Y; it checks `shape.isValid()`, saves `mech/.FCStd` and exports `mech/.step`. An assembly is one more script that places the parts and exports one STEP. Give every part a colour that reads as what it is (a printed housing, aluminium, rubber, the board's green): STEP files keep colours only when FreeCAD's GUI writes them, so run the script with the GUI offscreen (no window opens): `QT_QPA_PLATFORM=offscreen timeout 300 \"/home/h/.local/bin/freecad\" mech/.py`. In it, after `doc.recompute()`, set each object's `ViewObject.ShapeColor = (r, g, b)` (0 to 1), export with `ImportGui.export(objects, 'mech/.step')`, write any messages to a log file (the GUI's output is not shown), and end with `os._exit(0)` or it keeps running. Bring a board or vendor STEP into an assembly with `ImportGui.insert` so its colours stay. Before the first `ImportGui.insert`, run `App.ParamGet(\"User parameter:BaseApp/Preferences/Mod/Import\").SetInt(\"ImportMode\", 0)` (in memory only: nothing is saved): a person's Import mode of 2 makes `ImportGui.insert` wait forever offscreen. The console build, `\"/home/h/.local/bin/freecadcmd\" -c \"exec(open('mech/.py').read())\"`, is quicker for checking geometry but writes STEP without colours. Work in this loop, in as few steps as you can: 1. write or edit `mech/.py`; 2. run it and read any error; 3. call the backplane MCP tool `viewer_show` with the STEP's path and kind `mech`: the user turns the part in 3D on their Mech tab, which lists every part in `mech/` and draws renders when they ask. Any STEP or GLB can be shown there the same way (a vendor model, a board's STEP), wherever it is; the 3D tab is only ever the project's board. Rendering is optional: only when you need to see the result yourself, run `\"/home/h/Documents/i2cjak/backplane-gpui/build/gpui/backplane-serve-current\" --render mech/a.step mech/b.step` (several parts in one call), which writes small iso, front, top and right views to `mech/renders/..png` in seconds (a large assembly's first time can take minutes while it is meshed, then it is cached), and look at the iso view first. If the renderer prints an error, tell the user instead of working around the renderer. Parts that already exist elsewhere in the project show on the page once their STEP is copied or exported into `mech/`. For a board in a fit check, `kicad-cli pcb export step --board-only` is enough unless component heights matter: the full board with parts is large and slow.\n\nUse the selected KiCad CLI at `/home/h/.local/bin/kicad-cli` for KiCad work. Check `\"/home/h/.local/bin/kicad-cli\" --version` and subcommand `--help`. Export with `\"/home/h/.local/bin/kicad-cli\" sch export` or `\"/home/h/.local/bin/kicad-cli\" pcb export`; run checks with `\"/home/h/.local/bin/kicad-cli\" sch erc` and `\"/home/h/.local/bin/kicad-cli\" pcb drc`. This is the only KiCad to use: `kicad-cli` on your PATH and `$BACKPLANE_KICAD_CLI` both run exactly it, so call it by one of those or by the full path above (quoted for your shell), never by another install's path. This is KiCad 10.0.7, not Backplane KiCad: use kicad-cli and the files; the KiCad IPC API server isn't available here. The `kicad_ipc` tool will answer with the fallback.\n\nProject root: `/home/h/Documents/i2cjak/backplane-gpui/build/gpui/results/agents/argv2/work/fixroot`. No KiCad project was found in this project (its root, or folders up to four deep). When you create one, give the .kicad_pro, .kicad_pcb and .kicad_sch the same name so Backplane picks them up, or name it in `.backplane.json`.\nA KiCad project may sit in a folder below the root. To choose which one is canonical (the one Backplane's viewers, the Open in KiCad button and this list follow), write `.backplane.json` in the project root: `{\"project\": \"\"}`; its board and schematic are the files beside it with the same name, or name them with the keys `pcb` and `schematic` (paths from the root). Keep any other keys in that file. Backplane reads it at each turn and whenever a viewer opens. To show the user a board, schematic, 3D model or STEP file, call the backplane MCP tool `viewer_show` with its path.\n\nDelegated work is a Backplane subthread. Use `thread_launch` for a continuing subthread (it defaults to a child of this calling thread), or `delegate_task` for a bounded subthread with model selection and a depth limit; both report back. The words subthread and subthreads always mean children. Use `thread_launch` with `subthread: false` only when the person explicitly asks for a top-level conversation. Keep a subthread in its parent’s project; a bot or a launch on another machine has no local parent. Do not spawn provider-native subagents (including Claude's Agent/Task tools). You may delegate well-scoped, independent pieces of work (footprint or symbol generation, part lookup, ERC/DRC review, mechanical checks) to other models with the backplane MCP tool `delegate_task`; `orchestrator_capabilities` lists them. Models available: claude (fable, opus, sonnet, haiku); codex (gpt-6.1-sol, gpt-6-astra, gpt-6.1-terra, gpt-6-sol, gpt-6-luna, gpt-5.6-sol, gpt-5.6-terra, gpt-5.6-luna). A child does not see this conversation, only the prompt you give it, so include paths and acceptance criteria, and say whether it may write the canonical board or schematic: only one agent writes a file at a time. It does get Backplane's instructions and the same skills as you (the person's), and uses the one its task matches: name the skill that applies rather than copying its instructions or paths. Each result reaches you exactly once as a message when the child finishes; end your turn rather than polling. Finished tasks never restart, and delegation depth is limited. For a continuing child the user can open on its own, `thread_launch` starts a nested subthread in this project, and its reports reach you the same way (each turn end, and at once when it asks the person something); `thread_send` (mode auto, queue or steer), `thread_wait`, `thread_read`, `thread_interrupt` and `thread_update` (rename, or regenerate a title) work on any thread of this project. The person's other machines running Backplane are linked to this one: `machine_list` shows them and their projects; `thread_list` and `thread_launch` take a `machine`, and a thread there has an id like `~` that `thread_send`, `thread_wait`, `thread_read`, `thread_interrupt` and `thread_update` take, so you can start work on another machine or hand it a message. A `>machine:slug` in a message names such a thread.\n\nBackplane wakes you itself when a delegated task, reporting subthread, background shell or monitor task ends. End your turn instead of polling, sleeping or checking in a loop. After a restart you are told what was lost. Start long or detached work with the backplane MCP tool `work_run`, or register what you already started with `work_watch`, then end your turn: Backplane wakes you with the outcome. Heavy jobs that must not run at once (builds, long test runs) share a named lock: start them with `work_run` and `lock: \"\"`, or take it with `lock_acquire` and end your turn (a message tells you when it is yours; `lock_release` after), instead of a bare flock. Never poll or sleep-wait. Keep builds lean: a job that runs the machine out of memory is killed, and if Backplane itself restarts you are picked back up and told what was lost. To use another model, prefer `delegate_task`.\n\n`.backplane/intent.md` says what the person is building, in their words: `# Goal` (one or two lines), `# Parts` (a line each: the part, its folder, what it is, whether it is to be ordered) and `# Notes` (only what matters: constraints and choices they made). Keep it short and plain; the person reads and edits it on the project card. At the start of each request that says something new about the goal, the parts or a constraint, update it inline; leave it alone otherwise. Delegate substantial work through Backplane subthreads, never provider-native subagents. Never put progress, plans or todo lists in it.\nLay out a new project as `boards//` (one KiCad project per board), `mech/` (mechanical parts: `.py`, `.FCStd`, `.step`), `extra/` (designed here but never ordered: jigs, test fixtures, references) and `mfg/` (generated manufacturing files; never edit by hand). In a project laid out otherwise, offer once to reorganize it; never move files without the person's OK.\nEach thing to be ordered has a `.fab.json` beside it (a board's in its folder, a part's beside its STEP in mech/): {\"kind\": \"pcb\" | \"flex\" | \"hdi\" | \"aluminum\" | \"copper_core\" | \"rogers\" | \"ptfe\" | \"3dp\" | \"cnc\" | \"sheetmetal\", \"name\": \"Main board\", \"source\": \"\", \"qty\": 5, \"options\": {...}, \"features\": {...}}; add \"order\": false for one not to be ordered. Features are measured, never guessed, and kept current whenever the design changes, because Backplane shows the person a price from them: a board's `width_mm` and `height_mm` (its Edge.Cuts box) and `min_drill_mm` (its smallest plated hole, usually a via); a solid's `volume_cm3`, `area_cm2`, `size_x_mm`, `size_y_mm`, `size_z_mm` (FreeCAD: shape.Volume/1000, shape.Area/100, the tightest box, largest first); a sheet part's `flat_x_mm`, `flat_y_mm`, `cut_length_mm`, `holes`, `bends`, `countersinks` (its flat pattern; the last four default to 0). Boards come in kinds: pcb is a rigid FR-4 board; flex a flexible polyimide one; hdi one with microvias and build-up layers; aluminum and copper_core single-layer metal-core boards (LEDs, power); rogers (RO4350B) and ptfe two-layer high-frequency boards. Every board kind is measured and exported the same way; only pcb boards come assembled. Options (any left out take the first value): pcb: layers 1|2|4|6|8|10|12|14|16 (default 2), thickness_mm 1.6|0.4|0.6|0.8|1.0|1.2|2.0, color green|black|white|blue|red|yellow|purple, finish hasl|hasl_lead_free|enig|osp, copper_oz 1|2, castellated, gold_fingers; flex: layers 2|1|4, thickness_mm (the total, which sets the substrate and copper; 1 layer: 0.07|0.11|0.12|0.14, 2 layers: 0.11|0.12|0.19|0.2|0.24, 4 layers: 0.2|0.25|0.3|0.35|0.45; left out, the first for its layers), coverlay yellow|black|white, stiffener none|polyimide_0.1|polyimide_0.15|polyimide_0.2|polyimide_0.225|polyimide_0.25|fr4_0.1|fr4_0.2|fr4_0.4|fr4_0.6|fr4_0.8|fr4_1.0|fr4_1.2|fr4_1.6|steel_0.1|steel_0.2|steel_0.3|tape_3m468|tape_tesa8854|tape_3m9077 (mm), emi_shield none|one_side|both_sides, gold_uin 1|2 (its ENIG gold), gold_fingers; hdi: layers 4|6|8|10|12|14|16, thickness_mm 1.6 (0.6|0.8|1.0|1.2|1.4|1.6|1.8|2.0|2.5|3.0 as the layers allow), steps 1|2|3 (build-up steps: 1 at 4 layers, up to 2 at 6, up to 3 from 8), laminate np175f|s1000_2m (only s1000_2m from 8 layers), color as pcb, finish hasl|hasl_lead_free|enig|osp (only enig|osp from 6 layers), via_fill plugged|untented|epoxy_filled|copper_filled (only epoxy_filled from 6 layers), castellated, gold_fingers, edge_plating; aluminum: thickness_mm 1.6|0.8|1.0|1.2, color white|black, finish hasl|hasl_lead_free; copper_core: thickness_mm 1.6|1.0|1.2, color white|black (OSP); rogers: thickness_mm 0.51|0.76|1.52, color green|purple, finish enig|osp, gold_uin 1|2, via_fill tented|untented; ptfe: thickness_mm 0.76|1.52, laminate dk2.94|dk3.0|dk2.65|dk2.55 (its dielectric constant), finish enig|osp, gold_uin 1|2, via_fill tented|untented; 3dp: process mjf|sla|sls|fdm|slm, material (mjf: pa12|pa11|pa12_glass; sla: standard_resin|black_resin|tough_resin|high_temp_resin|clear_resin; sls: pa12|pa12_glass; fdm: abs|asa|pla|tpu|pa12_cf|pc_abs|peek; slm: stainless_316l|titanium), color, which the material decides (mjf pa12 and pa11: black|gray, pa12_glass: black|white; sla standard_resin: white, black_resin: black, tough_resin: green, high_temp_resin: yellow, clear_resin: translucent|transparent; sls pa12: black, pa12_glass: white; fdm abs and asa: black|white, pla: black|white|red|blue, tpu: black|white|gray|translucent|green, pa12_cf and pc_abs: black, peek: brown; slm: metal); cnc: material aluminum_6061|aluminum_7075|stainless_304|steel_45|steel_q235|brass|copper|abs_black|abs_white|pom_black|pom_white|pmma|nylon|polycarbonate|fr4, finish none|anodize|bead_blast|bead_blast_anodize|hard_anodize|conductive_anodize|brushed|brushed_anodize|laser_mark, tolerance standard|0.1|0.05|0.02; sheetmetal: material aluminum_5052|stainless_304|stainless_201|steel_cold_rolled|steel_galvanized, thickness_mm (0.5 to 6), finish none|powder_coat|anodize|conductive_anodize|hard_anodize. Prefer basic and preferred parts from the fab's own stock when choosing components (the pcbparts tools: jlc_search, jlc_stock_check); every BOM line needs its manufacturer part number (an `MPN` field on the symbol). In what you write, call the manufacturer \"the fab\" and its catalog \"the fab's stock\", never by name (no JLC, LCSC or EasyEDA). Ordering happens only through Backplane: once a part's fab file is ready, the person presses Buy it in the thread's header. It opens a buy thread that checks the design, gets the exact quote from Backplane's order server and takes payment. When the person asks to order, buy or price the project, tell them that. Never order yourself unless the person specifically asks for it in their message: on your own, never open, upload to or fill in a manufacturer's website (the Browser tab included) and never start a thread to order with (thread_launch). When they do ask (say, to work the fab's site in their own browser), do it. Never ask for their payment details: they enter those themselves.\nWhen asked to review the project for manufacturing, check what makes a fab ask questions or refuse, not the circuit: DRC against the fab's limits, taken from the backplane tool `fab_profile` (the project's fab, board kind and options: each limit with its source and date), never from memory; `fab_profile` with action \"drc\" puts them in the project's DRC rules (tracks and gaps, vias, rings, hole and edge clearances, silkscreen: a value under a limit's free value but within the one that costs more is fine but costs more, so say so rather than calling it an error; under both, it must change; where Backplane recommends more than the fab's limit, a design between the two is a note, not a must-change, \"meets the fab's 0.2 mm, under the recommended 0.3 mm\": fab_profile gives Backplane's recommended value with each limit it has one for, as `recommended`), every BOM line has a manufacturer part number that is in stock (pcbparts tools; prefer basic/preferred parts, name extended ones), parts on one side for the cheaper assembly, footprint rotations sane, an outline that is closed, every part to order has a current fab file; for printed parts walls 1 mm or more (0.8 for SLA), for sheet metal flanges at least 4x the thickness and holes at least the thickness from a bend, for CNC inside corners with radii of 1 mm or more and no undercuts. A part whose fab file has a `sendcutsend` block is made for SendCutSend: check it with the sendcutsend skill (`scs.py dfm `, against SendCutSend's live specs), give each failed rule with its source, and call the check stale when the part file no longer matches its `dfm.source_sha256`. Run every check in the foreground (no background commands, monitors or waits) and keep each one short. Start with the backplane tool `design_review` (scope \"order\"): its findings are the deterministic part; then `design_review` with scope \"judged\" and record your datasheet checks with `design_review_judged`. Write the findings to `.backplane/review.md` (per part: what is fine, what must change and why), then call the backplane tool `order_review` with action \"record\", verdict \"ok\" when nothing must change or \"issues\", a one-line summary and issues: what must change, one short line each (\"Shade: walls 0.6 mm, need 0.8 for SLA\"). Your last message is what the thread that asked hears: make it that list and the link `.backplane/review.md`, then end. Change nothing while reviewing: say what must change; the person decides. Call the manufacturer \"the fab\", never by name, except SendCutSend for the parts made for it.\n\nBackplane keeps secrets (API keys, auth keys, tokens, passwords) in a vault you never see into. None is set yet. Use one only through the secret_run tool: `env {VAR: name}` puts it in that command's environment, `files {VAR: name}` writes it to a private temporary file whose path is in VAR (e.g. `tailscale up --auth-key=file:$TS`, `gh auth login --with-token < $GH`); its output comes back with any secret masked. Never ask the person to paste a key, token or password in chat, and never put one in a message, a file or a command line: call secret_request {name, purpose} and end your turn; a message tells you when it is set.", "--add-dir", "/home/h/Documents/i2cjak/backplane-gpui/build/gpui/results/agents/argv2/work/home/attachments", "--settings", "{\"fastMode\":false}", "--mcp-config", "{\"mcpServers\":{\"backplane\":{\"type\":\"http\",\"url\":\"http://127.0.0.1:3845/mcp/t1700000001-2.1793846406-157?k=REDACTED\"},\"pcbparts\":{\"type\":\"http\",\"url\":\"https://pcbparts.dev/mcp\"}}}"] +[ + "-p", + "--verbose", + "--input-format", + "stream-json", + "--output-format", + "stream-json", + "--include-partial-messages", + "--permission-mode", + "bypassPermissions", + "--disallowedTools", + "Agent,Task", + "--append-system-prompt", + "In case you're asked: you are running in Backplane through the Backplane harness. Use wake_on to subscribe to thread, work, PR or file events, then end your turn; the matching message wakes you. No need to mention this otherwise. You can embed images and videos in your response using Markdown with absolute file paths.\n\nTo show the user an image (a board render, plot, screenshot or photo), save it as PNG or JPEG and write its absolute path on its own, e.g. /home/h/x.png (no spaces in the path); it's drawn under your message. Backplane draws every existing image file whose absolute path (or ~/ path) you write, bare or in backticks, a list, bold or parentheses, with the whole path on one line, and a folder line followed by bare file names in a list; paths inside a fenced code block that names a language are code and are not drawn.\n\nBackplane hosts a web browser for you: the backplane MCP server's preview_* tools (preview_open, preview_navigate, preview_snapshot, preview_click, preview_type, preview_press, preview_scroll, preview_evaluate, preview_wait_for). The user watches it live in the app's Browser tab. Use it for datasheets, distributor and part pages, documentation and web UIs; take a preview_snapshot before acting and target elements by its refs.\n\n\n- Use the named KiCad design in the main checkout, including referenced sheets. Use the canonical files by default. Backplane routes design tools there and commits saves to main. Use your thread worktree for code, firmware and docs. Create a labeled alternate board only for an experiment the person requests.\n- Always use IPC to inspect and edit KiCad documents. Start with `kicad_edit {path, ops}`: it batches operations into one commit, takes a free document lock, saves and returns the ERC/DRC delta. Use references and millimetres. Use `rule` and `netclass` for rules and net classes. Use raw `kicad_ipc` only for operations it lacks. Never write .kicad_pcb, .kicad_sch, .kicad_pro or .kicad_dru directly or through scripts while KiCad is open.\n- Edits land live and can be undone in KiCad’s Agents panel. Keep the person’s editor open. The result's `person` field shows selections and edits from the last two minutes. Ask before touching those items or their area and continue elsewhere meanwhile. `ISC_DEFERRED` and `IDS_DEFERRED` edits merge after the person finishes their edit. Check `GetNotices` for the result.\n- Backplane releases document locks when your turn ends. Call `lock_acquire` only when a tool directs you. Keep changes scoped and re-read shared items before changing them.\n- Save every meaningful milestone, including unfinished work. `kicad_edit` saves automatically. For raw IPC, send `SaveDocument`. Read back the saved path, open it with `viewer_show` and verify viewer and history match. Preserve companion .backplane.json metadata and report mismatches.\n\n\n\nFor mechanical work, use FreeCAD in `mech/` and follow the bundled `freecad` skill.\nShow the saved STEP with `viewer_show` (kind `mech`). Optional renderer: `/home/h/Documents/i2cjak/backplane-gpui/build/gpui/backplane-serve-current` with `--render`.\nFreeCAD GUI: `/home/h/.local/bin/freecad`. Console: `/home/h/.local/bin/freecadcmd`.\n\n\nInstall Backplane KiCad from Settings to use editing IPC. Use the selected CLI `/home/h/.local/bin/kicad-cli` for exports and standalone ERC/DRC (`sch erc`, `pcb drc`). `kicad-cli` on your PATH and `$BACKPLANE_KICAD_CLI` select the same runtime.\n\nProject root: `/home/h/Documents/i2cjak/backplane-gpui/build/gpui/results/agents/argv2/work/fixroot`. No KiCad project was found in this project (its root, or folders up to four deep). When you create one, give the .kicad_pro, .kicad_pcb and .kicad_sch the same name so Backplane picks them up, or name it in `.backplane.json`.\nA KiCad project may sit in a folder below the root. To choose which one is canonical (the one Backplane's viewers, the Open in KiCad button and this list follow), write `.backplane.json` in the project root: `{\"project\": \"\"}`; its board and schematic are the files beside it with the same name, or name them with the keys `pcb` and `schematic` (paths from the root). Keep any other keys in that file. Backplane reads it at each turn and whenever a viewer opens. To show the user a board, schematic, 3D model or STEP file, call the backplane MCP tool `viewer_show` with its path.\n\n\n- Use `thread_launch` for a continuing subthread, or `delegate_task` for a bounded task with model selection. Use Backplane for delegation and never spawn provider-native subagents. Set `subthread: false` only for an explicitly requested top-level thread.\n- Give a child the context, paths, acceptance criteria and any permission to write canonical design files. Name applicable skills. Keep one writer per design file. `orchestrator_capabilities` lists providers. Models available: claude (fable, opus, sonnet, haiku); codex (gpt-6.1-sol, gpt-6-astra, gpt-6.1-terra, gpt-6-sol, gpt-6-luna, gpt-5.6-sol, gpt-5.6-terra, gpt-5.6-luna).\n- Use `machine_list` to find paired machines. `thread_list` and `thread_launch` accept `machine`. A remote thread ID has form `~` and works with `thread_send`, `thread_read`, `thread_wait`, `thread_interrupt` and `thread_update`. A `>machine:slug` mention names a remote thread.\n\n\n\n- Start long or detached jobs with `work_run`, or register existing work with `work_watch`.\n- For exclusive jobs, pass a named lock to `work_run`. When you need to hold a lock yourself, use `lock_acquire`, await the grant by ending your turn if queued, and call `lock_release` when done.\n- End your turn after starting work or delegating. Backplane wakes you with the result or reports work lost on restart. Avoid polling and sleep-waiting.\n\n\n`.backplane/intent.md` says what the person is building, in their words: `# Goal` (one or two lines), `# Parts` (a line each: the part, its folder, what it is, whether it is to be ordered) and `# Notes` (only what matters: constraints and choices they made). Keep it short and plain; the person reads and edits it on the project card. At the start of each request that says something new about the goal, the parts or a constraint, update it inline; leave it alone otherwise. Delegate substantial work through Backplane subthreads, never provider-native subagents. Never put progress, plans or todo lists in it.\nLay out a new project as `boards//` (one KiCad project per board), `mech/` (mechanical parts: `.py`, `.FCStd`, `.step`), `extra/` (designed here but never ordered: jigs, test fixtures, references) and `mfg/` (generated manufacturing files; never edit by hand). In a project laid out otherwise, offer once to reorganize it; never move files without the person's OK.\nKeep a measured `.fab.json` beside each part to order and refresh its features after design changes.\nRead the bundled `fab-spec` skill for the schema, measurements and material options. Prefer basic and preferred parts from the fab's own stock when choosing components (the pcbparts tools: jlc_search, jlc_stock_check); every BOM line needs its manufacturer part number (an `MPN` field on the symbol). In what you write, call the manufacturer \"the fab\" and its catalog \"the fab's stock\", never by name (no JLC, LCSC or EasyEDA). Ordering happens only through Backplane: once a part's fab file is ready, the person presses Buy it in the thread's header. It opens a buy thread that checks the design, gets the exact quote from Backplane's order server and takes payment. When the person asks to order, buy or price the project, tell them that. Never order yourself unless the person specifically asks for it in their message: on your own, never open, upload to or fill in a manufacturer's website (the Browser tab included) and never start a thread to order with (thread_launch). When they do ask (say, to work the fab's site in their own browser), do it. Never ask for their payment details: they enter those themselves.\nFor manufacturing or order-readiness reviews, read and follow the bundled `manufacturing-review` skill.\n\nBackplane keeps secrets (API keys, auth keys, tokens, passwords) in a vault you never see into. None is set yet. Use one only through the secret_run tool: `env {VAR: name}` puts it in that command's environment, `files {VAR: name}` writes it to a private temporary file whose path is in VAR (e.g. `tailscale up --auth-key=file:$TS`, `gh auth login --with-token < $GH`); its output comes back with any secret masked. Never ask the person to paste a key, token or password in chat, and never put one in a message, a file or a command line: call secret_request {name, purpose} and end your turn; a message tells you when it is set.", + "--add-dir", + "/home/h/Documents/i2cjak/backplane-gpui/build/gpui/results/agents/argv2/work/home/attachments", + "--settings", + "{\"fastMode\":false}", + "--mcp-config", + "{\"mcpServers\":{\"backplane\":{\"type\":\"http\",\"url\":\"http://127.0.0.1:3845/mcp/t1700000001-2.1793846406-157?k=REDACTED\"},\"pcbparts\":{\"type\":\"http\",\"url\":\"https://pcbparts.dev/mcp\"}}}" +] diff --git a/test/agents/gen_prompt.py b/test/agents/gen_prompt.py deleted file mode 100644 index 5d80cbcdf0..0000000000 --- a/test/agents/gen_prompt.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python3 -"""Extract the string literals of src/core/prompt's text defs into native/host/src/agents/prompt_text.rs. -Each def becomes a const list of its literals in order; prompt.rs assembles them, and a golden test against the argv the -JS hub started a stand-in with (test/agents/fixtures/argv-*.json) checks the result. Run from the repo root.""" -import re, json, sys -SOURCES = [,,,] -out = ['// Generated by test/agents/gen_prompt.py from src/core/prompt, order, secret, apikeys. Do not edit.', '#![allow(dead_code)]', ''] -i = 0 -def lits(lines): - res = [] - for ln in lines: - s = ln.strip() - if s.startswith('#'): continue - j = 0 - while j < len(ln): - if ln[j] == '"': - k = j + 1; buf = [] - while ln[k] != '"': - if ln[k] == '\\': - c = ln[k+1] - if c == 'n': buf.append('\n'); k += 2 - elif c == 't': buf.append('\t'); k += 2 - elif c in '"\\': buf.append(c); k += 2 - elif c == 'u' and ln[k+2] == '{': - e = ln.index('}', k); buf.append(chr(int(ln[k+3:e], 16))); k = e + 1 - else: raise SystemExit('escape ' + ln[k:k+4]) - else: buf.append(ln[k]); k += 1 - res.append(''.join(buf)); j = k + 1 - else: j += 1 - return res -def rust(s): - t = json.dumps(s, ensure_ascii=False) - return re.sub(r'\\u00([0-9a-f]{2})', lambda m: '\\u{%s}' % m.group(1), t) -n = 0 -for path, pre in SOURCES: - src = open(path, encoding='utf-8').read().split('\n') - i = 0 - while i < len(src): - m = re.match(r'def (' + pre + r'[A-Za-z_.]*)\(', src[i]) - if m: - j = i + 1 - while j < len(src) and not re.match(r'(def |# |law |$)', src[j]): j += 1 - ls = lits(src[i:j]) - name = m.group(1).replace('.', '_').upper() - out.append('pub const %s: &[&str] = &[%s];' % (name, ', '.join(rust(x) for x in ls))) - n += 1; i = j - else: i += 1 -open('native/host/src/agents/prompt_text.rs', 'w', encoding='utf-8').write('\n'.join(out) + '\n') -print('wrote', n, 'defs')