aimdb-mcp 0.8.0

Model Context Protocol (MCP) server for AimDB - enables LLM-powered introspection
Documentation
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! Architecture agent MCP tools (M11)
//!
//! Provides typed proposal tools for the architecture agent ideation loop:
//! `get_architecture`, `propose_add_record`, `propose_modify_buffer`,
//! `propose_add_connector`, `propose_modify_fields`, `propose_modify_key_variants`,
//! `propose_add_task`, `propose_add_binary`,
//! `resolve_proposal`, `remove_record`, `rename_record`, `remove_task`, `remove_binary`,
//! `validate_against_instance`, `reset_session`.
//!
//! All proposal-related tools are routed through the session state machine,
//! which enforces: `Idle → Gathering → Proposing → (resolve) → Gathering`.

use crate::architecture::conflicts::{detect_conflicts, LiveRecord};
use crate::architecture::session::next_proposal_id;
use crate::architecture::{
    self, apply_change, default_memory_path, default_mermaid_path, default_rust_path,
    default_state_path, ensure_state_initialised, session_store, write_artefacts,
    write_state_locked, Proposal, ProposalResolution, ProposedChange,
};
use crate::error::{McpError, McpResult};
use aimdb_client::AimxClient;
use serde::Deserialize;
use serde_json::Value;
use tracing::debug;

// ── get_architecture ──────────────────────────────────────────────────────────

/// Return the current architecture state as structured JSON.
///
/// Side-effect: creates a session if none exists, transitions Idle → Gathering.
pub async fn get_architecture(args: Option<Value>) -> McpResult<Value> {
    debug!("get_architecture called");

    #[derive(Debug, Deserialize, Default)]
    struct Params {
        #[serde(default)]
        state_path: Option<String>,
    }
    let params: Params = parse_optional(args)?;
    let path = params
        .state_path
        .map(std::path::PathBuf::from)
        .unwrap_or_else(default_state_path);

    // Transition: Idle → Gathering (or no-op if already in session)
    let store = session_store()
        .ok_or_else(|| McpError::Internal("Session store not initialised".to_string()))?;
    let session_info = {
        let mut locked = store
            .lock()
            .map_err(|e| McpError::Internal(format!("session store poisoned: {e}")))?;
        let session = locked.on_get_architecture();
        serde_json::to_value(session).unwrap_or_default()
    };

    match architecture::read_state(&path).map_err(|e| McpError::Internal(e.to_string()))? {
        None => Ok(serde_json::json!({
            "exists": false,
            "message": format!(
                "No state.toml found at {}. Start an architecture session with the onboarding prompt.",
                path.display()
            ),
            "session": session_info,
        })),
        Some(state) => {
            let errors = aimdb_codegen::validate(&state);
            let result = serde_json::json!({
                "exists": true,
                "state": serde_json::to_value(&state)?,
                "record_count": state.records.len(),
                "decision_count": state.decisions.len(),
                "validation_errors": errors.iter().filter(|e| e.severity == aimdb_codegen::Severity::Error).count(),
                "validation_warnings": errors.iter().filter(|e| e.severity == aimdb_codegen::Severity::Warning).count(),
                "session": session_info,
            });
            Ok(result)
        }
    }
}

// ── propose_* typed tools ─────────────────────────────────────────────────────
//
// Each tool has a concrete, fully-specified JSON Schema exposed to the MCP
// client so AI agents never have to guess payload structure. Error messages
// include the expected schema as a self-describing hint.

// Shared helper: push a Proposal into the session store and return its ID.
fn submit_proposal(proposal: Proposal) -> McpResult<String> {
    let store = session_store()
        .ok_or_else(|| McpError::Internal("Session store not initialised".to_string()))?;
    let mut locked = store
        .lock()
        .map_err(|e| McpError::Internal(format!("session store poisoned: {e}")))?;
    let p = locked.on_propose(proposal).map_err(|e| {
        McpError::InvalidParams(format!("Cannot propose in current session state: {e}"))
    })?;
    Ok(p.id.clone())
}

