agm-core 1.1.0

Core library for parsing, validating, loading, and rendering AGM (Agent Graph Memory) files
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
//! Markdown renderer: produces a human-readable Markdown document.
//!
//! Nodes are grouped by type with type headers. Within each group,
//! nodes appear in their original order.

use crate::model::code::CodeBlock;
use crate::model::context::AgentContext;
use crate::model::fields::NodeType;
use crate::model::file::AgmFile;
use crate::model::memory::MemoryEntry;
use crate::model::node::Node;
use crate::model::orchestration::ParallelGroup;
use crate::model::verify::VerifyCheck;

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Renders the `AgmFile` as a human-readable Markdown document.
///
/// Nodes are grouped by type with type headers. Within each group,
/// nodes appear in their original order. Only sections with at least one
/// node are emitted.
#[must_use]
pub fn render_markdown(file: &AgmFile) -> String {
    let mut buf = String::new();

    // Document title
    buf.push_str(&format!(
        "# {} v{}\n",
        file.header.package, file.header.version
    ));

    if let Some(ref title) = file.header.title {
        buf.push('\n');
        buf.push_str(&format!("> {title}\n"));
    }

    if let Some(ref desc) = file.header.description {
        buf.push('\n');
        buf.push_str(desc);
        buf.push('\n');
    }

    // Properties table
    let has_props = file.header.owner.is_some()
        || file.header.status.is_some()
        || file.header.default_load.is_some()
        || file.header.tags.is_some()
        || file.header.target_runtime.is_some();

    if has_props {
        buf.push('\n');
        buf.push_str("| Property | Value |\n");
        buf.push_str("|----------|-------|\n");
        if let Some(ref owner) = file.header.owner {
            buf.push_str(&format!("| Owner | {owner} |\n"));
        }
        if let Some(ref status) = file.header.status {
            buf.push_str(&format!("| Status | {status} |\n"));
        }
        if let Some(ref dl) = file.header.default_load {
            buf.push_str(&format!("| Default load | {dl} |\n"));
        }
        if let Some(ref tags) = file.header.tags {
            buf.push_str(&format!("| Tags | {} |\n", tags.join(", ")));
        }
        if let Some(ref rt) = file.header.target_runtime {
            buf.push_str(&format!("| Target runtime | {rt} |\n"));
        }
    }

    // Imports section
    if let Some(ref imports) = file.header.imports {
        if !imports.is_empty() {
            buf.push('\n');
            buf.push_str("## Imports\n\n");
            for import in imports {
                buf.push_str(&format!("- `{import}`\n"));
            }
        }
    }

    // Node sections grouped by type
    let type_order = type_order();
    let mut remaining: Vec<&Node> = file.nodes.iter().collect();

    for node_type in &type_order {
        let group: Vec<&Node> = remaining
            .iter()
            .copied()
            .filter(|n| std::mem::discriminant(&n.node_type) == std::mem::discriminant(node_type))
            .collect();

        if group.is_empty() {
            continue;
        }

        // Remove these nodes from remaining so custom types can be handled
        remaining
            .retain(|n| std::mem::discriminant(&n.node_type) != std::mem::discriminant(node_type));

        buf.push('\n');
        buf.push_str(&format!("## {}\n", type_display_name(node_type)));

        for node in group {
            buf.push('\n');
            render_node_section(&mut buf, node);
        }
    }

    // Custom types — group by type name, sorted
    let mut custom_types: Vec<String> = remaining
        .iter()
        .map(|n| n.node_type.to_string())
        .collect::<std::collections::BTreeSet<_>>()
        .into_iter()
        .collect();
    custom_types.sort();

    for type_name in custom_types {
        let group: Vec<&Node> = remaining
            .iter()
            .copied()
            .filter(|n| n.node_type.to_string() == type_name)
            .collect();

        if group.is_empty() {
            continue;
        }

        buf.push('\n');
        buf.push_str(&format!("## {}\n", capitalize_first(&type_name)));

        for node in group {
            buf.push('\n');
            render_node_section(&mut buf, node);
        }
    }

    buf
}

