agent-trace 0.1.0

Git-backed document memory, trace continuity, and permissioned writes for agent workflows
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
use crate::agent_trace_md;
use crate::config::MergedConfig;
use crate::data_plane::{self, WriteDocumentError};
use crate::git_store::CommitInfo;
use crate::manifest::Manifest;
use crate::observability::format_permission_denied;
use crate::permissions::{check_permission, Overrides, PermissionResult};
use crate::running_summary;
use crate::runtime::ActivityMonitor;
use crate::session::{self, AgentState};
use crate::store::Store;
use crate::types::{Action, Actor, DocType};
use anyhow::Result;
use serde_json::{json, Value};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

pub fn run(root: &Path, actor_name: Option<String>) -> Result<()> {
    let config = MergedConfig::load(root)?;
    let manifest = Arc::new(Mutex::new(Manifest::load(root)?));
    let agent_state = AgentState::new(actor_name.clone());
    let _monitor = ActivityMonitor::try_start(
        root,
        config,
        manifest,
        AgentState::new(actor_name.clone()),
        None,
    )?;

    let actor = agent_state.current_actor(root);
    let mut session_id = session::session_id_for_actor(root, &actor);
    if let Some(name) = actor.agent_name() {
        if session_id.is_none() {
            // MCP with explicit actor should create a durable session lineage.
            if let Ok(s) = session::start_session(root, name, "mcp") {
                session_id = Some(s.session_id);
            }
        } else {
            let _ = session::touch_session(root, name);
        }
    }

    if let Err(e) = running_summary::refresh_if_stale(root) {
        tracing::warn!("running summary refresh on MCP start failed: {e}");
    }

    let stdin = std::io::stdin();
    let stdout = std::io::stdout();
    let mut reader = BufReader::new(stdin.lock());
    let mut out = stdout.lock();

    let mut line = String::new();
    loop {
        line.clear();
        let n = reader.read_line(&mut line)?;
        if n == 0 {
            break; // EOF — client closed the connection
        }
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        let msg: Value = match serde_json::from_str(trimmed) {
            Ok(v) => v,
            Err(e) => {
                let err = json!({
                    "jsonrpc": "2.0",
                    "id": null,
                    "error": {"code": -32700, "message": format!("Parse error: {}", e)}
                });
                writeln!(out, "{err}")?;
                out.flush()?;
                continue;
            }
        };

        // Notifications have no "id" field — process silently, no response sent
        let id = match msg.get("id") {
            Some(id) => id.clone(),
            None => continue,
        };

        let method = msg.get("method").and_then(|v| v.as_str()).unwrap_or("");
        if let Some(name) = actor.agent_name() {
            let _ = session::touch_session(root, name);
        }
        let mut response = dispatch(&msg, method, root, &actor, session_id.as_deref());
        response["id"] = id;

        writeln!(out, "{response}")?;
        out.flush()?;
    }
    Ok(())
}

fn dispatch(
    msg: &Value,
    method: &str,
    root: &Path,
    actor: &Actor,
    session_id: Option<&str>,
) -> Value {
    match method {
        "initialize" => handle_initialize(),
        "tools/list" => handle_tools_list(),
        "tools/call" => {
            let params = msg.get("params").cloned().unwrap_or(json!({}));
            let name = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
            let args = params.get("arguments").cloned().unwrap_or(json!({}));
            match name {
                "read_file" => handle_read_file(root, &args),
                "write_file" => handle_write_file(root, &args, actor, session_id),
                "list_documents" => handle_list_documents(root, &args),
                "get_permissions" => handle_get_permissions(root, actor),
                "add_document" => handle_add_document(root, &args),
                "get_resume_context" => handle_get_resume_context(root, actor, &args),
                _ => error_response(-32601, &format!("Unknown tool: {name}")),
            }
        }
        _ => error_response(-32601, &format!("Method not found: {method}")),
    }
}

fn handle_initialize() -> Value {
    json!({
        "jsonrpc": "2.0",
        "result": {
            "protocolVersion": "2024-11-05",
            "capabilities": {"tools": {}},
            "serverInfo": {
                "name": "agent-trace",
                "version": env!("CARGO_PKG_VERSION")
            },
            "instructions": "Call get_resume_context before other tools to load session state."
        }
    })
}