// ── propose_add_record ────────────────────────────────────────────────────────

/// Add a new record. All fields are fully typed — no payload guessing required.
pub async fn propose_add_record(args: Option<Value>) -> McpResult<Value> {
    debug!("propose_add_record called");

    const SCHEMA_HINT: &str = concat!(
        "Expected fields:\n",
        "  name        : string  — PascalCase record name (required)\n",
        "  buffer      : string  — \"SpmcRing\" | \"SingleLatest\" | \"Mailbox\" (required)\n",
        "  capacity    : number  — required when buffer = \"SpmcRing\"\n",
        "  description : string  — human-readable description shown to the user (required)\n",
        "  key_prefix  : string  — common key prefix, e.g. \"sensors.temp.\" (optional, default \"\")\n",
        "  key_variants: string[] — concrete variant names, e.g. [\"Default\"] (optional, default [])\n",
        "  producers   : string[] — task names that write to this record (optional)\n",
        "  consumers   : string[] — task names that read from this record (optional)\n",
        "  fields      : [{name, type, description}][] — value struct fields (optional)\n",
        "  connectors  : [{protocol, direction, url}][] — connector wiring (optional)"
    );

    #[derive(Debug, Deserialize)]
    struct Params {
        description: String,
        #[serde(flatten)]
        record: aimdb_codegen::RecordDef,
    }

    let p: Params = serde_json::from_value(args.unwrap_or(Value::Null)).map_err(|e| {
        McpError::InvalidParams(format!("propose_add_record: {e}\n\n{SCHEMA_HINT}"))
    })?;

    let proposal_id = submit_proposal(Proposal {
        id: next_proposal_id(),
        change_type: "add_record".to_string(),
        description: p.description,
        change: ProposedChange::AddRecord { record: p.record },
        created_at: chrono::Utc::now().to_rfc3339(),
    })?;

    Ok(serde_json::json!({
        "proposal_id": proposal_id,
        "message": "Proposal created. Present it to the user and call resolve_proposal with their decision.",
    }))
}

// ── propose_modify_buffer ─────────────────────────────────────────────────────

/// Change the buffer type (and optionally capacity) of an existing record.
pub async fn propose_modify_buffer(args: Option<Value>) -> McpResult<Value> {
    debug!("propose_modify_buffer called");

    const SCHEMA_HINT: &str = concat!(
        "Expected fields:\n",
        "  record_name : string — PascalCase name of existing record (required)\n",
        "  description : string — human-readable description shown to the user (required)\n",
        "  buffer      : string — \"SpmcRing\" | \"SingleLatest\" | \"Mailbox\" (required)\n",
        "  capacity    : number — required when buffer = \"SpmcRing\""
    );

    #[derive(Debug, Deserialize)]
    struct Params {
        record_name: String,
        description: String,
        buffer: aimdb_codegen::BufferType,
        capacity: Option<usize>,
    }

    let p: Params = serde_json::from_value(args.unwrap_or(Value::Null)).map_err(|e| {
        McpError::InvalidParams(format!("propose_modify_buffer: {e}\n\n{SCHEMA_HINT}"))
    })?;

    let proposal_id = submit_proposal(Proposal {
        id: next_proposal_id(),
        change_type: "modify_buffer".to_string(),
        description: p.description,
        change: ProposedChange::ModifyBuffer {
            record_name: p.record_name,
            buffer: p.buffer,
            capacity: p.capacity,
        },
        created_at: chrono::Utc::now().to_rfc3339(),
    })?;

    Ok(serde_json::json!({
        "proposal_id": proposal_id,
        "message": "Proposal created. Present it to the user and call resolve_proposal with their decision.",
    }))
}

// ── propose_add_connector ─────────────────────────────────────────────────────