// ---------------------------------------------------------------------------
// Node section rendering
// ---------------------------------------------------------------------------

fn render_node_section(buf: &mut String, node: &Node) {
    buf.push_str(&format!("### `{}`\n\n", node.id));
    buf.push_str(&node.summary);
    buf.push('\n');

    // Control table
    let has_control = node.priority.is_some()
        || node.stability.is_some()
        || node.confidence.is_some()
        || node.status.is_some();

    if has_control {
        buf.push('\n');
        buf.push_str("| Control | Value |\n");
        buf.push_str("|---------|-------|\n");
        if let Some(ref p) = node.priority {
            buf.push_str(&format!("| Priority | {p} |\n"));
        }
        if let Some(ref s) = node.stability {
            buf.push_str(&format!("| Stability | {s} |\n"));
        }
        if let Some(ref c) = node.confidence {
            buf.push_str(&format!("| Confidence | {c} |\n"));
        }
        if let Some(ref s) = node.status {
            buf.push_str(&format!("| Status | {s} |\n"));
        }
    }

    // Tags
    if let Some(ref tags) = node.tags {
        if !tags.is_empty() {
            buf.push('\n');
            buf.push_str(&format!("**Tags**: {}\n", tags.join(", ")));
        }
    }

    // Relationships
    render_opt_rel(buf, "Depends on", &node.depends);
    render_opt_rel(buf, "Related to", &node.related_to);
    render_opt_rel(buf, "Replaces", &node.replaces);
    render_opt_rel(buf, "Conflicts with", &node.conflicts);
    render_opt_rel(buf, "See also", &node.see_also);

    // I/O
    if let Some(ref input) = node.input {
        if !input.is_empty() {
            buf.push('\n');
            buf.push_str(&format!("**Input**: {}\n", format_id_list(input)));
        }
    }
    if let Some(ref output) = node.output {
        if !output.is_empty() {
            buf.push('\n');
            buf.push_str(&format!("**Output**: {}\n", format_id_list(output)));
        }
    }

    // Detail
    if let Some(ref detail) = node.detail {
        buf.push('\n');
        buf.push_str("#### Detail\n\n");
        buf.push_str(detail);
        buf.push('\n');
    }

    // Items
    if let Some(ref items) = node.items {
        if !items.is_empty() {
            buf.push('\n');
            buf.push_str("#### Items\n\n");
            for item in items {
                buf.push_str(&format!("- {item}\n"));
            }
        }
    }

    // Steps
    if let Some(ref steps) = node.steps {
        if !steps.is_empty() {
            buf.push('\n');
            buf.push_str("#### Steps\n\n");
            for (i, step) in steps.iter().enumerate() {
                buf.push_str(&format!("{}. {step}\n", i + 1));
            }
        }
    }

    // Fields
    if let Some(ref fields) = node.fields {
        if !fields.is_empty() {
            buf.push('\n');
            buf.push_str("#### Fields\n\n");
            for field in fields {
                buf.push_str(&format!("- {field}\n"));
            }
        }
    }

    // Rationale
    if let Some(ref rationale) = node.rationale {
        if !rationale.is_empty() {
            buf.push('\n');
            buf.push_str("#### Rationale\n\n");
            for r in rationale {
                buf.push_str(&format!("- {r}\n"));
            }
        }
    }

    // Tradeoffs
    if let Some(ref tradeoffs) = node.tradeoffs {
        if !tradeoffs.is_empty() {
            buf.push('\n');
            buf.push_str("#### Tradeoffs\n\n");
            for t in tradeoffs {
                buf.push_str(&format!("- {t}\n"));
            }
        }
    }

    // Resolution
    if let Some(ref resolution) = node.resolution {
        if !resolution.is_empty() {
            buf.push('\n');
            buf.push_str("#### Resolution\n\n");
            for r in resolution {
                buf.push_str(&format!("- {r}\n"));
            }
        }
    }

    // Examples
    if let Some(ref examples) = node.examples {
        buf.push('\n');
        buf.push_str("#### Examples\n\n");
        buf.push_str(examples);
        buf.push('\n');
    }

    // Notes
    if let Some(ref notes) = node.notes {
        buf.push('\n');
        buf.push_str("#### Notes\n\n");
        buf.push_str(notes);
        buf.push('\n');
    }

    // Code
    if let Some(ref cb) = node.code {
        buf.push('\n');
        buf.push_str("#### Code\n\n");
        render_code_block_md(buf, cb);
    }

    // Code blocks
    if let Some(ref blocks) = node.code_blocks {
        if !blocks.is_empty() {
            buf.push('\n');
            buf.push_str("#### Code Blocks\n\n");
            for cb in blocks {
                render_code_block_md(buf, cb);
            }
        }
    }

    // Verify
    if let Some(ref checks) = node.verify {
        if !checks.is_empty() {
            buf.push('\n');
            buf.push_str("#### Verification\n\n");
            for check in checks {
                render_verify_check_md(buf, check);
            }
        }
    }

    // Agent context
    if let Some(ref ctx) = node.agent_context {
        buf.push('\n');
        render_agent_context_md(buf, ctx);
    }

    // Memory
    if let Some(ref entries) = node.memory {
        if !entries.is_empty() {
            buf.push('\n');
            buf.push_str("#### Memory\n\n");
            render_memory_table_md(buf, entries);
        }
    }

    // Parallel groups
    if let Some(ref groups) = node.parallel_groups {
        if !groups.is_empty() {
            buf.push('\n');
            buf.push_str("#### Parallel Groups\n\n");
            render_parallel_groups_md(buf, groups);
        }
    }

    // Execution state
    let has_exec =
        node.execution_status.is_some() || node.executed_by.is_some() || node.executed_at.is_some();

    if has_exec {
        buf.push('\n');
        buf.push_str("#### Execution State\n\n");
        if let Some(ref s) = node.execution_status {
            buf.push_str(&format!("- **Status**: {s}\n"));
        }
        if let Some(ref by) = node.executed_by {
            buf.push_str(&format!("- **Executed by**: {by}\n"));
        }
        if let Some(ref at) = node.executed_at {
            buf.push_str(&format!("- **Executed at**: {at}\n"));
        }
        if let Some(n) = node.retry_count {
            buf.push_str(&format!("- **Retry count**: {n}\n"));
        }
    }

    buf.push_str("\n---\n");
}

