meld 1.1.5

Deterministic filesystem state management using Merkle trees
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
//! Integration tests for Context CLI commands

use clap::Parser;
use meld::agent::{AgentIdentity, AgentRole, AgentStorage, XdgAgentStorage};
use meld::cli::{Cli, Commands, ContextCommands, RunContext};
use meld::config::{xdg, AgentConfig, ProviderConfig, ProviderType};
use meld::context::frame::{Basis, Frame};
use meld::error::ApiError;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use tempfile::TempDir;

use crate::integration::with_xdg_env;

/// Create a test agent config file
fn create_test_agent(
    agent_id: &str,
    role: AgentRole,
    prompt_path: Option<&str>,
) -> Result<PathBuf, ApiError> {
    let agents_dir = XdgAgentStorage::new().agents_dir()?;
    // Ensure directory exists
    fs::create_dir_all(&agents_dir)
        .map_err(|e| ApiError::ConfigError(format!("Failed to create agents directory: {}", e)))?;
    let config_path = agents_dir.join(format!("{}.toml", agent_id));

    let mut agent_config = AgentConfig {
        agent_id: agent_id.to_string(),
        role,
        system_prompt: None,
        system_prompt_path: prompt_path.map(|s| s.to_string()),
        metadata: Default::default(),
    };

    if role != AgentRole::Reader {
        agent_config.metadata.insert(
            "user_prompt_file".to_string(),
            "Analyze the file at {path}".to_string(),
        );
        agent_config.metadata.insert(
            "user_prompt_directory".to_string(),
            "Analyze the directory at {path}".to_string(),
        );
    }

    let toml = toml::to_string(&agent_config)
        .map_err(|e| ApiError::ConfigError(format!("Failed to serialize agent config: {}", e)))?;

    fs::write(&config_path, toml)
        .map_err(|e| ApiError::ConfigError(format!("Failed to write agent config: {}", e)))?;

    Ok(config_path)
}

/// Create a test provider config file
fn create_test_provider(
    provider_name: &str,
    provider_type: ProviderType,
) -> Result<PathBuf, ApiError> {
    let providers_dir = xdg::providers_dir()?;
    // Ensure directory exists
    fs::create_dir_all(&providers_dir).map_err(|e| {
        ApiError::ConfigError(format!("Failed to create providers directory: {}", e))
    })?;
    let config_path = providers_dir.join(format!("{}.toml", provider_name));

    let provider_config = ProviderConfig {
        provider_name: Some(provider_name.to_string()),
        provider_type,
        model: "test-model".to_string(),
        api_key: None,
        endpoint: None,
        default_options: meld::provider::CompletionOptions::default(),
    };

    let toml = toml::to_string(&provider_config).map_err(|e| {
        ApiError::ConfigError(format!("Failed to serialize provider config: {}", e))
    })?;

    fs::write(&config_path, toml)
        .map_err(|e| ApiError::ConfigError(format!("Failed to write provider config: {}", e)))?;

    Ok(config_path)
}

#[test]
fn test_context_get_with_path() {
    let temp_dir = TempDir::new().unwrap();
    with_xdg_env(&temp_dir, || {
        // Create workspace
        let workspace_root = temp_dir.path().join("workspace");
        fs::create_dir_all(&workspace_root).unwrap();

        // Create a test file
        let test_file = workspace_root.join("test.txt");
        fs::write(&test_file, "test content").unwrap();

        // Initialize CLI context
        let run_context = RunContext::new(workspace_root.clone(), None).unwrap();

        // Scan the workspace
        run_context
            .execute(&Commands::Scan { force: true })
            .unwrap();

        // Get context for the file
        let result = run_context.execute(&Commands::Context {
            command: ContextCommands::Get {
                node: None,
                path: Some(test_file),
                agent: None,
                frame_type: None,
                max_frames: 10,
                ordering: "recency".to_string(),
                combine: false,
                separator: "\n\n---\n\n".to_string(),
                format: "text".to_string(),
                include_metadata: false,
                include_deleted: false,
            },
        });

        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("Node:"));
        assert!(output.contains("test.txt"));
    });
}