/// Add a connector (MQTT, KNX, etc.) to an existing record.
pub async fn propose_add_connector(args: Option<Value>) -> McpResult<Value> {
    debug!("propose_add_connector called");

    const SCHEMA_HINT: &str = concat!(
        "Expected fields:\n",
        "  record_name : string — PascalCase name of existing record (required)\n",
        "  description : string — human-readable description shown to the user (required)\n",
        "  protocol    : string — e.g. \"mqtt\", \"knx\" (required)\n",
        "  direction   : string — \"inbound\" | \"outbound\" (required)\n",
        "  url         : string — topic / address template; may contain {variant} placeholder (required)"
    );

    #[derive(Debug, Deserialize)]
    struct Params {
        record_name: String,
        description: String,
        protocol: String,
        direction: aimdb_codegen::ConnectorDirection,
        url: String,
    }

    let p: Params = serde_json::from_value(args.unwrap_or(Value::Null)).map_err(|e| {
        McpError::InvalidParams(format!("propose_add_connector: {e}\n\n{SCHEMA_HINT}"))
    })?;

    let proposal_id = submit_proposal(Proposal {
        id: next_proposal_id(),
        change_type: "add_connector".to_string(),
        description: p.description,
        change: ProposedChange::AddConnector {
            record_name: p.record_name,
            connector: aimdb_codegen::ConnectorDef {
                protocol: p.protocol,
                direction: p.direction,
                url: p.url,
            },
        },
        created_at: chrono::Utc::now().to_rfc3339(),
    })?;

    Ok(serde_json::json!({
        "proposal_id": proposal_id,
        "message": "Proposal created. Present it to the user and call resolve_proposal with their decision.",
    }))
}

// ── propose_modify_fields ─────────────────────────────────────────────────────

/// Replace the fields of an existing record's value struct.
pub async fn propose_modify_fields(args: Option<Value>) -> McpResult<Value> {
    debug!("propose_modify_fields called");

    const SCHEMA_HINT: &str = concat!(
        "Expected fields:\n",
        "  record_name : string — PascalCase name of existing record (required)\n",
        "  description : string — human-readable description shown to the user (required)\n",
        "  fields      : array  — replacement field list (required)\n",
        "    Each element: { \"name\": string, \"type\": \"f64|f32|u8|u16|u32|u64|i8|i16|i32|i64|bool|String\", \"description\": string }"
    );

    #[derive(Debug, Deserialize)]
    struct Params {
        record_name: String,
        description: String,
        fields: Vec<aimdb_codegen::FieldDef>,
    }

    let p: Params = serde_json::from_value(args.unwrap_or(Value::Null)).map_err(|e| {
        McpError::InvalidParams(format!("propose_modify_fields: {e}\n\n{SCHEMA_HINT}"))
    })?;

    let proposal_id = submit_proposal(Proposal {
        id: next_proposal_id(),
        change_type: "modify_fields".to_string(),
        description: p.description,
        change: ProposedChange::ModifyFields {
            record_name: p.record_name,
            fields: p.fields,
        },
        created_at: chrono::Utc::now().to_rfc3339(),
    })?;

    Ok(serde_json::json!({
        "proposal_id": proposal_id,
        "message": "Proposal created. Present it to the user and call resolve_proposal with their decision.",
    }))
}

// ── propose_modify_key_variants ───────────────────────────────────────────────

