Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion native/host/src/agents/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,12 @@ impl Prompt {
let (instructions, project) = instructions_for(cwd, provider, claude);
let discovered = skills::index(env, cwd);
let active = skills::for_model(&discovered, provider, model);
let index = skills::prompt_index(&active, provider, isolated);
let index = if base.contains("</kistack_skills>") {
let filtered: Vec<_> = active.iter().filter(|f| !f.kistack).cloned().collect();
skills::prompt_index(&filtered, provider, isolated)
} else {
skills::prompt_index(&active, provider, isolated)
};
let skills = discovered.iter().map(|s| {
let status = if !active.contains(s) { "Skipped" }
else if skills::native(s, provider, isolated) { "Native" }
Expand Down Expand Up @@ -304,6 +309,14 @@ mod launch_tests {
let claude = prompt("claude", "sonnet");
assert!(claude.skills.iter().any(|row| row["name"] == "deploy" && row["status"] == "Native"));
assert!(!claude.index.contains("command marker"));

// Pinned KiStack skills are omitted from <available_skills> when <kistack_skills> is already in base, while remaining active in skills.
let ks_dir = dir.join("kistack_pin");
put(&ks_dir, "skills/schematic/SKILL.md", "---\nname: kicad-schematic\ndescription: Draw schematics.\n---\nBODY");
let env_ks = crate::agents::skills::env_from(home.to_str().unwrap(), &bundle, Some(&ks_dir));
let codex_with_ks = Prompt::build("<kistack_skills>MANDATORY: ...</kistack_skills>".into(), &env_ks, cwd.to_str().unwrap(), "codex", "gpt-6", false, ClaudeFiles::default());
assert!(!codex_with_ks.index.contains("kicad-schematic"), "no duplicate KiStack entry in <available_skills>");
assert!(codex_with_ks.skills.iter().any(|row| row["name"] == "kicad-schematic" && row["status"] == "Cross-provider"));
}

#[test]
Expand Down
19 changes: 17 additions & 2 deletions native/host/src/agents/kistack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,24 @@ mod tests {
std::fs::write(&stale, "---\nname: kicad-schematic\ndescription: an older copy\n---\nold\n").unwrap();
let ss = crate::agents::skills::scan_all(&env, &home.to_string_lossy());
let f = crate::agents::skills::lookup(&ss, "kicad-schematic").expect("listed");
assert_eq!((f.group.as_str(), f.kind), ("Agents · yours", crate::agents::skills::Kind::Agents), "the user copy wins the name");
assert_eq!((f.group.as_str(), f.kind, f.kistack), ("Backplane", crate::agents::skills::Kind::Hub, true), "pinned KiStack beats user copy");
let fk = crate::agents::skills::lookup(&ss, "kistack:kicad-schematic").expect("plugin name lookup");
assert_eq!(fk.path, f.path);
assert_eq!(ss.iter().filter(|f| f.name == "kicad-schematic" && f.kind == crate::agents::skills::Kind::Hub).count(), 1, "one entry, not one per root");
assert!(crate::agents::skills::prepare("$kicad-schematic draw it", &ss, "codex", false).replace('\\', "/").contains(".agents/skills/schematic/SKILL.md"), "Codex is told the user file");
for (prov, model) in [("claude", "fable"), ("codex", "gpt-6")] {
let active = crate::agents::skills::for_model(&ss, prov, model);
let picked = active.iter().find(|s| s.name == "kicad-schematic").expect("kicad-schematic in for_model");
assert!(picked.kistack && picked.path.replace('\\', "/").contains("hub/kistack/skills/schematic/SKILL.md"), "{prov} picked {}", picked.path);
}
assert!(crate::agents::skills::prepare("$kicad-schematic draw it", &ss, "codex", false).replace('\\', "/").contains("hub/kistack/skills/schematic/SKILL.md"), "Codex is told the pinned KiStack file");
// a project-scoped override still wins over pinned KiStack when cwd is inside that project
let proj = h.join("proj"); let ovr = proj.join(".backplane/skills/schematic/SKILL.md");
std::fs::create_dir_all(ovr.parent().unwrap()).unwrap();
std::fs::write(&ovr, "---\nname: kicad-schematic\ndescription: project override\n---\nproj\n").unwrap();
let pss = crate::agents::skills::scan_all(&env, &proj.to_string_lossy());
let pf = crate::agents::skills::lookup(&pss, "kicad-schematic").expect("project override");
assert_eq!(pf.scope, "Project");
assert!(pf.path.replace('\\', "/").contains(".backplane/skills/schematic/SKILL.md"));
let _ = std::fs::remove_dir_all(&h);
}
}
101 changes: 100 additions & 1 deletion native/host/src/agents/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,32 @@ pub trait ToolSet: Send + Sync {
pub fn altium_next(spec: &Value) -> Option<&'static str> {
spec.get("schdoc").filter(|v| v.is_object()).map(|_| "Look at the sheet now (viewer_show) and check it against KiStack's kicad-schematic rules: signal left to right, power ports up and ground down, wires between nearby pins, parts spread over the sheet, no text over a part or another text. Fix what fails before the next step.")
}

/// Deterministic wall-of-labels lint for an `altium_write` `schdoc` spec.
pub fn altium_schdoc_lint(spec: &Value) -> Option<Value> {
let schdoc = spec.get("schdoc")?.as_object()?;
let parts = schdoc.get("place").and_then(Value::as_array).map_or(0, Vec::len);
let label_connects = schdoc.get("connect").and_then(Value::as_array).map_or(0, |a| {
a.iter().filter(|c| {
let is_power = c.get("power").is_some_and(|p| !p.is_null() && *p != json!(false));
let is_nc = c.get("net").and_then(Value::as_str).is_some_and(|n| n.eq_ignore_ascii_case("NC"));
!is_power && !is_nc
}).count()
});
let labels = schdoc.get("labels").and_then(Value::as_array).map_or(0, Vec::len);
let wires = schdoc.get("wires").and_then(Value::as_array).map_or(0, Vec::len);
let net_stubs = label_connects + labels;
if parts >= 3 && net_stubs >= 6 && (wires == 0 || (wires < parts && net_stubs > wires * 2)) {
return Some(json!({
"warnings": [
format!("Wall-of-labels schematic pattern: placed {parts} parts with {net_stubs} connect/label entries ({label_connects} connect, {labels} labels) and only {wires} explicit wire(s). Follow KiStack's kicad-schematic skill: wire passives directly to IC pins with `wires`, group decoupling capacitors onto shared rails, box and label subcircuits, and reserve net labels for inter-block signals.")
],
"stats": {"parts": parts, "connects": label_connects, "labels": labels, "wires": wires},
"next": "Load and follow KiStack's kicad-schematic skill, replace floating pin labels on passives with direct wires, box subcircuits, and visually inspect the rendered sheet."
}));
}
None
}
pub const TOOLS_JSON: &str = include_str!("../../../../test/agents/fixtures/mcp-tools.json");
pub const IMPLEMENTED: &[&str] = &["orchestrator_capabilities", "review_comment", "review_comments", "work_run", "work_watch", "work_list", "work_cancel", "work_unwatch", "lock_acquire", "lock_release", "lock_cancel", "lock_list", "account_list", "thread_launch", "machine_list", "delegate_task", "task_status", "task_cancel", "thread_list", "thread_read", "thread_send", "thread_reply", "thread_update", "thread_wait", "thread_interrupt", "thread_settle", "viewer_show", "permission_prompt", "kicad_ipc", "kicad_edit", "kicad_ipc_status", "kicad_select", "kicad_bring_back", "altium_status", "altium_script", "altium_write", "terminal_open", "terminal_read", "terminal_send", "terminal_close", "preview_open", "preview_navigate", "preview_snapshot", "preview_click", "preview_type", "preview_press", "preview_scroll", "preview_evaluate", "preview_wait_for", "preview_resize", "preview_status", "secret_request", "secret_list", "secret_run", "settings_inspect", "settings_propose"];
const MAX_BODY: usize = 4 << 20;
Expand Down Expand Up @@ -305,7 +331,7 @@ impl Mcp {
let spec = a.clone();
let ran = tokio::task::spawn_blocking(move || crate::files::altium::write::spec::run(&spec, std::path::Path::new(&base))).await;
match ran {
Ok(Ok((v, _written))) => { let added = crate::files::altium::write::spec::project_added(&v); let mut out = crate::files::altium::live::after_write(&ss, v, &open, &added).await; if let (Some(n), Some(o)) = (altium_next(&a), out.as_object_mut()) { o.insert("next".into(), json!(n)); } (true, out) }
Ok(Ok((v, _written))) => { let added = crate::files::altium::write::spec::project_added(&v); let mut out = crate::files::altium::live::after_write(&ss, v, &open, &added).await; if let (Some(n), Some(o)) = (altium_next(&a), out.as_object_mut()) { o.insert("next".into(), json!(n)); } if let (Some(lint), Some(o)) = (altium_schdoc_lint(&a), out.as_object_mut()) { o.insert("schematic_lint".into(), lint); } (true, out) }
Ok(Err(e)) => { let _ = crate::files::altium::live::after_write(&ss, json!({}), &open, &[]).await; fail(&e) }
Err(e) => { let _ = crate::files::altium::live::after_write(&ss, json!({}), &open, &[]).await; fail(&e.to_string()) }
}
Expand Down Expand Up @@ -400,6 +426,79 @@ mod tests {
#[test] fn the_tool_list_is_the_js_hubs_for_every_tool_we_serve() {
let all: Value = serde_json::from_str(TOOLS_JSON).unwrap(); let names: Vec<&str> = all["result"]["tools"].as_array().unwrap().iter().map(|t| sv(t, "name")).collect();
for n in IMPLEMENTED { assert!(names.contains(n), "{n} is not a tool the JS hub lists") }
let ke = all["result"]["tools"].as_array().unwrap().iter().find(|t| sv(t, "name") == "kicad_edit").unwrap();
let desc = sv(ke, "description");
assert!(desc.contains("load and follow the matching KiStack skill") && desc.contains("kistack:kicad-schematic"), "{desc}");
assert!(!desc.contains("do not read or render the sheet to find room or to check the result"), "{desc}");
}
#[test] fn altium_schdoc_lint_flags_wall_of_labels_and_stays_quiet_when_wired() {
let wall = json!({
"schdoc": {
"path": "Main.SchDoc",
"place": [
{"symbol": "MCU", "designator": "U1", "at": [1000, 1000]},
{"symbol": "RES", "designator": "R1", "at": [2000, 1000]},
{"symbol": "CAP", "designator": "C1", "at": [3000, 1000]}
],
"connect": [
{"pin": "U1.1", "net": "VCC"},
{"pin": "U1.2", "net": "GND"},
{"pin": "U1.3", "net": "SDA"},
{"pin": "U1.4", "net": "SCL"},
{"pin": "R1.1", "net": "SDA"},
{"pin": "C1.1", "net": "VCC"}
],
"wires": []
}
});
let lint = altium_schdoc_lint(&wall).expect("wall-of-labels schdoc should trigger lint");
assert!(lint["warnings"][0].as_str().unwrap().contains("Wall-of-labels schematic pattern"), "{lint}");
assert_eq!(lint["stats"]["parts"], 3);
assert_eq!(lint["stats"]["wires"], 0);

let wired = json!({
"schdoc": {
"path": "Main.SchDoc",
"place": [
{"symbol": "MCU", "designator": "U1", "at": [1000, 1000]},
{"symbol": "RES", "designator": "R1", "at": [1500, 1000]},
{"symbol": "CAP", "designator": "C1", "at": [1500, 800]}
],
"connect": [
{"pin": "U1.1", "net": "VCC", "power": true},
{"pin": "U1.2", "net": "GND", "power": true}
],
"wires": [
[[1200, 1000], [1400, 1000]],
[[1200, 900], [1400, 900]],
[[1500, 900], [1500, 850]]
]
}
});
assert!(altium_schdoc_lint(&wired).is_none());

let power_only = json!({
"schdoc": {
"path": "Power.SchDoc",
"place": [
{"symbol": "LDO", "designator": "U1", "at": [1000, 1000]},
{"symbol": "CAP", "designator": "C1", "at": [1500, 1000]},
{"symbol": "CAP", "designator": "C2", "at": [2000, 1000]}
],
"connect": [
{"pin": "U1.1", "net": "VIN", "power": true},
{"pin": "U1.2", "net": "GND", "power": true},
{"pin": "U1.3", "net": "+3V3", "power": "bar"},
{"pin": "U1.4", "net": "NC"},
{"pin": "C1.1", "net": "+3V3", "power": true},
{"pin": "C1.2", "net": "GND", "power": true},
{"pin": "C2.1", "net": "VIN", "power": true},
{"pin": "C2.2", "net": "GND", "power": true}
],
"wires": []
}
});
assert!(altium_schdoc_lint(&power_only).is_none(), "power/NC connects should not trigger wall-of-labels");
}
}

Expand Down
5 changes: 3 additions & 2 deletions native/host/src/agents/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,10 @@ impl Agents {
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());
let kistack = host.kistack.as_deref().map(kistack::describe);
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,
// The context index supplies the skill catalog once, with provider scoping and overrides.
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: vec![], kistack: None })
// Keep `<kistack_skills>` in the base prompt so every provider (including Claude with `--plugin-dir` and brand-new projects with no KiCad files yet) sees the mandatory KiStack workflow directive and pinned `SKILL.md` paths untruncated by `<available_skills>`.
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: vec![], kistack })
}).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).
Expand Down
Loading
Loading