#[test]
fn test_context_get_with_node_id() {
    let temp_dir = TempDir::new().unwrap();
    with_xdg_env(&temp_dir, || {
        // Create workspace
        let workspace_root = temp_dir.path().join("workspace");
        fs::create_dir_all(&workspace_root).unwrap();

        // Create a test file
        let test_file = workspace_root.join("test.txt");
        fs::write(&test_file, "test content").unwrap();

        // Initialize CLI context
        let run_context = RunContext::new(workspace_root.clone(), None).unwrap();

        // Scan the workspace
        run_context
            .execute(&Commands::Scan { force: true })
            .unwrap();

        // Get root node ID from status (use JSON format to get full hash)
        let status_output = run_context
            .execute(&Commands::Status {
                format: "json".to_string(),
                workspace_only: true,
                agents_only: false,
                providers_only: false,
                breakdown: false,
                test_connectivity: false,
            })
            .unwrap();
        let status_json: serde_json::Value = serde_json::from_str(&status_output).unwrap();
        let root_hash = status_json["workspace"]["tree"]["root_hash"]
            .as_str()
            .unwrap();

        // Get context for the root node
        let result = run_context.execute(&Commands::Context {
            command: ContextCommands::Get {
                node: Some(root_hash.to_string()),
                path: None,
                agent: None,
                frame_type: None,
                max_frames: 10,
                ordering: "recency".to_string(),
                combine: false,
                separator: "\n\n---\n\n".to_string(),
                format: "text".to_string(),
                include_metadata: false,
                include_deleted: false,
            },
        });

        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("Node:"));
    });
}

#[test]
fn test_context_get_invalid_path() {
    let temp_dir = TempDir::new().unwrap();
    with_xdg_env(&temp_dir, || {
        let workspace_root = temp_dir.path().join("workspace");
        fs::create_dir_all(&workspace_root).unwrap();

        let run_context = RunContext::new(workspace_root.clone(), None).unwrap();

        // Create the file but don't scan it (so it's not in the tree)
        let test_path = workspace_root.join("nonexistent.txt");
        fs::write(&test_path, "test content").unwrap();

        // Try to get context for a path not in the tree
        let result = run_context.execute(&Commands::Context {
            command: ContextCommands::Get {
                node: None,
                path: Some(test_path),
                agent: None,
                frame_type: None,
                max_frames: 10,
                ordering: "recency".to_string(),
                combine: false,
                separator: "\n\n---\n\n".to_string(),
                format: "text".to_string(),
                include_metadata: false,
                include_deleted: false,
            },
        });

        assert!(result.is_err());
        match result {
            Err(ApiError::PathNotInTree(_)) => {}
            _ => panic!("Expected PathNotInTree error, got: {:?}", result),
        }
    });
}

#[test]
fn test_context_get_json_format() {
    let temp_dir = TempDir::new().unwrap();
    with_xdg_env(&temp_dir, || {
        let workspace_root = temp_dir.path().join("workspace");
        fs::create_dir_all(&workspace_root).unwrap();

        let test_file = workspace_root.join("test.txt");
        fs::write(&test_file, "test content").unwrap();

        let run_context = RunContext::new(workspace_root.clone(), None).unwrap();
        run_context
            .execute(&Commands::Scan { force: true })
            .unwrap();

        let result = run_context.execute(&Commands::Context {
            command: ContextCommands::Get {
                node: None,
                path: Some(test_file),
                agent: None,
                frame_type: None,
                max_frames: 10,
                ordering: "recency".to_string(),
                combine: false,
                separator: "\n\n---\n\n".to_string(),
                format: "json".to_string(),
                include_metadata: false,
                include_deleted: false,
            },
        });

        assert!(result.is_ok());
        let output = result.unwrap();
        // Verify it's valid JSON
        let _json: serde_json::Value = serde_json::from_str(&output).unwrap();
        assert!(output.contains("node_id"));
        assert!(output.contains("frames"));
    });
}