/// Set the key variants (and optionally key_prefix) of an existing record.
///
/// Use this after adding a record with no variants, or when adding new devices
/// to an existing key family.
pub async fn propose_modify_key_variants(args: Option<Value>) -> McpResult<Value> {
    debug!("propose_modify_key_variants called");

    const SCHEMA_HINT: &str = concat!(
        "Expected fields:\n",
        "  record_name  : string   — PascalCase name of existing record (required)\n",
        "  description  : string   — human-readable description shown to the user (required)\n",
        "  key_variants : string[] — concrete PascalCase variant names, e.g. [\"Default\"] or\n",
        "                           [\"ApiServer\", \"Worker\", \"Db\"] (required)\n",
        "  key_prefix   : string   — optional common prefix, e.g. \"sensors.temp.\" (optional)"
    );

    #[derive(Debug, Deserialize)]
    struct Params {
        record_name: String,
        description: String,
        key_variants: Vec<String>,
        key_prefix: Option<String>,
    }

    let p: Params = serde_json::from_value(args.unwrap_or(Value::Null)).map_err(|e| {
        McpError::InvalidParams(format!("propose_modify_key_variants: {e}\n\n{SCHEMA_HINT}"))
    })?;

    let proposal_id = submit_proposal(Proposal {
        id: next_proposal_id(),
        change_type: "modify_key_variants".to_string(),
        description: p.description,
        change: ProposedChange::ModifyKeyVariants {
            record_name: p.record_name,
            key_variants: p.key_variants,
            key_prefix: p.key_prefix,
        },
        created_at: chrono::Utc::now().to_rfc3339(),
    })?;

    Ok(serde_json::json!({
        "proposal_id": proposal_id,
        "message": "Proposal created. Present it to the user and call resolve_proposal with their decision.",
    }))
}

// ── propose_add_task ─────────────────────────────────────────────────────────

/// Add a new task definition. Tasks are async functions that source, transform,
/// or tap data in records.
pub async fn propose_add_task(args: Option<Value>) -> McpResult<Value> {
    debug!("propose_add_task called");

    const SCHEMA_HINT: &str = concat!(
        "Expected fields:\n",
        "  name        : string  — snake_case task function name (required)\n",
        "  description : string  — human-readable description (required)\n",
        "  task_type   : string  — \"source\" | \"transform\" | \"tap\" | \"agent\" (default: \"transform\")\n",
        "  inputs      : [{record, variants?}][] — records this task reads from (optional)\n",
        "  outputs     : [{record, variants?}][] — records this task writes to (optional)"
    );

    #[derive(Debug, Deserialize)]
    struct Params {
        description: String,
        #[serde(flatten)]
        task: aimdb_codegen::TaskDef,
    }

    let p: Params = serde_json::from_value(args.unwrap_or(Value::Null))
        .map_err(|e| McpError::InvalidParams(format!("propose_add_task: {e}\n\n{SCHEMA_HINT}")))?;

    let proposal_id = submit_proposal(Proposal {
        id: next_proposal_id(),
        change_type: "add_task".to_string(),
        description: p.description,
        change: ProposedChange::AddTask { task: p.task },
        created_at: chrono::Utc::now().to_rfc3339(),
    })?;

    Ok(serde_json::json!({
        "proposal_id": proposal_id,
        "message": "Proposal created. Present it to the user and call resolve_proposal with their decision.",
    }))
}

// ── propose_add_binary ──────────────────────────────────────────────────────

/// Add a new binary definition. Binaries are deployable crates that group
/// tasks and optionally declare external broker connections.
pub async fn propose_add_binary(args: Option<Value>) -> McpResult<Value> {
    debug!("propose_add_binary called");

    const SCHEMA_HINT: &str = concat!(
        "Expected fields:\n",
        "  name                : string  — crate directory name (required)\n",
        "  description         : string  — human-readable description (required)\n",
        "  tasks               : string[] — task names belonging to this binary (optional)\n",
        "  external_connectors : [{protocol, env_var, default}][] — broker connections (optional)"
    );

    #[derive(Debug, Deserialize)]
    struct Params {
        description: String,
        #[serde(flatten)]
        binary: aimdb_codegen::BinaryDef,
    }

    let p: Params = serde_json::from_value(args.unwrap_or(Value::Null)).map_err(|e| {
        McpError::InvalidParams(format!("propose_add_binary: {e}\n\n{SCHEMA_HINT}"))
    })?;

    let proposal_id = submit_proposal(Proposal {
        id: next_proposal_id(),
        change_type: "add_binary".to_string(),
        description: p.description,
        change: ProposedChange::AddBinary { binary: p.binary },
        created_at: chrono::Utc::now().to_rfc3339(),
    })?;

    Ok(serde_json::json!({
        "proposal_id": proposal_id,
        "message": "Proposal created. Present it to the user and call resolve_proposal with their decision.",
    }))
}