// ---------------------------------------------------------------------------
// Sub-renderers
// ---------------------------------------------------------------------------

fn render_opt_rel(buf: &mut String, label: &str, val: &Option<Vec<String>>) {
    if let Some(ids) = val {
        if !ids.is_empty() {
            buf.push('\n');
            buf.push_str(&format!("**{label}**: {}\n", format_id_list(ids)));
        }
    }
}

fn format_id_list(ids: &[String]) -> String {
    ids.iter()
        .map(|id| format!("`{id}`"))
        .collect::<Vec<_>>()
        .join(", ")
}

fn render_code_block_md(buf: &mut String, cb: &CodeBlock) {
    let lang = cb.lang.as_deref().unwrap_or("");
    if let Some(ref target) = cb.target {
        buf.push_str(&format!("**File**: `{target}`  \n"));
    }
    if let Some(ref anchor) = cb.anchor {
        buf.push_str(&format!("**Anchor**: `{anchor}`  \n"));
    }
    buf.push_str(&format!("**Action**: {}  \n\n", cb.action));
    buf.push_str(&format!("```{lang}\n"));
    buf.push_str(&cb.body);
    if !cb.body.ends_with('\n') {
        buf.push('\n');
    }
    buf.push_str("```\n");
}

fn render_verify_check_md(buf: &mut String, check: &VerifyCheck) {
    match check {
        VerifyCheck::Command { run, expect } => {
            let exp_str = expect
                .as_deref()
                .map(|e| format!(" (expect: {e})"))
                .unwrap_or_default();
            buf.push_str(&format!("- `{run}`{exp_str}\n"));
        }
        VerifyCheck::FileExists { file } => {
            buf.push_str(&format!("- File exists: `{file}`\n"));
        }
        VerifyCheck::FileContains { file, pattern } => {
            buf.push_str(&format!("- `{file}` contains `{pattern}`\n"));
        }
        VerifyCheck::FileNotContains { file, pattern } => {
            buf.push_str(&format!("- `{file}` does NOT contain `{pattern}`\n"));
        }
        VerifyCheck::NodeStatus { node, status } => {
            buf.push_str(&format!("- Node `{node}` has status `{status}`\n"));
        }
    }
}