#[test]
fn test_context_get_json_metadata_projection_filters_internal_keys() {
    let temp_dir = TempDir::new().unwrap();
    with_xdg_env(&temp_dir, || {
        let workspace_root = temp_dir.path().join("workspace");
        fs::create_dir_all(&workspace_root).unwrap();

        let test_file = workspace_root.join("test.txt");
        fs::write(&test_file, "test content").unwrap();

        let run_context = RunContext::new(workspace_root.clone(), None).unwrap();
        run_context
            .execute(&Commands::Scan { force: true })
            .unwrap();

        {
            let mut registry = run_context.api().agent_registry().write();
            registry.register(AgentIdentity::new(
                "writer-metadata".to_string(),
                AgentRole::Writer,
            ));
        }

        let node_id = run_context
            .api()
            .node_store()
            .find_by_path(&test_file)
            .unwrap()
            .unwrap()
            .node_id;

        let mut metadata = HashMap::new();
        metadata.insert("provider".to_string(), "test-provider".to_string());
        metadata.insert("model".to_string(), "test-model".to_string());
        metadata.insert("provider_type".to_string(), "ollama".to_string());
        metadata.insert(
            "prompt_digest".to_string(),
            "digest-summarize-file".to_string(),
        );
        metadata.insert(
            "context_digest".to_string(),
            "digest-context-file".to_string(),
        );
        metadata.insert("prompt_link_id".to_string(), "prompt-link-1".to_string());
        metadata.insert("deleted".to_string(), "true".to_string());

        let frame = Frame::new(
            Basis::Node(node_id),
            b"metadata projection".to_vec(),
            "context-writer-metadata".to_string(),
            "writer-metadata".to_string(),
            metadata,
        )
        .unwrap();
        run_context
            .api()
            .put_frame(node_id, frame, "writer-metadata".to_string())
            .unwrap();

        let output = run_context
            .execute(&Commands::Context {
                command: ContextCommands::Get {
                    node: None,
                    path: Some(test_file),
                    agent: None,
                    frame_type: None,
                    max_frames: 10,
                    ordering: "recency".to_string(),
                    combine: false,
                    separator: "\n\n---\n\n".to_string(),
                    format: "json".to_string(),
                    include_metadata: true,
                    include_deleted: true,
                },
            })
            .unwrap();

        let parsed: serde_json::Value = serde_json::from_str(&output).unwrap();
        let frames = parsed["frames"].as_array().unwrap();
        assert_eq!(frames.len(), 1);
        assert_eq!(frames[0]["agent_id"].as_str(), Some("writer-metadata"));

        let metadata_obj = frames[0]["metadata"].as_object().unwrap();
        assert!(!metadata_obj.contains_key("agent_id"));
        assert!(!metadata_obj.contains_key("deleted"));
        assert_eq!(
            metadata_obj.get("provider").and_then(|v| v.as_str()),
            Some("test-provider")
        );
        assert_eq!(
            metadata_obj.get("model").and_then(|v| v.as_str()),
            Some("test-model")
        );
        assert_eq!(
            metadata_obj.get("provider_type").and_then(|v| v.as_str()),
            Some("ollama")
        );
        assert_eq!(
            metadata_obj.get("prompt_digest").and_then(|v| v.as_str()),
            Some("digest-summarize-file")
        );
        assert_eq!(
            metadata_obj.get("context_digest").and_then(|v| v.as_str()),
            Some("digest-context-file")
        );
        assert_eq!(
            metadata_obj.get("prompt_link_id").and_then(|v| v.as_str()),
            Some("prompt-link-1")
        );
        assert!(!metadata_obj.contains_key("prompt"));
    });
}