// ── remove_task ─────────────────────────────────────────────────────────────

/// Propose removal of an existing task (creates a pending proposal).
///
/// Enforces session phase: must be in `Gathering` phase.
pub async fn remove_task(args: Option<Value>) -> McpResult<Value> {
    debug!("remove_task called");

    #[derive(Debug, Deserialize)]
    struct Params {
        task_name: String,
    }

    let params: Params = serde_json::from_value(args.unwrap_or(Value::Null))
        .map_err(|e| McpError::InvalidParams(format!("remove_task: {e}")))?;

    let proposal_id = submit_proposal(Proposal {
        id: next_proposal_id(),
        change_type: "remove_task".to_string(),
        description: format!("Remove task '{}'", params.task_name),
        change: ProposedChange::RemoveTask {
            task_name: params.task_name.clone(),
        },
        created_at: chrono::Utc::now().to_rfc3339(),
    })?;

    Ok(serde_json::json!({
        "proposal_id": proposal_id,
        "task_name": params.task_name,
        "warning": "Removing this task will affect any binaries that reference it and any records listing it as a source/consumer.",
        "message": "Removal proposal created. Present to the user, then call resolve_proposal.",
    }))
}

// ── remove_binary ───────────────────────────────────────────────────────────

/// Propose removal of an existing binary (creates a pending proposal).
///
/// Enforces session phase: must be in `Gathering` phase.
pub async fn remove_binary(args: Option<Value>) -> McpResult<Value> {
    debug!("remove_binary called");

    #[derive(Debug, Deserialize)]
    struct Params {
        binary_name: String,
    }

    let params: Params = serde_json::from_value(args.unwrap_or(Value::Null))
        .map_err(|e| McpError::InvalidParams(format!("remove_binary: {e}")))?;

    let proposal_id = submit_proposal(Proposal {
        id: next_proposal_id(),
        change_type: "remove_binary".to_string(),
        description: format!("Remove binary '{}'", params.binary_name),
        change: ProposedChange::RemoveBinary {
            binary_name: params.binary_name.clone(),
        },
        created_at: chrono::Utc::now().to_rfc3339(),
    })?;

    Ok(serde_json::json!({
        "proposal_id": proposal_id,
        "binary_name": params.binary_name,
        "warning": "Removing this binary will delete the generated crate scaffold. The task definitions themselves are preserved.",
        "message": "Removal proposal created. Present to the user, then call resolve_proposal.",
    }))
}

// ── resolve_proposal ──────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
struct ResolveProposalParams {
    proposal_id: String,
    resolution: ProposalResolution,
    /// Optional redirect message when resolution is `revise`
    #[serde(default)]
    redirect: Option<String>,
    #[serde(default)]
    state_path: Option<String>,
    #[serde(default)]
    mermaid_path: Option<String>,
    #[serde(default)]
    rust_path: Option<String>,
}