fn handle_tools_list() -> Value {
    json!({
        "jsonrpc": "2.0",
        "result": {
            "tools": [
                {
                    "name": "read_file",
                    "description": "Read a tracked document from the agent-trace store",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "path": {"type": "string", "description": "Relative path to the file"}
                        },
                        "required": ["path"]
                    }
                },
                {
                    "name": "write_file",
                    "description": "Write content to a document. Enforces permissions synchronously — returns an error if the current actor cannot write this document type.",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "path": {"type": "string", "description": "Relative path to the file"},
                            "content": {"type": "string", "description": "New file content"}
                        },
                        "required": ["path", "content"]
                    }
                },
                {
                    "name": "list_documents",
                    "description": "List tracked documents, optionally filtered by type",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "type": {
                                "type": "string",
                                "description": "Filter by doc type: plan, context, log, reference, scratch"
                            }
                        }
                    }
                },
                {
                    "name": "get_permissions",
                    "description": "Show what the current actor can read and write",
                    "inputSchema": {
                        "type": "object",
                        "properties": {}
                    }
                },
                {
                    "name": "add_document",
                    "description": "Register an existing file as a tracked document with a given type",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "path": {"type": "string", "description": "Relative path to the file"},
                            "doc_type": {
                                "type": "string",
                                "description": "Document type: plan, context, log, reference, or scratch"
                            }
                        },
                        "required": ["path", "doc_type"]
                    }
                },
                {
                    "name": "get_resume_context",
                    "description": "Get the four-section resume briefing (objective, current state, recent events, earlier work). Call FIRST after initialize.",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "include_git_log": {"type": "boolean", "default": false},
                            "git_log_limit": {"type": "integer", "default": 10},
                            "include_prior_recap": {"type": "boolean", "default": true},
                            "include_session_log": {"type": "boolean", "default": false}
                        }
                    }
                }
            ]
        }
    })
}

fn handle_get_resume_context(root: &Path, actor: &Actor, args: &Value) -> Value {
    let include_git_log = args
        .get("include_git_log")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let git_log_limit = args
        .get("git_log_limit")
        .and_then(|v| v.as_u64())
        .unwrap_or(10) as usize;
    let include_prior_recap = args
        .get("include_prior_recap")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    let include_session_log = args
        .get("include_session_log")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    if let Err(e) = crate::session_recap::ensure_prior_session_recap(root) {
        tracing::warn!("prior session recap failed: {e}");
    }

    if let Err(e) = running_summary::refresh_if_stale(root) {
        tracing::warn!("running summary refresh before resume context failed: {e}");
    }

    let opts = crate::briefing::BriefingOptions {
        include_git_log,
        include_prior_recap,
        include_session_log,
        git_log_limit,
        ..Default::default()
    };

    match crate::briefing::assemble_resume_briefing(root, actor, &opts) {
        Ok(text) => tool_result(&text),
        Err(e) => error_response(-32603, &format!("Cannot assemble resume context: {e}")),
    }
}

fn handle_read_file(root: &Path, args: &Value) -> Value {
    let path_str = match args.get("path").and_then(|v| v.as_str()) {
        Some(p) => p,
        None => return error_response(-32602, "Missing required argument: path"),
    };
    let rel = PathBuf::from(path_str);
    let full = root.join(&rel);

    let content = match std::fs::read_to_string(&full) {
        Ok(c) => c,
        Err(e) => return error_response(-32603, &format!("Cannot read {path_str}: {e}")),
    };

    let doc_type = Store::open(root)
        .ok()
        .and_then(|s| s.manifest.find_by_path(&rel).map(|e| e.doc_type.clone()))
        .map(|dt| dt.to_string())
        .unwrap_or_else(|| "untracked".to_string());

    tool_result(&format!(
        "path: {path_str}\ndoc_type: {doc_type}\n\n{content}"
    ))
}

fn handle_write_file(root: &Path, args: &Value, actor: &Actor, session_id: Option<&str>) -> Value {
    let path_str = match args.get("path").and_then(|v| v.as_str()) {
        Some(p) => p,
        None => return error_response(-32602, "Missing required argument: path"),
    };
    let content = match args.get("content").and_then(|v| v.as_str()) {
        Some(c) => c,
        None => return error_response(-32602, "Missing required argument: content"),
    };

    let rel = PathBuf::from(path_str);
    match data_plane::write_document(root, &rel, content, actor, "mcp write", session_id) {
        Ok(_) => tool_result(&format!("OK: {path_str} written")),
        Err(WriteDocumentError::PermissionDenied { path, reason }) => {
            tool_error(&format_permission_denied(&path, &reason))
        }
        Err(WriteDocumentError::Other(e)) => error_response(-32603, &format!("Write failed: {e}")),
    }
}