#[test]
fn test_context_get_combine() {
    let temp_dir = TempDir::new().unwrap();
    with_xdg_env(&temp_dir, || {
        let workspace_root = temp_dir.path().join("workspace");
        fs::create_dir_all(&workspace_root).unwrap();

        let test_file = workspace_root.join("test.txt");
        fs::write(&test_file, "test content").unwrap();

        let run_context = RunContext::new(workspace_root.clone(), None).unwrap();
        run_context
            .execute(&Commands::Scan { force: true })
            .unwrap();

        let result = run_context.execute(&Commands::Context {
            command: ContextCommands::Get {
                node: None,
                path: Some(test_file),
                agent: None,
                frame_type: None,
                max_frames: 10,
                ordering: "recency".to_string(),
                combine: true,
                separator: " | ".to_string(),
                format: "text".to_string(),
                include_metadata: false,
                include_deleted: false,
            },
        });

        assert!(result.is_ok());
        // With no frames, should still work
    });
}

#[test]
fn test_context_generate_requires_provider() {
    let temp_dir = TempDir::new().unwrap();
    with_xdg_env(&temp_dir, || {
        // Create workspace and agent
        let workspace_root = temp_dir.path().join("workspace");
        fs::create_dir_all(&workspace_root).unwrap();

        let prompts_dir = xdg::prompts_dir().unwrap();
        let prompt_path = prompts_dir.join("test.md");
        fs::write(&prompt_path, "Test prompt").unwrap();

        create_test_agent("test-agent", AgentRole::Writer, Some("prompts/test.md")).unwrap();

        let test_file = workspace_root.join("test.txt");
        fs::write(&test_file, "test content").unwrap();

        let run_context = RunContext::new(workspace_root.clone(), None).unwrap();
        run_context
            .execute(&Commands::Scan { force: true })
            .unwrap();

        // Try to generate without provider
        let result = run_context.execute(&Commands::Context {
            command: ContextCommands::Generate {
                node: None,
                path: Some(test_file),
                path_positional: None,
                agent: Some("test-agent".to_string()),
                provider: None,
                frame_type: None,
                force: false,
                no_recursive: false,
            },
        });

        assert!(result.is_err());
        match result {
            Err(ApiError::ProviderNotConfigured(_)) => {}
            _ => panic!("Expected ProviderNotConfigured error"),
        }
    });
}

#[test]
fn test_context_generate_requires_agent_or_default() {
    let temp_dir = TempDir::new().unwrap();
    with_xdg_env(&temp_dir, || {
        let workspace_root = temp_dir.path().join("workspace");
        fs::create_dir_all(&workspace_root).unwrap();

        let prompts_dir = xdg::prompts_dir().unwrap();
        let prompt_path = prompts_dir.join("test.md");
        fs::write(&prompt_path, "Test prompt").unwrap();

        // Create a single Writer agent (should be used as default)
        create_test_agent("test-agent", AgentRole::Writer, Some("prompts/test.md")).unwrap();
        create_test_provider("test-provider", ProviderType::Ollama).unwrap();

        let test_file = workspace_root.join("test.txt");
        fs::write(&test_file, "test content").unwrap();

        let run_context = RunContext::new(workspace_root.clone(), None).unwrap();
        run_context
            .execute(&Commands::Scan { force: true })
            .unwrap();

        // Should work without --agent (uses default)
        // Note: This will fail at generation time if provider is not actually available,
        // but the agent resolution should work
        let result = run_context.execute(&Commands::Context {
            command: ContextCommands::Generate {
                node: None,
                path: Some(test_file),
                path_positional: None,
                agent: None,
                provider: Some("test-provider".to_string()),
                frame_type: None,
                force: false,
                no_recursive: false,
            },
        });

        // May fail at provider connection, but should not fail at agent resolution
        if let Err(e) = result {
            // Should not be a "no agent" error
            assert!(!e.to_string().contains("No Writer agents found"));
        }
    });
}