/// Accept, reject, or redirect (revise) a pending proposal.
///
/// Enforces session phase: must be in `Proposing` phase with a matching
/// proposal ID. On resolve, transitions back to `Gathering`.
pub async fn resolve_proposal(args: Option<Value>) -> McpResult<Value> {
    debug!("resolve_proposal called");
    let params: ResolveProposalParams = serde_json::from_value(args.unwrap_or(Value::Null))
        .map_err(|e| McpError::InvalidParams(format!("resolve_proposal: {e}")))?;

    let store = session_store()
        .ok_or_else(|| McpError::Internal("Session store not initialised".to_string()))?;

    // Extract the proposal from the session (validates phase + ID)
    let proposal = {
        let mut locked = store
            .lock()
            .map_err(|e| McpError::Internal(format!("session store poisoned: {e}")))?;
        locked
            .on_resolve(&params.proposal_id)
            .map_err(|e| McpError::InvalidParams(format!("Cannot resolve proposal: {e}")))?
    };

    match params.resolution {
        ProposalResolution::Reject => Ok(serde_json::json!({
            "resolution": "rejected",
            "proposal_id": proposal.id,
            "message": "Proposal rejected. No changes were made to state.toml.",
        })),

        ProposalResolution::Revise => Ok(serde_json::json!({
            "resolution": "revise",
            "proposal_id": proposal.id,
            "redirect": params.redirect,
            "message": "Proposal marked for revision. Please revise and call the appropriate propose_* tool again.",
        })),

        ProposalResolution::Confirm => {
            let state_path = params
                .state_path
                .map(std::path::PathBuf::from)
                .unwrap_or_else(default_state_path);
            let mermaid_path = params
                .mermaid_path
                .map(std::path::PathBuf::from)
                .unwrap_or_else(default_mermaid_path);
            let rust_path = params
                .rust_path
                .map(std::path::PathBuf::from)
                .unwrap_or_else(default_rust_path);

            // Read current state (or initialise)
            let mut state = ensure_state_initialised(&state_path)
                .map_err(|e| McpError::Internal(format!("reading state.toml: {e}")))?;

            // Apply the change
            apply_change(&mut state, &proposal.change)
                .map_err(|e| McpError::Internal(format!("applying change: {e}")))?;

            // Validate result before writing
            let errors = aimdb_codegen::validate(&state);
            let blocking_errors: Vec<_> = errors
                .iter()
                .filter(|e| e.severity == aimdb_codegen::Severity::Error)
                .collect();
            if !blocking_errors.is_empty() {
                let msgs: Vec<String> = blocking_errors.iter().map(|e| e.to_string()).collect();
                return Err(McpError::InvalidParams(format!(
                    "Applying this change produces validation errors — cannot confirm:\n{}",
                    msgs.join("\n")
                )));
            }

            // Write state.toml with file lock
            write_state_locked(&state_path, &state)
                .map_err(|e| McpError::Internal(format!("writing state.toml: {e}")))?;

            // Generate artefacts
            let generated = write_artefacts(&state, &mermaid_path, &rust_path)
                .map_err(|e| McpError::Internal(format!("generating artefacts: {e}")))?;

            Ok(serde_json::json!({
                "resolution": "confirmed",
                "proposal_id": proposal.id,
                "change_type": proposal.change_type,
                "state_toml": state_path.display().to_string(),
                "generated": generated,
                "record_count": state.records.len(),
                "message": "Proposal confirmed. state.toml updated, Mermaid and Rust generated.",
            }))
        }
    }
}

// ── save_memory ───────────────────────────────────────────────────────────────

