-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathconfig.rs
More file actions
623 lines (569 loc) · 23.2 KB
/
Copy pathconfig.rs
File metadata and controls
623 lines (569 loc) · 23.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! `config` toolset — User preferences, project rules, and effective configuration.
//!
//! Persists user-level config to `~/.konnect/config.json` and project-level
//! config to `<project_dir>/.konnect/project.json`. Claude should call
//! `load_user_config` at the start of every session.
use crate::mcp::protocol::CallToolResult;
use crate::tool;
use crate::tools::{require_str, ToolContext, ToolDef};
use serde_json::json;
use std::path::{Path, PathBuf};
use tracing::{debug, info};
// ─── Default config ──────────────────────────────────────────────────────────
fn default_user_config() -> serde_json::Value {
json!({
"preferred_manufacturers": [],
"preferred_distributors": ["JLCPCB", "LCSC"],
"default_passives": {
"decoupling_cap": "100nF X7R 0402",
"pull_up": "10k 0402",
"bulk_cap": "10uF X5R 0805"
},
"fab_constraints": {
"min_trace_width_mm": 0.15,
"min_via_drill_mm": 0.3,
"min_clearance_mm": 0.15,
"layer_count": 2,
"fab_house": "JLCPCB"
},
"naming_conventions": {
"net_prefix_power": "VCC_",
"net_prefix_ground": "GND"
},
"design_rules": [],
// Sourcing policy consumed by the upcoming derating/AVL checks.
// Derating limits are max operating/rated utilization — conservative
// general practice, not MIL-HDBK-217. An empty AVL means "not
// enforced", which those checks report as a warning, never a pass.
"sourcing": {
"avl": [],
"derating": {
"capacitor": { "voltage": 0.80 },
"resistor": { "power": 0.60 },
"inductor": { "current": 0.80 },
"mosfet": { "vds": 0.80, "id": 0.80 },
"diode": { "vr": 0.80, "if": 0.80 },
"led": { "if": 0.80 },
"connector": { "current": 0.80 },
"regulator": { "power": 0.70, "current": 0.80 }
}
}
})
}
fn default_project_config() -> serde_json::Value {
json!({
"design_rules": [],
"fab_constraints": {},
"naming_conventions": {},
// Project-side sourcing overrides. NOTE: deep_merge REPLACES arrays,
// so a project-level "avl" supersedes the user list entirely rather
// than appending to it — the same semantics design_rules has.
"sourcing": {}
})
}
// ─── Config file paths ───────────────────────────────────────────────────────
fn user_config_dir() -> PathBuf {
#[cfg(target_os = "windows")]
{
let appdata = std::env::var("APPDATA").unwrap_or_default();
PathBuf::from(appdata).join("konnect")
}
#[cfg(target_os = "macos")]
{
let home = std::env::var("HOME").unwrap_or_default();
PathBuf::from(home)
.join("Library")
.join("Application Support")
.join("konnect")
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
{
let home = std::env::var("HOME").unwrap_or_default();
PathBuf::from(home).join(".konnect")
}
}
fn user_config_path() -> PathBuf {
user_config_dir().join("config.json")
}
fn project_config_path(project_dir: &Path) -> PathBuf {
project_dir.join(".konnect").join("project.json")
}
// ─── Config I/O helpers ──────────────────────────────────────────────────────
async fn read_config(path: &Path, default: serde_json::Value) -> serde_json::Value {
match tokio::fs::read_to_string(path).await {
Ok(content) => serde_json::from_str(&content).unwrap_or(default),
Err(_) => default,
}
}
async fn write_config(path: &Path, config: &serde_json::Value) -> anyhow::Result<()> {
if let Some(parent) = path.parent() {
tokio::fs::create_dir_all(parent).await?;
}
let content = serde_json::to_string_pretty(config)?;
tokio::fs::write(path, content).await?;
Ok(())
}
/// Deep merge: overlay values onto base. overlay takes precedence.
fn deep_merge(base: &serde_json::Value, overlay: &serde_json::Value) -> serde_json::Value {
match (base, overlay) {
(serde_json::Value::Object(b), serde_json::Value::Object(o)) => {
let mut merged = b.clone();
for (key, val) in o {
let base_val = merged.get(key).cloned().unwrap_or(serde_json::Value::Null);
merged.insert(key.clone(), deep_merge(&base_val, val));
}
serde_json::Value::Object(merged)
}
(_, overlay) if !overlay.is_null() => overlay.clone(),
(base, _) => base.clone(),
}
}
/// Set a value at a dot-notation path, e.g. "fab_constraints.fab_house" = "JLCPCB".
///
/// Fails with an error (instead of panicking) if a segment of the path already
/// holds a non-object value, since there is nowhere to insert the child key.
fn set_dot_path(
config: &mut serde_json::Value,
key_path: &str,
value: serde_json::Value,
) -> anyhow::Result<()> {
let parts: Vec<&str> = key_path.split('.').collect();
let mut current = config;
for (i, part) in parts.iter().enumerate() {
if i == parts.len() - 1 {
// Last part — set the value
return match current {
serde_json::Value::Object(map) => {
map.insert(part.to_string(), value);
Ok(())
}
other => anyhow::bail!(
"Cannot set '{key_path}': '{}' is not an object (found {})",
parts[..i].join("."),
json_type_name(other)
),
};
}
// Navigate into nested object, creating it if missing.
if !current.get(*part).map(|v| v.is_object()).unwrap_or(false) {
match current {
serde_json::Value::Object(map) => {
map.insert(part.to_string(), json!({}));
}
other => anyhow::bail!(
"Cannot set '{key_path}': '{}' is not an object (found {})",
parts[..i].join("."),
json_type_name(other)
),
}
}
current = current
.get_mut(*part)
.expect("just verified or inserted as an object above");
}
Ok(())
}
fn json_type_name(value: &serde_json::Value) -> &'static str {
match value {
serde_json::Value::Null => "null",
serde_json::Value::Bool(_) => "boolean",
serde_json::Value::Number(_) => "number",
serde_json::Value::String(_) => "string",
serde_json::Value::Array(_) => "array",
serde_json::Value::Object(_) => "object",
}
}
// ─── Tool definitions ─────────────────────────────────────────────────────────
pub fn tools() -> Vec<ToolDef> {
vec![
tool!(
"load_user_config",
"Load the user's global Konnect preferences. Call this at the start of every session \
to get preferred manufacturers, fab constraints, default passives, and design rules.",
json!({
"type": "object",
"properties": {},
"required": []
}),
|args, ctx| async move { handle_load_user_config(args, ctx).await }
),
tool!(
"save_user_config",
"Update a user preference. Use dot-notation for nested keys, e.g. 'fab_constraints.fab_house'. \
Call this when the user says things like 'always use JLCPCB' or 'I prefer 0402 passives'.",
json!({
"type": "object",
"properties": {
"key_path": {
"type": "string",
"description": "Dot-notation path to the config key, e.g. 'fab_constraints.fab_house' or 'default_passives.decoupling_cap'"
},
"value": {
"description": "New value to set (string, number, array, or object)"
}
},
"required": ["key_path", "value"]
}),
|args, ctx| async move { handle_save_user_config(args, ctx).await }
),
tool!(
"load_project_config",
"Load project-specific configuration from <project_dir>/.konnect/project.json. \
Project config overrides user config where both exist.",
json!({
"type": "object",
"properties": {
"project_dir": {
"type": "string",
"description": "Path to the KiCAD project directory. If omitted, uses the configured project_dir."
}
},
"required": []
}),
|args, ctx| async move { handle_load_project_config(args, ctx).await }
),
tool!(
"save_project_config",
"Save a project-specific rule or override. Same dot-notation as save_user_config \
but writes to the project's .konnect/project.json.",
json!({
"type": "object",
"properties": {
"project_dir": { "type": "string", "description": "Project directory (optional, uses configured default)" },
"key_path": { "type": "string", "description": "Dot-notation config key" },
"value": { "description": "New value to set" }
},
"required": ["key_path", "value"]
}),
|args, ctx| async move { handle_save_project_config(args, ctx).await }
),
tool!(
"get_effective_config",
"Return the merged configuration (user defaults + project overrides). \
This is the config Claude should use for all design decisions.",
json!({
"type": "object",
"properties": {
"project_dir": { "type": "string", "description": "Project directory (optional)" }
},
"required": []
}),
|args, ctx| async move { handle_get_effective_config(args, ctx).await }
),
tool!(
"add_design_rule",
"Add a natural-language design rule that Claude should follow in this project. \
Examples: 'Always use 100nF X7R for MCU decoupling within 3mm of power pin', \
'Route USB D+/D- as 90-ohm differential pair'.",
json!({
"type": "object",
"properties": {
"rule": { "type": "string", "description": "The design rule in plain English" },
"scope": {
"type": "string",
"description": "'user' (applies to all projects) or 'project' (this project only)",
"default": "project"
},
"project_dir": { "type": "string", "description": "Project directory (for project-scoped rules)" }
},
"required": ["rule"]
}),
|args, ctx| async move { handle_add_design_rule(args, ctx).await }
),
tool!(
"list_design_rules",
"List all active design rules (user-level + project-level).",
json!({
"type": "object",
"properties": {
"project_dir": { "type": "string", "description": "Project directory (optional)" }
},
"required": []
}),
|args, ctx| async move { handle_list_design_rules(args, ctx).await }
),
]
}
// ─── Handlers ─────────────────────────────────────────────────────────────────
async fn handle_load_user_config(
_args: &serde_json::Value,
_ctx: &ToolContext,
) -> anyhow::Result<CallToolResult> {
let path = user_config_path();
info!(path = %path.display(), "[BETA] Loading user config");
let config = read_config(&path, default_user_config()).await;
// Create default config file if it doesn't exist
if !path.exists() {
debug!("[BETA] Creating default user config at {}", path.display());
let _ = write_config(&path, &config).await;
}
Ok(CallToolResult::text(
serde_json::to_string(&json!({
"config": config,
"path": path.to_str().unwrap_or(""),
"note": "User preferences loaded. Project config may override these values."
}))
.unwrap(),
))
}
async fn handle_save_user_config(
args: &serde_json::Value,
_ctx: &ToolContext,
) -> anyhow::Result<CallToolResult> {
let key_path = match require_str(args, "key_path") {
Ok(v) => v.to_string(),
Err(e) => return Ok(e),
};
let value = args["value"].clone();
if value.is_null() {
return Ok(CallToolResult::error("Missing required argument: 'value'"));
}
let path = user_config_path();
info!(key_path = %key_path, "[BETA] Saving user config");
let mut config = read_config(&path, default_user_config()).await;
set_dot_path(&mut config, &key_path, value.clone())?;
write_config(&path, &config).await?;
Ok(CallToolResult::text(
serde_json::to_string(&json!({
"updated": key_path,
"value": value,
"config": config
}))
.unwrap(),
))
}
async fn handle_load_project_config(
args: &serde_json::Value,
ctx: &ToolContext,
) -> anyhow::Result<CallToolResult> {
let project_dir = resolve_project_dir(args, ctx)?;
let path = project_config_path(&project_dir);
info!(path = %path.display(), "[BETA] Loading project config");
let config = read_config(&path, default_project_config()).await;
Ok(CallToolResult::text(
serde_json::to_string(&json!({
"config": config,
"project_dir": project_dir.to_str().unwrap_or(""),
"path": path.to_str().unwrap_or("")
}))
.unwrap(),
))
}
async fn handle_save_project_config(
args: &serde_json::Value,
ctx: &ToolContext,
) -> anyhow::Result<CallToolResult> {
let project_dir = resolve_project_dir(args, ctx)?;
let key_path = match require_str(args, "key_path") {
Ok(v) => v.to_string(),
Err(e) => return Ok(e),
};
let value = args["value"].clone();
if value.is_null() {
return Ok(CallToolResult::error("Missing required argument: 'value'"));
}
let path = project_config_path(&project_dir);
let mut config = read_config(&path, default_project_config()).await;
set_dot_path(&mut config, &key_path, value.clone())?;
write_config(&path, &config).await?;
Ok(CallToolResult::text(
serde_json::to_string(&json!({
"updated": key_path,
"value": value,
"project_dir": project_dir.to_str().unwrap_or("")
}))
.unwrap(),
))
}
async fn handle_get_effective_config(
args: &serde_json::Value,
ctx: &ToolContext,
) -> anyhow::Result<CallToolResult> {
let user_config = read_config(&user_config_path(), default_user_config()).await;
let project_config = if let Ok(project_dir) = resolve_project_dir(args, ctx) {
let path = project_config_path(&project_dir);
read_config(&path, default_project_config()).await
} else {
default_project_config()
};
let effective = deep_merge(&user_config, &project_config);
Ok(CallToolResult::text(
serde_json::to_string(&json!({
"effective_config": effective,
"note": "Merged user defaults + project overrides. Use these values for all design decisions."
}))
.unwrap(),
))
}
async fn handle_add_design_rule(
args: &serde_json::Value,
ctx: &ToolContext,
) -> anyhow::Result<CallToolResult> {
let rule = match require_str(args, "rule") {
Ok(v) => v.to_string(),
Err(e) => return Ok(e),
};
let scope = args["scope"].as_str().unwrap_or("project");
if scope == "user" {
let path = user_config_path();
let mut config = read_config(&path, default_user_config()).await;
let rules = config["design_rules"].as_array_mut();
if let Some(rules) = rules {
rules.push(json!(rule));
} else {
config["design_rules"] = json!([rule]);
}
write_config(&path, &config).await?;
} else {
let project_dir = resolve_project_dir(args, ctx)?;
let path = project_config_path(&project_dir);
let mut config = read_config(&path, default_project_config()).await;
let rules = config["design_rules"].as_array_mut();
if let Some(rules) = rules {
rules.push(json!(rule));
} else {
config["design_rules"] = json!([rule]);
}
write_config(&path, &config).await?;
}
Ok(CallToolResult::text(
serde_json::to_string(&json!({
"added_rule": rule,
"scope": scope
}))
.unwrap(),
))
}
async fn handle_list_design_rules(
args: &serde_json::Value,
ctx: &ToolContext,
) -> anyhow::Result<CallToolResult> {
let user_config = read_config(&user_config_path(), default_user_config()).await;
let user_rules: Vec<String> = user_config["design_rules"]
.as_array()
.map(|a| {
a.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
let project_rules: Vec<String> = if let Ok(project_dir) = resolve_project_dir(args, ctx) {
let path = project_config_path(&project_dir);
let config = read_config(&path, default_project_config()).await;
config["design_rules"]
.as_array()
.map(|a| {
a.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default()
} else {
Vec::new()
};
Ok(CallToolResult::text(
serde_json::to_string(&json!({
"user_rules": user_rules,
"project_rules": project_rules,
"total": user_rules.len() + project_rules.len()
}))
.unwrap(),
))
}
// ─── Helpers ─────────────────────────────────────────────────────────────────
fn resolve_project_dir(args: &serde_json::Value, ctx: &ToolContext) -> anyhow::Result<PathBuf> {
if let Some(dir) = args["project_dir"].as_str() {
return Ok(PathBuf::from(dir));
}
if let Some(ref dir) = ctx.config.project_dir {
return Ok(dir.clone());
}
anyhow::bail!("No project directory specified. Pass 'project_dir' or configure a default.")
}
#[cfg(test)]
mod dot_path_and_merge_tests {
use super::*;
#[test]
fn deep_merge_overlays_nested_object_keys() {
let base = json!({
"fab_constraints": { "fab_house": "JLCPCB", "layer_count": 2 },
"design_rules": []
});
let overlay = json!({
"fab_constraints": { "layer_count": 4 }
});
let merged = deep_merge(&base, &overlay);
assert_eq!(merged["fab_constraints"]["fab_house"], "JLCPCB");
assert_eq!(merged["fab_constraints"]["layer_count"], 4);
assert_eq!(merged["design_rules"], json!([]));
}
/// The sourcing policy the derating/AVL checks read must exist in the
/// defaults with the documented limits — a missing key would make those
/// checks silently unenforceable, the #218 class.
#[test]
fn default_sourcing_policy_is_present_with_conservative_limits() {
let user = default_user_config();
assert_eq!(user["sourcing"]["avl"], json!([]));
assert_eq!(user["sourcing"]["derating"]["capacitor"]["voltage"], 0.80);
assert_eq!(user["sourcing"]["derating"]["resistor"]["power"], 0.60);
assert_eq!(user["sourcing"]["derating"]["regulator"]["power"], 0.70);
assert_eq!(default_project_config()["sourcing"], json!({}));
}
/// A project-level AVL REPLACES the user list (deep_merge array
/// semantics) — pinned so a future "append" change is a decision, not
/// an accident.
#[test]
fn project_avl_replaces_user_avl_wholesale() {
let user = json!({ "sourcing": { "avl": ["Murata", "TDK"] } });
let project = json!({ "sourcing": { "avl": ["Vishay"] } });
let merged = deep_merge(&user, &project);
assert_eq!(merged["sourcing"]["avl"], json!(["Vishay"]));
}
#[test]
fn deep_merge_null_overlay_value_keeps_base() {
let base = json!({ "fab_house": "JLCPCB" });
let overlay = json!({ "fab_house": null });
let merged = deep_merge(&base, &overlay);
assert_eq!(merged["fab_house"], "JLCPCB");
}
#[test]
fn set_dot_path_sets_top_level_key() {
let mut config = json!({});
set_dot_path(&mut config, "fab_house", json!("JLCPCB")).expect("should succeed");
assert_eq!(config["fab_house"], "JLCPCB");
}
#[test]
fn set_dot_path_creates_missing_intermediate_objects() {
let mut config = json!({});
set_dot_path(&mut config, "fab_constraints.fab_house", json!("JLCPCB"))
.expect("should succeed");
assert_eq!(config["fab_constraints"]["fab_house"], "JLCPCB");
}
#[test]
fn set_dot_path_overwrites_existing_nested_value() {
let mut config = json!({ "fab_constraints": { "fab_house": "PCBWay" } });
set_dot_path(&mut config, "fab_constraints.fab_house", json!("JLCPCB"))
.expect("should succeed");
assert_eq!(config["fab_constraints"]["fab_house"], "JLCPCB");
}
#[test]
fn set_dot_path_errors_instead_of_panicking_on_non_object_root() {
// Regression test: a corrupted config file that parses as valid JSON
// but isn't a `{...}` object used to make this function panic via
// `.unwrap()` on a failed `get_mut`, crashing the whole server.
let mut config = json!(null);
let result = set_dot_path(&mut config, "fab_constraints.fab_house", json!("JLCPCB"));
assert!(result.is_err());
}
#[test]
fn set_dot_path_replaces_scalar_intermediate_segment_with_object() {
// "fab_constraints" already holds a string, not an object. The parent
// (root) is still an object, so it's free to replace that key with a
// fresh nested object rather than erroring — this matches the
// function's pre-existing "create if needed" behavior.
let mut config = json!({ "fab_constraints": "JLCPCB" });
set_dot_path(&mut config, "fab_constraints.fab_house", json!("PCBWay"))
.expect("should succeed by replacing the scalar with an object");
assert_eq!(config["fab_constraints"]["fab_house"], "PCBWay");
}
}