fn render_agent_context_md(buf: &mut String, ctx: &AgentContext) {
    buf.push_str("#### Agent Context\n\n");
    if let Some(ref nodes) = ctx.load_nodes {
        buf.push_str(&format!("**Load nodes**: {}\n\n", format_id_list(nodes)));
    }
    if let Some(ref files) = ctx.load_files {
        buf.push_str("**Load files**:\n");
        for lf in files {
            buf.push_str(&format!(
                "- `{}` (range: {})\n",
                lf.path,
                format_file_range(&lf.range)
            ));
        }
        buf.push('\n');
    }
    if let Some(ref hint) = ctx.system_hint {
        buf.push_str(&format!("**System hint**: {hint}\n\n"));
    }
}

fn format_file_range(range: &crate::model::context::FileRange) -> String {
    match range {
        crate::model::context::FileRange::Full => "full".into(),
        crate::model::context::FileRange::Lines(s, e) => format!("{s}-{e}"),
        crate::model::context::FileRange::Function(name) => format!("function: {name}"),
    }
}

fn render_memory_table_md(buf: &mut String, entries: &[MemoryEntry]) {
    buf.push_str("| Key | Topic | Action | Value |\n");
    buf.push_str("|-----|-------|--------|-------|\n");
    for entry in entries {
        let value = entry.value.as_deref().unwrap_or("-");
        buf.push_str(&format!(
            "| {} | {} | {} | {} |\n",
            entry.key, entry.topic, entry.action, value
        ));
    }
}

fn render_parallel_groups_md(buf: &mut String, groups: &[ParallelGroup]) {
    buf.push_str("| Group | Nodes | Strategy |\n");
    buf.push_str("|-------|-------|----------|\n");
    for group in groups {
        buf.push_str(&format!(
            "| {} | {} | {} |\n",
            group.group,
            group.nodes.join(", "),
            group.strategy
        ));
    }
}

// ---------------------------------------------------------------------------
// Type ordering and display names
// ---------------------------------------------------------------------------

fn type_order() -> Vec<NodeType> {
    vec![
        NodeType::Facts,
        NodeType::Rules,
        NodeType::Workflow,
        NodeType::Entity,
        NodeType::Decision,
        NodeType::Exception,
        NodeType::Example,
        NodeType::Glossary,
        NodeType::AntiPattern,
        NodeType::Orchestration,
    ]
}

fn type_display_name(node_type: &NodeType) -> &'static str {
    match node_type {
        NodeType::Facts => "Facts",
        NodeType::Rules => "Rules",
        NodeType::Workflow => "Workflow",
        NodeType::Entity => "Entity",
        NodeType::Decision => "Decision",
        NodeType::Exception => "Exception",
        NodeType::Example => "Example",
        NodeType::Glossary => "Glossary",
        NodeType::AntiPattern => "Anti-Pattern",
        NodeType::Orchestration => "Orchestration",
        NodeType::Custom(_) => "Custom",
    }
}