/// Persist ideation context to `.aimdb/memory.md`.
///
/// Call this after every confirmed proposal to record the conversational
/// rationale that led to each decision — the *why* that state.toml cannot
/// express.
pub async fn save_memory(args: Option<Value>) -> McpResult<Value> {
    debug!("save_memory called");

    const SCHEMA_HINT: &str = concat!(
        "Expected fields:\n",
        "  entry       : string — markdown text to append (required)\n",
        "  mode        : \"append\" (default) | \"overwrite\" — append adds a dated\n",
        "                section; overwrite replaces the entire file\n",
        "  memory_path : string — override path (default: .aimdb/memory.md)"
    );

    #[derive(Debug, Default, Deserialize)]
    #[serde(rename_all = "snake_case")]
    enum MemoryMode {
        #[default]
        Append,
        Overwrite,
    }

    #[derive(Debug, Deserialize)]
    struct Params {
        entry: String,
        #[serde(default)]
        mode: MemoryMode,
        #[serde(default)]
        memory_path: Option<String>,
    }

    let p: Params = serde_json::from_value(args.unwrap_or(Value::Null))
        .map_err(|e| McpError::InvalidParams(format!("save_memory: {e}\n\n{SCHEMA_HINT}")))?;

    let path = p
        .memory_path
        .map(std::path::PathBuf::from)
        .unwrap_or_else(default_memory_path);

    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| McpError::Internal(format!("creating .aimdb dir: {e}")))?;
    }

    let content = match p.mode {
        MemoryMode::Overwrite => p.entry.clone(),
        MemoryMode::Append => {
            let timestamp = chrono::Utc::now().format("%Y-%m-%d %H:%M UTC");
            let section = format!("\n---\n<!-- {} -->\n{}\n", timestamp, p.entry.trim());
            if path.exists() {
                let existing = std::fs::read_to_string(&path)
                    .map_err(|e| McpError::Internal(format!("reading memory.md: {e}")))?;
                format!("{}{}", existing.trim_end(), section)
            } else {
                // First write: add a header
                "# AimDB Architecture Memory\n\
                 > Generated by the architecture agent. Do not edit — use the agent to update.\n\
                 > Records the ideation context and design rationale behind each decision.\n"
                    .to_string()
                    + &section
            }
        }
    };

    std::fs::write(&path, &content)
        .map_err(|e| McpError::Internal(format!("writing memory.md: {e}")))?;

    Ok(serde_json::json!({
        "written": path.display().to_string(),
        "mode": match p.mode { MemoryMode::Append => "append", MemoryMode::Overwrite => "overwrite" },
        "bytes": content.len(),
        "message": "Memory updated. The agent will read this on next session start.",
    }))
}

#[derive(Debug, Deserialize)]
struct RemoveRecordParams {
    record_name: String,
    #[serde(default)]
    #[allow(dead_code)]
    state_path: Option<String>,
}

/// Propose removal of an existing record (creates a pending proposal).
///
/// Enforces session phase: must be in `Gathering` phase.
pub async fn remove_record(args: Option<Value>) -> McpResult<Value> {
    debug!("remove_record called");
    let params: RemoveRecordParams = serde_json::from_value(args.unwrap_or(Value::Null))
        .map_err(|e| McpError::InvalidParams(format!("remove_record: {e}")))?;

    let store = session_store()
        .ok_or_else(|| McpError::Internal("Session store not initialised".to_string()))?;

    let proposal = Proposal {
        id: next_proposal_id(),
        change_type: "remove_record".to_string(),
        description: format!("Remove record '{}'", params.record_name),
        change: ProposedChange::RemoveRecord {
            record_name: params.record_name.clone(),
        },
        created_at: chrono::Utc::now().to_rfc3339(),
    };

    let id = {
        let mut locked = store
            .lock()
            .map_err(|e| McpError::Internal(format!("session store poisoned: {e}")))?;
        let p = locked
            .on_propose(proposal)
            .map_err(|e| McpError::InvalidParams(format!("Cannot propose removal: {e}")))?;
        p.id.clone()
    };

    Ok(serde_json::json!({
        "proposal_id": id,
        "record_name": params.record_name,
        "warning": format!(
            "Removing '{}' will delete its generated key enum and value struct from \
             src/generated_schema.rs. Application code referencing these types will fail to compile.",
            params.record_name
        ),
        "message": "Removal proposal created. Present to the user, then call resolve_proposal.",
    }))
}

// ── rename_record ─────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
struct RenameRecordParams {
    old_name: String,
    new_name: String,
    #[serde(default)]
    #[allow(dead_code)]
    state_path: Option<String>,
}