fn handle_list_documents(root: &Path, args: &Value) -> Value {
    let type_filter: Option<DocType> = args
        .get("type")
        .and_then(|v| v.as_str())
        .and_then(|s| s.parse().ok());

    let store = match Store::open(root) {
        Ok(s) => s,
        Err(e) => return error_response(-32603, &format!("Cannot open store: {e}")),
    };

    let docs: Vec<Value> = store
        .manifest
        .list(type_filter.as_ref())
        .iter()
        .map(|d| {
            json!({
                "path": d.path.display().to_string(),
                "doc_type": d.doc_type.to_string(),
                "id": d.id.to_string(),
            })
        })
        .collect();

    let text = serde_json::to_string_pretty(&docs).unwrap_or_default();
    tool_result(&text)
}

fn handle_get_permissions(root: &Path, actor: &Actor) -> Value {
    let overrides = Overrides::load(root).unwrap_or_default();

    let doc_types = [
        DocType::Plan,
        DocType::Context,
        DocType::Log,
        DocType::Reference,
        DocType::Scratch,
    ];

    let perms: Vec<Value> = doc_types
        .iter()
        .map(|dt| {
            let status = match check_permission(dt, actor, &overrides, None) {
                PermissionResult::Allowed => "allowed",
                PermissionResult::Denied { .. } => "denied",
                PermissionResult::RequiresConfirmation { .. } => "requires_confirmation",
            };
            json!({"doc_type": dt.to_string(), "write": status})
        })
        .collect();

    let text = format!(
        "Actor: {}\nPermissions:\n{}",
        actor,
        serde_json::to_string_pretty(&perms).unwrap_or_default()
    );
    tool_result(&text)
}

fn handle_add_document(root: &Path, args: &Value) -> Value {
    let path_str = match args.get("path").and_then(|v| v.as_str()) {
        Some(p) => p,
        None => return error_response(-32602, "Missing required argument: path"),
    };
    let doc_type_str = match args.get("doc_type").and_then(|v| v.as_str()) {
        Some(t) => t,
        None => return error_response(-32602, "Missing required argument: doc_type"),
    };
    let doc_type: DocType = match doc_type_str.parse() {
        Ok(dt) => dt,
        Err(e) => return error_response(-32602, &format!("Invalid doc_type: {e}")),
    };

    let rel = PathBuf::from(path_str);
    let mut store = match Store::open(root) {
        Ok(s) => s,
        Err(e) => return error_response(-32603, &format!("Cannot open store: {e}")),
    };

    if !root.join(&rel).exists() {
        return tool_error(&format!("File does not exist: {path_str}"));
    }
    if store.manifest.is_tracked(&rel) {
        return tool_error(&format!("Already tracked: {path_str}"));
    }

    if let Err(e) = store.manifest.register(&rel, doc_type.clone(), "") {
        return error_response(-32603, &format!("Cannot register: {e}"));
    }
    if let Err(e) = store.manifest.save(root) {
        return error_response(-32603, &format!("Cannot save manifest: {e}"));
    }

    let at_content = agent_trace_md::generate(root, &store.manifest);
    let _ = std::fs::write(root.join("AGENT-TRACE.md"), &at_content);

    let info = CommitInfo {
        action: Action::Create,
        files: vec![
            (rel.clone(), Action::Create, doc_type.clone()),
            (
                PathBuf::from("AGENT-TRACE.md"),
                Action::Modify,
                DocType::Reference,
            ),
        ],
        actor: Actor::System,
        summary: format!("mcp add: {path_str} as {doc_type}"),
        agent_name: None,
        session_id: None,
    };
    if let Err(e) = store.commit(&info) {
        return error_response(-32603, &format!("Cannot commit: {e}"));
    }

    tool_result(&format!("Added {path_str} as {doc_type}"))
}

// ── Response helpers ──────────────────────────────────────────────────────────

fn tool_result(text: &str) -> Value {
    json!({
        "jsonrpc": "2.0",
        "result": {
            "content": [{"type": "text", "text": text}],
            "isError": false
        }
    })
}