fn capitalize_first(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        None => String::new(),
        Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::fields::{NodeType, Priority, Span, Stability};
    use crate::model::file::{AgmFile, Header};
    use crate::model::node::Node;
    use std::collections::BTreeMap;

    fn minimal_file() -> AgmFile {
        AgmFile {
            header: Header {
                agm: "1".to_owned(),
                package: "test.minimal".to_owned(),
                version: "0.1.0".to_owned(),
                title: None,
                owner: None,
                imports: None,
                default_load: None,
                description: None,
                tags: None,
                status: None,
                load_profiles: None,
                target_runtime: None,
            },
            nodes: vec![Node {
                id: "test.node".to_owned(),
                node_type: NodeType::Facts,
                summary: "a minimal test node".to_owned(),
                priority: None,
                stability: None,
                confidence: None,
                status: None,
                depends: None,
                related_to: None,
                replaces: None,
                conflicts: None,
                see_also: None,
                items: None,
                steps: None,
                fields: None,
                input: None,
                output: None,
                detail: None,
                rationale: None,
                tradeoffs: None,
                resolution: None,
                examples: None,
                notes: None,
                code: None,
                code_blocks: None,
                verify: None,
                agent_context: None,
                target: None,
                execution_status: None,
                executed_by: None,
                executed_at: None,
                execution_log: None,
                retry_count: None,
                parallel_groups: None,
                memory: None,
                scope: None,
                applies_when: None,
                valid_from: None,
                valid_until: None,
                tags: None,
                aliases: None,
                keywords: None,
                extra_fields: BTreeMap::new(),
                span: Span::default(),
            }],
        }
    }

    #[test]
    fn test_render_markdown_groups_by_type() {
        let mut file = minimal_file();
        // Add a workflow node
        let mut wf = file.nodes[0].clone();
        wf.id = "test.workflow".into();
        wf.node_type = NodeType::Workflow;
        wf.summary = "a workflow node".into();
        file.nodes.push(wf);

        let output = render_markdown(&file);
        let facts_pos = output.find("## Facts").unwrap();
        let workflow_pos = output.find("## Workflow").unwrap();
        assert!(
            facts_pos < workflow_pos,
            "Facts section before Workflow section"
        );
    }

    #[test]
    fn test_render_markdown_title_in_header() {
        let file = minimal_file();
        let output = render_markdown(&file);
        assert!(output.starts_with("# test.minimal v0.1.0\n"));
    }

    #[test]
    fn test_render_markdown_node_has_summary() {
        let file = minimal_file();
        let output = render_markdown(&file);
        assert!(output.contains("a minimal test node"));
    }

    #[test]
    fn test_render_markdown_control_table_when_priority() {
        let mut file = minimal_file();
        file.nodes[0].priority = Some(Priority::Critical);
        file.nodes[0].stability = Some(Stability::High);
        let output = render_markdown(&file);
        assert!(output.contains("| Control | Value |"));
        assert!(output.contains("| Priority | critical |"));
        assert!(output.contains("| Stability | high |"));
    }

    #[test]
    fn test_render_markdown_depends_section() {
        let mut file = minimal_file();
        file.nodes[0].depends = Some(vec!["auth.constraints".into()]);
        let output = render_markdown(&file);
        assert!(output.contains("**Depends on**: `auth.constraints`"));
    }

    #[test]
    fn test_render_markdown_no_empty_sections() {
        let file = minimal_file();
        let output = render_markdown(&file);
        // Should not have empty type sections for types with no nodes
        assert!(!output.contains("## Rules\n\n---"));
        assert!(!output.contains("## Workflow\n\n---"));
    }

    #[test]
    fn test_render_markdown_imports_section() {
        let mut file = minimal_file();
        file.header.imports = Some(vec![crate::model::imports::ImportEntry::new(
            "shared.security".into(),
            Some("^1.0.0".into()),
        )]);
        let output = render_markdown(&file);
        assert!(output.contains("## Imports\n"));
        assert!(output.contains("- `shared.security@^1.0.0`"));
    }
}