/// Propose renaming an existing record (creates a pending proposal).
///
/// Enforces session phase: must be in `Gathering` phase.
pub async fn rename_record(args: Option<Value>) -> McpResult<Value> {
    debug!("rename_record called");
    let params: RenameRecordParams = serde_json::from_value(args.unwrap_or(Value::Null))
        .map_err(|e| McpError::InvalidParams(format!("rename_record: {e}")))?;

    let store = session_store()
        .ok_or_else(|| McpError::Internal("Session store not initialised".to_string()))?;

    let proposal = Proposal {
        id: next_proposal_id(),
        change_type: "rename_record".to_string(),
        description: format!("Rename '{}' → '{}'", params.old_name, params.new_name),
        change: ProposedChange::RenameRecord {
            old_name: params.old_name.clone(),
            new_name: params.new_name.clone(),
        },
        created_at: chrono::Utc::now().to_rfc3339(),
    };

    let id = {
        let mut locked = store
            .lock()
            .map_err(|e| McpError::Internal(format!("session store poisoned: {e}")))?;
        let p = locked
            .on_propose(proposal)
            .map_err(|e| McpError::InvalidParams(format!("Cannot propose rename: {e}")))?;
        p.id.clone()
    };

    Ok(serde_json::json!({
        "proposal_id": id,
        "old_name": params.old_name,
        "new_name": params.new_name,
        "warning": format!(
            "Renaming '{}' to '{}' will update the generated key enum and value struct names. \
             Application code using the old name ('{}Key', '{}Value') will fail to compile.",
            params.old_name, params.new_name, params.old_name, params.old_name
        ),
        "message": "Rename proposal created. Present to the user, then call resolve_proposal.",
    }))
}

// ── validate_against_instance ─────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
struct ValidateInstanceParams {
    /// Unix socket path to the AimDB instance (falls back to AIMDB_SOCKET env)
    socket_path: Option<String>,
    #[serde(default)]
    state_path: Option<String>,
}

/// Compare state.toml against a live AimDB instance and return conflicts.
///
/// Session-agnostic: works in any phase.
pub async fn validate_against_instance(args: Option<Value>) -> McpResult<Value> {
    debug!("validate_against_instance called");
    let params: ValidateInstanceParams = serde_json::from_value(args.unwrap_or(Value::Null))
        .map_err(|e| McpError::InvalidParams(format!("validate_against_instance: {e}")))?;
    let socket_path = super::resolve_socket_path(params.socket_path)?;

    let state_path = params
        .state_path
        .map(std::path::PathBuf::from)
        .unwrap_or_else(default_state_path);

    let state = architecture::read_state(&state_path)
        .map_err(|e| McpError::Internal(e.to_string()))?
        .ok_or_else(|| {
            McpError::InvalidParams(format!(
                "No state.toml at {}. Nothing to validate against.",
                state_path.display()
            ))
        })?;

    // Connect and list live records
    let mut client = AimxClient::connect(&socket_path)
        .await
        .map_err(McpError::Client)?;

    let raw = client.list_records().await.map_err(McpError::Client)?;

    // Parse the live records into our lightweight struct
    let live_records: Vec<LiveRecord> = raw
        .into_iter()
        .map(|r| LiveRecord {
            name: r.name,
            buffer_type: r.buffer_type,
            buffer_capacity: r.buffer_capacity,
        })
        .collect();

    let report = detect_conflicts(&state, &live_records);

    Ok(serde_json::to_value(&report)?)
}

// ── reset_session ─────────────────────────────────────────────────────────────

/// Reset the architecture session, discarding any pending proposals.
///
/// Use this when the user wants to start over or abandon the current
/// ideation cycle.
pub async fn reset_session(_args: Option<Value>) -> McpResult<Value> {
    debug!("reset_session called");

    let store = session_store()
        .ok_or_else(|| McpError::Internal("Session store not initialised".to_string()))?;

    let mut locked = store
        .lock()
        .map_err(|e| McpError::Internal(format!("session store poisoned: {e}")))?;
    locked.reset();

    Ok(serde_json::json!({
        "message": "Session reset. Call get_architecture to begin a new ideation cycle.",
    }))
}

// ── Helpers ───────────────────────────────────────────────────────────────────

fn parse_optional<T: serde::de::DeserializeOwned + Default>(args: Option<Value>) -> McpResult<T> {
    match args {
        None | Some(Value::Null) => Ok(T::default()),
        Some(v) => serde_json::from_value(v).map_err(|e| McpError::InvalidParams(e.to_string())),
    }
}