fn tool_error(text: &str) -> Value {
    json!({
        "jsonrpc": "2.0",
        "result": {
            "content": [{"type": "text", "text": text}],
            "isError": true
        }
    })
}

fn error_response(code: i32, message: &str) -> Value {
    json!({
        "jsonrpc": "2.0",
        "error": {"code": code, "message": message}
    })
}

// ── Unit tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{GlobalConfig, MergedConfig, PollingConfig, StoreConfig, StoreInfo};
    use crate::git_store::GitStore;
    use crate::manifest::Manifest;
    use tempfile::TempDir;

    fn setup_store(tmp: &TempDir) -> PathBuf {
        let root = tmp.path().to_path_buf();
        std::fs::create_dir_all(root.join(".agent-trace/locks")).unwrap();
        let git = GitStore::init(&root).unwrap();
        let info = StoreInfo::new("test".into());
        let manifest = Manifest::create_empty(info.clone(), &root).unwrap();
        let global = GlobalConfig::default();
        let store_cfg = StoreConfig {
            store: info,
            llm: None,
            synthesis: None,
            polling: PollingConfig::default(),
        };
        store_cfg.save(&root).unwrap();
        let config = MergedConfig::merge(global, store_cfg);
        // Silence unused warning — we init git which sets up the repo
        drop((git, manifest, config));
        root
    }

    fn agent(name: &str) -> Actor {
        Actor::Agent { name: name.into() }
    }

    #[test]
    fn test_initialize_response() {
        let resp = handle_initialize();
        assert_eq!(resp["result"]["protocolVersion"], "2024-11-05");
        assert_eq!(resp["result"]["serverInfo"]["name"], "agent-trace");
        assert!(resp["result"]["instructions"]
            .as_str()
            .unwrap()
            .contains("get_resume_context"));
        assert!(resp.get("error").is_none());
    }

    #[test]
    fn test_tools_list_contains_all_tools() {
        let resp = handle_tools_list();
        let tools = resp["result"]["tools"].as_array().unwrap();
        let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
        assert!(names.contains(&"read_file"));
        assert!(names.contains(&"write_file"));
        assert!(names.contains(&"list_documents"));
        assert!(names.contains(&"get_permissions"));
        assert!(names.contains(&"add_document"));
        assert!(names.contains(&"get_resume_context"));
        assert_eq!(names.len(), 6);
    }

    #[test]
    fn test_write_file_allowed_plan() {
        let tmp = TempDir::new().unwrap();
        let root = setup_store(&tmp);
        std::fs::write(root.join("plan.md"), "# Plan").unwrap();
        Store::open(&root).unwrap(); // ensure store opens
                                     // Add plan.md via add command path so it's tracked
        let mut store = Store::open(&root).unwrap();
        store
            .manifest
            .register(&PathBuf::from("plan.md"), DocType::Plan, "")
            .unwrap();
        store.manifest.save(&root).unwrap();
        let info = CommitInfo {
            action: Action::Create,
            files: vec![(PathBuf::from("plan.md"), Action::Create, DocType::Plan)],
            actor: Actor::System,
            summary: "setup".into(),
            agent_name: None,
            session_id: None,
        };
        store.commit(&info).unwrap();

        let args = json!({"path": "plan.md", "content": "# Updated Plan"});
        let resp = handle_write_file(&root, &args, &agent("test-agent"), None);
        assert_eq!(resp["result"]["isError"], false);
        assert_eq!(
            std::fs::read_to_string(root.join("plan.md")).unwrap(),
            "# Updated Plan"
        );
    }

    #[test]
    fn test_write_file_denied_context() {
        let tmp = TempDir::new().unwrap();
        let root = setup_store(&tmp);
        std::fs::write(root.join("context.md"), "# Context").unwrap();
        let mut store = Store::open(&root).unwrap();
        store
            .manifest
            .register(&PathBuf::from("context.md"), DocType::Context, "")
            .unwrap();
        store.manifest.save(&root).unwrap();
        let info = CommitInfo {
            action: Action::Create,
            files: vec![(
                PathBuf::from("context.md"),
                Action::Create,
                DocType::Context,
            )],
            actor: Actor::System,
            summary: "setup".into(),
            agent_name: None,
            session_id: None,
        };
        store.commit(&info).unwrap();

        let original = std::fs::read_to_string(root.join("context.md")).unwrap();
        let args = json!({"path": "context.md", "content": "# Hacked"});
        let resp = handle_write_file(&root, &args, &agent("test-agent"), None);

        assert_eq!(resp["result"]["isError"], true);
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        assert!(
            text.contains("Permission denied"),
            "expected denial, got: {text}"
        );
        // File must be unchanged
        assert_eq!(
            std::fs::read_to_string(root.join("context.md")).unwrap(),
            original
        );
    }

    #[test]
    fn test_list_documents_returns_all() {
        let tmp = TempDir::new().unwrap();
        let root = setup_store(&tmp);
        std::fs::write(root.join("plan.md"), "p").unwrap();
        std::fs::write(root.join("ref.md"), "r").unwrap();
        let mut store = Store::open(&root).unwrap();
        store
            .manifest
            .register(&PathBuf::from("plan.md"), DocType::Plan, "")
            .unwrap();
        store
            .manifest
            .register(&PathBuf::from("ref.md"), DocType::Reference, "")
            .unwrap();
        store.manifest.save(&root).unwrap();
        let info = CommitInfo {
            action: Action::Create,
            files: vec![
                (PathBuf::from("plan.md"), Action::Create, DocType::Plan),
                (PathBuf::from("ref.md"), Action::Create, DocType::Reference),
            ],
            actor: Actor::System,
            summary: "setup".into(),
            agent_name: None,
            session_id: None,
        };
        store.commit(&info).unwrap();

        let resp = handle_list_documents(&root, &json!({}));
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        assert!(text.contains("plan.md"));
        assert!(text.contains("ref.md"));
    }

    #[test]
    fn test_list_documents_type_filter() {
        let tmp = TempDir::new().unwrap();
        let root = setup_store(&tmp);
        std::fs::write(root.join("plan.md"), "p").unwrap();
        std::fs::write(root.join("ref.md"), "r").unwrap();
        let mut store = Store::open(&root).unwrap();
        store
            .manifest
            .register(&PathBuf::from("plan.md"), DocType::Plan, "")
            .unwrap();
        store
            .manifest
            .register(&PathBuf::from("ref.md"), DocType::Reference, "")
            .unwrap();
        store.manifest.save(&root).unwrap();
        let info = CommitInfo {
            action: Action::Create,
            files: vec![
                (PathBuf::from("plan.md"), Action::Create, DocType::Plan),
                (PathBuf::from("ref.md"), Action::Create, DocType::Reference),
            ],
            actor: Actor::System,
            summary: "setup".into(),
            agent_name: None,
            session_id: None,
        };
        store.commit(&info).unwrap();

        let resp = handle_list_documents(&root, &json!({"type": "plan"}));
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        assert!(text.contains("plan.md"));
        assert!(
            !text.contains("ref.md"),
            "type filter should exclude ref.md"
        );
    }

    #[test]
    fn test_get_permissions_agent_denied_context() {
        let tmp = TempDir::new().unwrap();
        let root = setup_store(&tmp);
        let resp = handle_get_permissions(&root, &agent("test-agent"));
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        assert!(text.contains("context"), "should mention context type");
        assert!(
            text.contains("denied"),
            "context should be denied for agent"
        );
        assert!(text.contains("allowed"), "plan should be allowed for agent");
    }

    #[test]
    fn test_unknown_method_returns_error() {
        let msg = json!({"jsonrpc":"2.0","id":1,"method":"bogus","params":{}});
        let resp = dispatch(&msg, "bogus", Path::new("/tmp"), &Actor::User, None);
        assert!(resp.get("error").is_some());
        assert_eq!(resp["error"]["code"], -32601);
    }

    #[test]
    fn test_unknown_tool_returns_error() {
        let msg = json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"fly","arguments":{}}});
        let resp = dispatch(&msg, "tools/call", Path::new("/tmp"), &Actor::User, None);
        assert!(resp.get("error").is_some());
        assert_eq!(resp["error"]["code"], -32601);
    }

    #[test]
    fn test_write_file_missing_path_arg() {
        let args = json!({"content": "hello"});
        let resp = handle_write_file(Path::new("/tmp"), &args, &Actor::User, None);
        assert_eq!(resp["error"]["code"], -32602);
    }

    #[test]
    fn test_write_file_missing_content_arg() {
        let args = json!({"path": "plan.md"});
        let resp = handle_write_file(Path::new("/tmp"), &args, &Actor::User, None);
        assert_eq!(resp["error"]["code"], -32602);
    }
}