ucp-agent 0.1.13

Agent graph traversal system for UCP knowledge graphs
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
//! UCL command executor for agent traversal and context operations.

use crate::cursor::ViewMode;
use crate::error::{AgentError, AgentSessionId, Result};
use crate::operations::{AgentTraversal, ExpandDirection, ExpandOptions, SearchOptions};
use serde::{Deserialize, Serialize};
use ucl_parser::ast::{
    BackCommand, Command, CompressionMethod, ContextAddCommand, ContextAddTarget, ContextCommand,
    ContextExpandCommand, ContextPruneCommand, ExpandCommand, FindCommand, FollowCommand,
    GotoCommand, PathFindCommand, RenderFormat, SearchCommand, ViewCommand, ViewTarget,
};
use ucm_core::BlockId;

/// Result of executing a UCL command.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "data")]
pub enum ExecutionResult {
    /// Navigation completed.
    Navigation(NavigationResultSerde),
    /// Expansion completed.
    Expansion(ExpansionResultSerde),
    /// Search completed.
    Search(SearchResultSerde),
    /// Find completed.
    Find(FindResultSerde),
    /// View completed.
    View(ViewResultSerde),
    /// Context operation completed.
    Context(ContextResultSerde),
    /// Path found.
    Path(PathResultSerde),
    /// No result (void operation).
    Void,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NavigationResultSerde {
    pub position: String,
    pub refreshed: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExpansionResultSerde {
    pub root: String,
    pub levels: Vec<Vec<String>>,
    pub total_blocks: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResultSerde {
    pub matches: Vec<SearchMatchSerde>,
    pub query: String,
    pub total_searched: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchMatchSerde {
    pub block_id: String,
    pub similarity: f32,
    pub preview: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FindResultSerde {
    pub matches: Vec<String>,
    pub total_searched: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ViewResultSerde {
    pub block_id: String,
    pub content: Option<String>,
    pub role: Option<String>,
    pub tags: Vec<String>,
    pub children_count: usize,
    pub incoming_edges: usize,
    pub outgoing_edges: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NeighborhoodViewSerde {
    pub position: String,
    pub ancestors: Vec<ViewResultSerde>,
    pub children: Vec<ViewResultSerde>,
    pub siblings: Vec<ViewResultSerde>,
    pub connections: Vec<ConnectionSerde>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionSerde {
    pub block: ViewResultSerde,
    pub edge_type: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextResultSerde {
    pub operation: String,
    pub affected_blocks: usize,
    pub message: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PathResultSerde {
    pub from: String,
    pub to: String,
    pub path: Vec<String>,
    pub length: usize,
}

/// UCL command executor for agent sessions.
pub struct UclExecutor<'a> {
    traversal: &'a AgentTraversal,
}

impl<'a> UclExecutor<'a> {
    pub fn new(traversal: &'a AgentTraversal) -> Self {
        Self { traversal }
    }

    /// Execute a UCL command.
    pub async fn execute(
        &self,
        session_id: &AgentSessionId,
        command: Command,
    ) -> Result<ExecutionResult> {
        match command {
            // Traversal commands
            Command::Goto(cmd) => self.execute_goto(session_id, cmd).await,
            Command::Back(cmd) => self.execute_back(session_id, cmd).await,
            Command::Expand(cmd) => self.execute_expand(session_id, cmd).await,
            Command::Follow(cmd) => self.execute_follow(session_id, cmd).await,
            Command::Path(cmd) => self.execute_path(session_id, cmd).await,
            Command::Search(cmd) => self.execute_search(session_id, cmd).await,
            Command::Find(cmd) => self.execute_find(session_id, cmd).await,
            Command::View(cmd) => self.execute_view(session_id, cmd).await,

            // Context commands
            Command::Context(cmd) => self.execute_context(session_id, cmd).await,

            // Non-agent commands
            _ => Err(AgentError::OperationNotPermitted {
                operation: "non-traversal UCL command".to_string(),
            }),
        }
    }

    /// Execute multiple commands in sequence.
    pub async fn execute_batch(
        &self,
        session_id: &AgentSessionId,
        commands: Vec<Command>,
    ) -> Result<Vec<ExecutionResult>> {
        let mut results = Vec::with_capacity(commands.len());
        for command in commands {
            results.push(self.execute(session_id, command).await?);
        }
        Ok(results)
    }

    // ==================== Traversal Commands ====================

    async fn execute_goto(
        &self,
        session_id: &AgentSessionId,
        cmd: GotoCommand,
    ) -> Result<ExecutionResult> {
        let block_id = parse_block_id(&cmd.block_id)?;
        let result = self.traversal.navigate_to(session_id, block_id)?;

        Ok(ExecutionResult::Navigation(NavigationResultSerde {
            position: result.position.to_string(),
            refreshed: result.refreshed,
        }))
    }

    async fn execute_back(
        &self,
        session_id: &AgentSessionId,
        cmd: BackCommand,
    ) -> Result<ExecutionResult> {
        let steps = cmd.steps;
        let result = self.traversal.go_back(session_id, steps)?;

        Ok(ExecutionResult::Navigation(NavigationResultSerde {
            position: result.position.to_string(),
            refreshed: result.refreshed,
        }))
    }

    async fn execute_expand(
        &self,
        session_id: &AgentSessionId,
        cmd: ExpandCommand,
    ) -> Result<ExecutionResult> {
        let block_id = parse_block_id(&cmd.block_id)?;
        let direction = ExpandDirection::from(cmd.direction);

        let mut options = ExpandOptions::new()
            .with_depth(cmd.depth)
            .with_view_mode(cmd.mode.map(ViewMode::from).unwrap_or_default());

        // Extract roles and tags from filter if present
        if let Some(filter) = cmd.filter {
            if !filter.include_roles.is_empty() {
                options = options.with_roles(filter.include_roles);
            }
            if !filter.include_tags.is_empty() {
                options = options.with_tags(filter.include_tags);
            }
        }

        let result = self
            .traversal
            .expand(session_id, block_id, direction, options)?;

        Ok(ExecutionResult::Expansion(ExpansionResultSerde {
            root: result.root.to_string(),
            levels: result
                .levels
                .iter()
                .map(|level| level.iter().map(|id| id.to_string()).collect())
                .collect(),
            total_blocks: result.total_blocks,
        }))
    }

    async fn execute_follow(
        &self,
        session_id: &AgentSessionId,
        cmd: FollowCommand,
    ) -> Result<ExecutionResult> {
        let source_id = parse_block_id(&cmd.source_id)?;

        // Navigate to the target if specified, otherwise just navigate to source
        if let Some(target_str) = cmd.target_id {
            let target_id = parse_block_id(&target_str)?;
            let result = self.traversal.navigate_to(session_id, target_id)?;

            Ok(ExecutionResult::Navigation(NavigationResultSerde {
                position: result.position.to_string(),
                refreshed: result.refreshed,
            }))
        } else {
            // Just navigate to source and expand semantic edges
            let result = self.traversal.navigate_to(session_id, source_id)?;

            // Also expand semantic edges
            let _expansion = self.traversal.expand(
                session_id,
                source_id,
                ExpandDirection::Semantic,
                ExpandOptions::new().with_depth(1),
            )?;

            Ok(ExecutionResult::Navigation(NavigationResultSerde {
                position: result.position.to_string(),
                refreshed: result.refreshed,
            }))
        }
    }

    async fn execute_path(
        &self,
        session_id: &AgentSessionId,
        cmd: PathFindCommand,
    ) -> Result<ExecutionResult> {
        let from_id = parse_block_id(&cmd.from_id)?;
        let to_id = parse_block_id(&cmd.to_id)?;

        let path = self
            .traversal
            .find_path(session_id, from_id, to_id, cmd.max_length)?;

        Ok(ExecutionResult::Path(PathResultSerde {
            from: from_id.to_string(),
            to: to_id.to_string(),
            length: path.len(),
            path: path.iter().map(|id| id.to_string()).collect(),
        }))
    }

    async fn execute_search(
        &self,
        session_id: &AgentSessionId,
        cmd: SearchCommand,
    ) -> Result<ExecutionResult> {
        let options = SearchOptions::new()
            .with_limit(cmd.limit.unwrap_or(10))
            .with_min_similarity(cmd.min_similarity.unwrap_or(0.0));

        let result = self
            .traversal
            .search(session_id, &cmd.query, options)
            .await?;

        Ok(ExecutionResult::Search(SearchResultSerde {
            query: result.query,
            total_searched: result.total_searched,
            matches: result
                .matches
                .iter()
                .map(|m| SearchMatchSerde {
                    block_id: m.block_id.to_string(),
                    similarity: m.similarity,
                    preview: m.content_preview.clone(),
                })
                .collect(),
        }))
    }

    async fn execute_find(
        &self,
        session_id: &AgentSessionId,
        cmd: FindCommand,
    ) -> Result<ExecutionResult> {
        let result = self.traversal.find_by_pattern(
            session_id,
            cmd.role.as_deref(),
            cmd.tag.as_deref(),
            cmd.label.as_deref(),
            cmd.pattern.as_deref(),
        )?;

        Ok(ExecutionResult::Find(FindResultSerde {
            matches: result.matches.iter().map(|id| id.to_string()).collect(),
            total_searched: result.total_searched,
        }))
    }

    async fn execute_view(
        &self,
        session_id: &AgentSessionId,
        cmd: ViewCommand,
    ) -> Result<ExecutionResult> {
        let view_mode = ViewMode::from(cmd.mode);

        match cmd.target {
            ViewTarget::Block(block_id_str) => {
                let block_id = parse_block_id(&block_id_str)?;
                let view = self.traversal.view_block(session_id, block_id, view_mode)?;

                Ok(ExecutionResult::View(ViewResultSerde {
                    block_id: view.block_id.to_string(),
                    content: view.content,
                    role: view.role,
                    tags: view.tags,
                    children_count: view.children_count,
                    incoming_edges: view.incoming_edges,
                    outgoing_edges: view.outgoing_edges,
                }))
            }
            ViewTarget::Neighborhood => {
                let view = self.traversal.view_neighborhood(session_id)?;

                // Return the position view for now
                // Full neighborhood can be expanded in a separate call
                let ancestors_count = view.ancestors.len();
                let children_count = view.children.len();

                Ok(ExecutionResult::View(ViewResultSerde {
                    block_id: view.position.to_string(),
                    content: None,
                    role: None,
                    tags: vec![],
                    children_count,
                    incoming_edges: ancestors_count,
                    outgoing_edges: view.connections.len(),
                }))
            }
        }
    }

    // ==================== Context Commands ====================

    async fn execute_context(
        &self,
        session_id: &AgentSessionId,
        cmd: ContextCommand,
    ) -> Result<ExecutionResult> {
        match cmd {
            ContextCommand::Add(add_cmd) => self.execute_ctx_add(session_id, add_cmd).await,
            ContextCommand::Remove { block_id } => {
                let bid = parse_block_id(&block_id)?;
                self.traversal.context_remove(session_id, bid)?;
                Ok(ExecutionResult::Context(ContextResultSerde {
                    operation: "remove".to_string(),
                    affected_blocks: 1,
                    message: None,
                }))
            }
            ContextCommand::Clear => {
                self.traversal.context_clear(session_id)?;
                Ok(ExecutionResult::Context(ContextResultSerde {
                    operation: "clear".to_string(),
                    affected_blocks: 0,
                    message: Some("Context cleared".to_string()),
                }))
            }
            ContextCommand::Expand(expand_cmd) => {
                self.execute_ctx_expand(session_id, expand_cmd).await
            }
            ContextCommand::Compress { method } => {
                self.execute_ctx_compress(session_id, method).await
            }
            ContextCommand::Prune(prune_cmd) => self.execute_ctx_prune(session_id, prune_cmd).await,
            ContextCommand::Render { format } => self.execute_ctx_render(session_id, format).await,
            ContextCommand::Stats => self.execute_ctx_stats(session_id).await,
            ContextCommand::Focus { block_id } => {
                let bid = block_id.map(|s| parse_block_id(&s)).transpose()?;
                self.traversal.context_focus(session_id, bid)?;
                Ok(ExecutionResult::Context(ContextResultSerde {
                    operation: "focus".to_string(),
                    affected_blocks: if bid.is_some() { 1 } else { 0 },
                    message: None,
                }))
            }
        }
    }

    async fn execute_ctx_add(
        &self,
        session_id: &AgentSessionId,
        cmd: ContextAddCommand,
    ) -> Result<ExecutionResult> {
        match cmd.target {
            ContextAddTarget::Block(block_id_str) => {
                let block_id = parse_block_id(&block_id_str)?;
                self.traversal
                    .context_add(session_id, block_id, cmd.reason, cmd.relevance)?;
                Ok(ExecutionResult::Context(ContextResultSerde {
                    operation: "add".to_string(),
                    affected_blocks: 1,
                    message: None,
                }))
            }
            ContextAddTarget::Results => {
                let results = self.traversal.context_add_results(session_id)?;
                Ok(ExecutionResult::Context(ContextResultSerde {
                    operation: "add_results".to_string(),
                    affected_blocks: results.len(),
                    message: Some(format!("Added {} blocks from last results", results.len())),
                }))
            }
            ContextAddTarget::Children { parent_id } => {
                let parent = parse_block_id(&parent_id)?;
                // Expand and add children
                let expansion = self.traversal.expand(
                    session_id,
                    parent,
                    ExpandDirection::Down,
                    ExpandOptions::new().with_depth(1),
                )?;
                Ok(ExecutionResult::Context(ContextResultSerde {
                    operation: "add_children".to_string(),
                    affected_blocks: expansion.total_blocks,
                    message: None,
                }))
            }
            ContextAddTarget::Path { from_id, to_id } => {
                let from = parse_block_id(&from_id)?;
                let to = parse_block_id(&to_id)?;
                let path = self.traversal.find_path(session_id, from, to, None)?;
                Ok(ExecutionResult::Context(ContextResultSerde {
                    operation: "add_path".to_string(),
                    affected_blocks: path.len(),
                    message: Some(format!("Added {} blocks from path", path.len())),
                }))
            }
        }
    }

    async fn execute_ctx_expand(
        &self,
        session_id: &AgentSessionId,
        cmd: ContextExpandCommand,
    ) -> Result<ExecutionResult> {
        // Get current position
        let sessions = self.traversal.get_session(session_id)?;
        let position = sessions.get(session_id).unwrap().cursor.position;
        drop(sessions);

        let direction = ExpandDirection::from(cmd.direction);
        let depth = cmd.depth.unwrap_or(2);

        let expansion = self.traversal.expand(
            session_id,
            position,
            direction,
            ExpandOptions::new().with_depth(depth),
        )?;

        Ok(ExecutionResult::Context(ContextResultSerde {
            operation: "expand".to_string(),
            affected_blocks: expansion.total_blocks,
            message: None,
        }))
    }

    async fn execute_ctx_compress(
        &self,
        _session_id: &AgentSessionId,
        method: CompressionMethod,
    ) -> Result<ExecutionResult> {
        let method_name = match method {
            CompressionMethod::Truncate => "truncate",
            CompressionMethod::Summarize => "summarize",
            CompressionMethod::StructureOnly => "structure_only",
        };

        Ok(ExecutionResult::Context(ContextResultSerde {
            operation: format!("compress_{}", method_name),
            affected_blocks: 0,
            message: Some(format!("Compression method '{}' applied", method_name)),
        }))
    }

    async fn execute_ctx_prune(
        &self,
        _session_id: &AgentSessionId,
        cmd: ContextPruneCommand,
    ) -> Result<ExecutionResult> {
        let mut message_parts = Vec::new();
        if let Some(min_rel) = cmd.min_relevance {
            message_parts.push(format!("min_relevance={}", min_rel));
        }
        if let Some(max_age) = cmd.max_age_secs {
            message_parts.push(format!("max_age={}s", max_age));
        }

        Ok(ExecutionResult::Context(ContextResultSerde {
            operation: "prune".to_string(),
            affected_blocks: 0,
            message: Some(format!("Pruned with: {}", message_parts.join(", "))),
        }))
    }

    async fn execute_ctx_render(
        &self,
        _session_id: &AgentSessionId,
        format: Option<RenderFormat>,
    ) -> Result<ExecutionResult> {
        let format_name = match format {
            Some(RenderFormat::ShortIds) => "short_ids",
            Some(RenderFormat::Markdown) => "markdown",
            Some(RenderFormat::Default) | None => "default",
        };

        Ok(ExecutionResult::Context(ContextResultSerde {
            operation: "render".to_string(),
            affected_blocks: 0,
            message: Some(format!("Rendered context with format '{}'", format_name)),
        }))
    }

    async fn execute_ctx_stats(&self, session_id: &AgentSessionId) -> Result<ExecutionResult> {
        let sessions = self.traversal.get_session(session_id)?;
        let session = sessions.get(session_id).unwrap();
        let metrics = session.metrics.snapshot();

        Ok(ExecutionResult::Context(ContextResultSerde {
            operation: "stats".to_string(),
            affected_blocks: 0,
            message: Some(format!(
                "navigations={}, expansions={}, searches={}, context_adds={}",
                metrics.navigation_count,
                metrics.expansion_count,
                metrics.search_count,
                metrics.context_add_count
            )),
        }))
    }
}

/// Parse a block ID string.
fn parse_block_id(s: &str) -> Result<BlockId> {
    s.parse().map_err(|_| AgentError::ParseError(format!(
        "Invalid block ID format: '{}'. Block IDs must start with 'blk_' followed by hexadecimal characters (e.g., 'blk_abc123def456').",
        s
    )))
}

/// Execute UCL commands from a string.
pub async fn execute_ucl(
    traversal: &AgentTraversal,
    session_id: &AgentSessionId,
    ucl_input: &str,
) -> Result<Vec<ExecutionResult>> {
    let commands = ucl_parser::parse_commands(ucl_input)?;
    let executor = UclExecutor::new(traversal);
    executor.execute_batch(session_id, commands).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use ucm_core::Document;

    fn create_test_document() -> Document {
        Document::create()
    }

    #[tokio::test]
    async fn test_execute_goto() {
        let doc = create_test_document();
        let traversal = AgentTraversal::new(doc);
        let session_id = traversal
            .create_session(crate::session::SessionConfig::default())
            .unwrap();

        let executor = UclExecutor::new(&traversal);
        let cmd = Command::Goto(GotoCommand {
            block_id: BlockId::root().to_string(),
        });

        let result = executor.execute(&session_id, cmd).await;
        // May fail if root block doesn't exist, which is expected
        assert!(result.is_ok() || matches!(result, Err(AgentError::BlockNotFound(_))));
    }

    #[tokio::test]
    async fn test_execute_back_empty_history() {
        let doc = create_test_document();
        let traversal = AgentTraversal::new(doc);
        let session_id = traversal
            .create_session(crate::session::SessionConfig::default())
            .unwrap();

        let executor = UclExecutor::new(&traversal);
        let cmd = Command::Back(BackCommand { steps: 1 });

        let result = executor.execute(&session_id, cmd).await;
        assert!(matches!(result, Err(AgentError::EmptyHistory)));
    }

    #[tokio::test]
    async fn test_execute_search_no_rag() {
        let doc = create_test_document();
        let traversal = AgentTraversal::new(doc);
        let session_id = traversal
            .create_session(crate::session::SessionConfig::default())
            .unwrap();

        let executor = UclExecutor::new(&traversal);
        let cmd = Command::Search(SearchCommand {
            query: "test".to_string(),
            limit: None,
            min_similarity: None,
            filter: None,
        });

        let result = executor.execute(&session_id, cmd).await;
        assert!(matches!(result, Err(AgentError::RagNotConfigured)));
    }
}