#[test]
fn test_context_generate_multiple_agents_requires_flag() {
    let temp_dir = TempDir::new().unwrap();
    with_xdg_env(&temp_dir, || {
        let workspace_root = temp_dir.path().join("workspace");
        fs::create_dir_all(&workspace_root).unwrap();

        let prompts_dir = xdg::prompts_dir().unwrap();
        let prompt_path = prompts_dir.join("test.md");
        fs::write(&prompt_path, "Test prompt").unwrap();

        // Create multiple Writer agents
        create_test_agent("agent1", AgentRole::Writer, Some("prompts/test.md")).unwrap();
        create_test_agent("agent2", AgentRole::Writer, Some("prompts/test.md")).unwrap();
        create_test_provider("test-provider", ProviderType::Ollama).unwrap();

        let test_file = workspace_root.join("test.txt");
        fs::write(&test_file, "test content").unwrap();

        let run_context = RunContext::new(workspace_root.clone(), None).unwrap();
        run_context
            .execute(&Commands::Scan { force: true })
            .unwrap();

        // Should fail without --agent when multiple agents exist
        let result = run_context.execute(&Commands::Context {
            command: ContextCommands::Generate {
                node: None,
                path: Some(test_file),
                path_positional: None,
                agent: None,
                provider: Some("test-provider".to_string()),
                frame_type: None,
                force: false,
                no_recursive: false,
            },
        });

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Multiple Writer agents found"));
    });
}

#[test]
fn test_context_get_invalid_ordering() {
    let temp_dir = TempDir::new().unwrap();
    with_xdg_env(&temp_dir, || {
        let workspace_root = temp_dir.path().join("workspace");
        fs::create_dir_all(&workspace_root).unwrap();

        let test_file = workspace_root.join("test.txt");
        fs::write(&test_file, "test content").unwrap();

        let run_context = RunContext::new(workspace_root.clone(), None).unwrap();
        run_context
            .execute(&Commands::Scan { force: true })
            .unwrap();

        let result = run_context.execute(&Commands::Context {
            command: ContextCommands::Get {
                node: None,
                path: Some(test_file),
                agent: None,
                frame_type: None,
                max_frames: 10,
                ordering: "invalid".to_string(),
                combine: false,
                separator: "\n\n---\n\n".to_string(),
                format: "text".to_string(),
                include_metadata: false,
                include_deleted: false,
            },
        });

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid ordering"));
    });
}

#[test]
fn test_context_get_invalid_format() {
    let temp_dir = TempDir::new().unwrap();
    with_xdg_env(&temp_dir, || {
        let workspace_root = temp_dir.path().join("workspace");
        fs::create_dir_all(&workspace_root).unwrap();

        let test_file = workspace_root.join("test.txt");
        fs::write(&test_file, "test content").unwrap();

        let run_context = RunContext::new(workspace_root.clone(), None).unwrap();
        run_context
            .execute(&Commands::Scan { force: true })
            .unwrap();

        let result = run_context.execute(&Commands::Context {
            command: ContextCommands::Get {
                node: None,
                path: Some(test_file),
                agent: None,
                frame_type: None,
                max_frames: 10,
                ordering: "recency".to_string(),
                combine: false,
                separator: "\n\n---\n\n".to_string(),
                format: "invalid".to_string(),
                include_metadata: false,
                include_deleted: false,
            },
        });

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid format"));
    });
}

#[test]
fn test_context_generate_rejects_async_flag() {
    let parse_result = Cli::try_parse_from([
        "meld",
        "context",
        "generate",
        "--path",
        "./foo.txt",
        "--async",
    ]);
    assert!(parse_result.is_err());
}

#[test]
fn test_context_generate_mutually_exclusive_node_path() {
    let temp_dir = TempDir::new().unwrap();
    with_xdg_env(&temp_dir, || {
        let workspace_root = temp_dir.path().join("workspace");
        fs::create_dir_all(&workspace_root).unwrap();

        let _run_context = RunContext::new(workspace_root.clone(), None).unwrap();

        // This should be caught by clap, but test the execution path anyway
        // Note: clap will prevent both from being set, so this test may not be reachable
        // But we handle it in code for safety
    });
}