agm-core 1.0.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
//! Parser for `.agm.state` sidecar files.

use std::collections::BTreeMap;
use std::str::FromStr;

use crate::error::{AgmError, ErrorCode, ErrorLocation};
use crate::model::execution::ExecutionStatus;
use crate::model::state::{NodeState, StateFile};
use crate::parser::ParseResult;
use crate::parser::sidecar::{SidecarLineKind, lex_sidecar};

// ---------------------------------------------------------------------------
// parse_state
// ---------------------------------------------------------------------------

/// Parses raw `.agm.state` text into a [`StateFile`].
///
/// Returns `Err(Vec<AgmError>)` if any Error-severity diagnostics are
/// produced (missing required headers, bad enum values, duplicate node IDs).
/// Warnings (unknown fields) are returned inside the `Ok` payload via the
/// diagnostic approach — since `ParseResult<StateFile>` only carries errors
/// we collect warnings as `AgmError` with `Severity::Warning` but still
/// return `Ok` as long as no errors are present.
///
/// To keep the API consistent with the rest of the codebase, warnings are
/// currently accumulated but not returned (they would be returned via a
/// `DiagnosticCollection` in a higher-level API). Fatal errors always cause
/// `Err`.
pub fn parse_state(input: &str) -> ParseResult<StateFile> {
    let lines = lex_sidecar(input)?;
    let mut pos = 0;
    let mut errors: Vec<AgmError> = Vec::new();

    // ------------------------------------------------------------------
    // 1. Consume header lines (# key: value)
    // ------------------------------------------------------------------
    let mut format_version: Option<String> = None;
    let mut package: Option<String> = None;
    let mut version: Option<String> = None;
    let mut session_id: Option<String> = None;
    let mut started_at: Option<String> = None;
    let mut updated_at: Option<String> = None;

    while pos < lines.len() {
        match &lines[pos].kind {
            SidecarLineKind::Blank | SidecarLineKind::Comment(_) => {
                pos += 1;
            }
            SidecarLineKind::Header(key, value) => {
                match key.as_str() {
                    "agm.state" => format_version = Some(value.clone()),
                    "package" => package = Some(value.clone()),
                    "version" => version = Some(value.clone()),
                    "session_id" => session_id = Some(value.clone()),
                    "started_at" => started_at = Some(value.clone()),
                    "updated_at" => updated_at = Some(value.clone()),
                    _ => {
                        // unknown header — emit warning but continue
                        errors.push(AgmError::new(
                            ErrorCode::P009,
                            format!("Unknown header field '{}' in state file", key),
                            ErrorLocation::new(None, Some(lines[pos].number), None),
                        ));
                    }
                }
                pos += 1;
            }
            // Once we hit a non-header line, headers are done
            _ => break,
        }
    }

    // Validate required headers
    for (field, present) in [
        ("agm.state", format_version.is_some()),
        ("package", package.is_some()),
        ("version", version.is_some()),
        ("session_id", session_id.is_some()),
        ("started_at", started_at.is_some()),
        ("updated_at", updated_at.is_some()),
    ] {
        if !present {
            errors.push(AgmError::new(
                ErrorCode::P001,
                format!("Missing required header field '{field}' in state file"),
                ErrorLocation::new(None, Some(1), None),
            ));
        }
    }

    // ------------------------------------------------------------------
    // 2. Parse node blocks
    // ------------------------------------------------------------------
    let mut nodes: BTreeMap<String, NodeState> = BTreeMap::new();

    while pos < lines.len() {
        match &lines[pos].kind {
            SidecarLineKind::Blank | SidecarLineKind::Comment(_) => {
                pos += 1;
            }
            SidecarLineKind::BlockDecl(keyword, node_id) if keyword == "state" => {
                let node_id = node_id.clone();
                let line_num = lines[pos].number;
                pos += 1;

                // Collect fields for this block
                let mut exec_status: Option<ExecutionStatus> = None;
                let mut executed_by: Option<String> = None;
                let mut executed_at: Option<String> = None;
                let mut execution_log: Option<String> = None;
                let mut retry_count: u32 = 0;

                while pos < lines.len() {
                    match &lines[pos].kind {
                        SidecarLineKind::Blank => break,
                        SidecarLineKind::Comment(_) => {
                            pos += 1;
                        }
                        SidecarLineKind::BlockDecl(_, _) => break,
                        SidecarLineKind::Field(key, value) => {
                            let field_line = lines[pos].number;
                            match key.as_str() {
                                "execution_status" => match ExecutionStatus::from_str(value) {
                                    Ok(s) => exec_status = Some(s),
                                    Err(_) => {
                                        errors.push(AgmError::new(
                                            ErrorCode::P003,
                                            format!(
                                                "Invalid execution_status value '{}' in node '{}'",
                                                value, node_id
                                            ),
                                            ErrorLocation::new(None, Some(field_line), None),
                                        ));
                                    }
                                },
                                "executed_by" => {
                                    executed_by = if value.is_empty() {
                                        None
                                    } else {
                                        Some(value.clone())
                                    };
                                }
                                "executed_at" => {
                                    executed_at = if value.is_empty() {
                                        None
                                    } else {
                                        Some(value.clone())
                                    };
                                }
                                "execution_log" => {
                                    execution_log = if value.is_empty() {
                                        None
                                    } else {
                                        Some(value.clone())
                                    };
                                }
                                "retry_count" => match value.parse::<u32>() {
                                    Ok(n) => retry_count = n,
                                    Err(_) => {
                                        errors.push(AgmError::new(
                                            ErrorCode::P003,
                                            format!(
                                                "Invalid retry_count value '{}' in node '{}'",
                                                value, node_id
                                            ),
                                            ErrorLocation::new(None, Some(field_line), None),
                                        ));
                                    }
                                },
                                unknown => {
                                    errors.push(AgmError::new(
                                        ErrorCode::P009,
                                        format!(
                                            "Unknown field '{}' in state block '{}'",
                                            unknown, node_id
                                        ),
                                        ErrorLocation::new(None, Some(field_line), None),
                                    ));
                                }
                            }
                            pos += 1;
                        }
                        SidecarLineKind::Header(_, _) | SidecarLineKind::Continuation(_) => {
                            pos += 1;
                        }
                    }
                }

                // execution_status is required
                let final_status = match exec_status {
                    Some(s) => s,
                    None => {
                        errors.push(AgmError::new(
                            ErrorCode::P001,
                            format!("Missing required field 'execution_status' in state block '{node_id}'"),
                            ErrorLocation::new(None, Some(line_num), None),
                        ));
                        ExecutionStatus::Pending // placeholder
                    }
                };

                // Duplicate node ID check
                use std::collections::btree_map::Entry;
                match nodes.entry(node_id.clone()) {
                    Entry::Occupied(_) => {
                        errors.push(AgmError::new(
                            ErrorCode::P006,
                            format!("Duplicate node ID '{node_id}' in state file"),
                            ErrorLocation::new(None, Some(line_num), None),
                        ));
                    }
                    Entry::Vacant(slot) => {
                        slot.insert(NodeState {
                            execution_status: final_status,
                            executed_by,
                            executed_at,
                            execution_log,
                            retry_count,
                        });
                    }
                }
            }
            SidecarLineKind::BlockDecl(keyword, _) => {
                // BlockDecl with unexpected keyword
                errors.push(AgmError::new(
                    ErrorCode::P003,
                    format!(
                        "Unexpected block keyword '{}' in state file (expected 'state')",
                        keyword
                    ),
                    ErrorLocation::new(None, Some(lines[pos].number), None),
                ));
                pos += 1;
            }
            SidecarLineKind::Field(key, _) => {
                // Field outside a block
                errors.push(AgmError::new(
                    ErrorCode::P003,
                    format!("Field '{}' outside of a 'state' block", key),
                    ErrorLocation::new(None, Some(lines[pos].number), None),
                ));
                pos += 1;
            }
            SidecarLineKind::Continuation(_) => {
                pos += 1;
            }
            SidecarLineKind::Header(_, _) => {
                pos += 1;
            }
        }
    }

    // ------------------------------------------------------------------
    // 3. Return
    // ------------------------------------------------------------------
    if errors.iter().any(|e| e.is_error()) {
        Err(errors)
    } else {
        Ok(StateFile {
            format_version: format_version.unwrap_or_default(),
            package: package.unwrap_or_default(),
            version: version.unwrap_or_default(),
            session_id: session_id.unwrap_or_default(),
            started_at: started_at.unwrap_or_default(),
            updated_at: updated_at.unwrap_or_default(),
            nodes,
        })
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ErrorCode;

    fn minimal_state() -> &'static str {
        "# agm.state: 1.0\n\
         # package: test.pkg\n\
         # version: 0.1.0\n\
         # session_id: run-001\n\
         # started_at: 2026-04-08T10:00:00Z\n\
         # updated_at: 2026-04-08T10:00:00Z\n"
    }

    fn full_state() -> &'static str {
        "# agm.state: 1.0\n\
         # package: acme.migration\n\
         # version: 1.0.0\n\
         # session_id: run-2026-04-08-153200\n\
         # started_at: 2026-04-08T15:32:00Z\n\
         # updated_at: 2026-04-08T15:35:00Z\n\
         \n\
         state migration.025.data\n\
         execution_status: ready\n\
         retry_count: 0\n\
         \n\
         state migration.025.schema\n\
         execution_status: completed\n\
         executed_by: shell-agent\n\
         executed_at: 2026-04-08T15:30:00Z\n\
         retry_count: 0\n\
         execution_log: .agm/logs/migration.025.schema.log\n"
    }

    fn errors_contain(errors: &[AgmError], code: ErrorCode) -> bool {
        errors.iter().any(|e| e.code == code)
    }

    // -----------------------------------------------------------------------
    // A: Valid minimal — no nodes
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_minimal_valid_returns_ok() {
        let result = parse_state(minimal_state());
        assert!(result.is_ok(), "expected Ok, got: {:?}", result);
        let sf = result.unwrap();
        assert_eq!(sf.format_version, "1.0");
        assert_eq!(sf.package, "test.pkg");
        assert_eq!(sf.version, "0.1.0");
        assert_eq!(sf.session_id, "run-001");
        assert!(sf.nodes.is_empty());
    }

    // -----------------------------------------------------------------------
    // B: Valid full — with nodes
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_full_valid_returns_nodes() {
        let sf = parse_state(full_state()).unwrap();
        assert_eq!(sf.nodes.len(), 2);
        assert_eq!(
            sf.nodes["migration.025.data"].execution_status,
            ExecutionStatus::Ready
        );
        assert_eq!(
            sf.nodes["migration.025.schema"].execution_status,
            ExecutionStatus::Completed
        );
        assert_eq!(
            sf.nodes["migration.025.schema"].executed_by.as_deref(),
            Some("shell-agent")
        );
        assert_eq!(
            sf.nodes["migration.025.schema"].execution_log.as_deref(),
            Some(".agm/logs/migration.025.schema.log")
        );
    }

    // -----------------------------------------------------------------------
    // C: Missing required header fields
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_missing_agm_state_header_returns_p001() {
        let input = "# package: test.pkg\n\
                     # version: 0.1.0\n\
                     # session_id: run-001\n\
                     # started_at: 2026-04-08T10:00:00Z\n\
                     # updated_at: 2026-04-08T10:00:00Z\n";
        let errors = parse_state(input).unwrap_err();
        assert!(errors_contain(&errors, ErrorCode::P001));
        assert!(
            errors
                .iter()
                .any(|e| e.code == ErrorCode::P001 && e.message.contains("agm.state"))
        );
    }

    #[test]
    fn test_parse_state_missing_package_header_returns_p001() {
        let input = "# agm.state: 1.0\n\
                     # version: 0.1.0\n\
                     # session_id: run-001\n\
                     # started_at: 2026-04-08T10:00:00Z\n\
                     # updated_at: 2026-04-08T10:00:00Z\n";
        let errors = parse_state(input).unwrap_err();
        assert!(
            errors
                .iter()
                .any(|e| e.code == ErrorCode::P001 && e.message.contains("package"))
        );
    }

    #[test]
    fn test_parse_state_missing_session_id_returns_p001() {
        let input = "# agm.state: 1.0\n\
                     # package: test.pkg\n\
                     # version: 0.1.0\n\
                     # started_at: 2026-04-08T10:00:00Z\n\
                     # updated_at: 2026-04-08T10:00:00Z\n";
        let errors = parse_state(input).unwrap_err();
        assert!(
            errors
                .iter()
                .any(|e| e.code == ErrorCode::P001 && e.message.contains("session_id"))
        );
    }

    // -----------------------------------------------------------------------
    // D: Duplicate node ID
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_duplicate_node_id_returns_p006() {
        let input = format!(
            "{}\n\
             state dup.node\n\
             execution_status: pending\n\
             retry_count: 0\n\
             \n\
             state dup.node\n\
             execution_status: ready\n\
             retry_count: 0\n",
            minimal_state()
        );
        let errors = parse_state(&input).unwrap_err();
        assert!(errors_contain(&errors, ErrorCode::P006));
    }

    // -----------------------------------------------------------------------
    // E: Invalid execution_status
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_bad_status_returns_p003() {
        let input = format!(
            "{}\n\
             state bad.node\n\
             execution_status: running\n\
             retry_count: 0\n",
            minimal_state()
        );
        let errors = parse_state(&input).unwrap_err();
        assert!(errors_contain(&errors, ErrorCode::P003));
        assert!(
            errors
                .iter()
                .any(|e| e.code == ErrorCode::P003 && e.message.contains("running"))
        );
    }

    // -----------------------------------------------------------------------
    // F: Unknown field produces P009 warning
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_unknown_field_returns_p009_warning() {
        let input = format!(
            "{}\n\
             state known.node\n\
             execution_status: pending\n\
             retry_count: 0\n\
             mystery_field: some value\n",
            minimal_state()
        );
        // Warnings don't cause Err — file should parse successfully
        let result = parse_state(&input);
        // P009 is a warning — should not block Ok
        assert!(
            result.is_ok(),
            "expected Ok with warnings, got: {:?}",
            result
        );
    }

    // -----------------------------------------------------------------------
    // G: Invalid retry_count
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_bad_retry_count_returns_p003() {
        let input = format!(
            "{}\n\
             state node.one\n\
             execution_status: pending\n\
             retry_count: not-a-number\n",
            minimal_state()
        );
        let errors = parse_state(&input).unwrap_err();
        assert!(errors_contain(&errors, ErrorCode::P003));
    }

    // -----------------------------------------------------------------------
    // H: All execution statuses parsed correctly
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_all_statuses_parsed_correctly() {
        let statuses = [
            ("pending", ExecutionStatus::Pending),
            ("ready", ExecutionStatus::Ready),
            ("in_progress", ExecutionStatus::InProgress),
            ("completed", ExecutionStatus::Completed),
            ("failed", ExecutionStatus::Failed),
            ("blocked", ExecutionStatus::Blocked),
            ("skipped", ExecutionStatus::Skipped),
        ];

        for (status_str, expected) in &statuses {
            let input = format!(
                "{}\n\
                 state test.node\n\
                 execution_status: {}\n\
                 retry_count: 0\n",
                minimal_state(),
                status_str
            );
            let sf =
                parse_state(&input).unwrap_or_else(|_| panic!("failed for status {status_str}"));
            assert_eq!(sf.nodes["test.node"].execution_status, *expected);
        }
    }

    // -----------------------------------------------------------------------
    // I: Comments are ignored
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_comments_are_ignored() {
        let input = "# agm.state: 1.0\n\
                     # package: test.pkg\n\
                     # version: 0.1.0\n\
                     # session_id: run-001\n\
                     # started_at: 2026-04-08T10:00:00Z\n\
                     # updated_at: 2026-04-08T10:00:00Z\n\
                     # This is a comment\n\
                     \n\
                     state n.one\n\
                     # comment inside block\n\
                     execution_status: pending\n\
                     retry_count: 0\n";
        let sf = parse_state(input).unwrap();
        assert_eq!(sf.nodes.len(), 1);
    }

    // -----------------------------------------------------------------------
    // J: Blank lines between blocks
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_blank_lines_between_blocks_ok() {
        let input = format!(
            "{}\n\
             state n.one\n\
             execution_status: pending\n\
             retry_count: 0\n\
             \n\
             \n\
             state n.two\n\
             execution_status: ready\n\
             retry_count: 0\n",
            minimal_state()
        );
        let sf = parse_state(&input).unwrap();
        assert_eq!(sf.nodes.len(), 2);
    }

    // -----------------------------------------------------------------------
    // K: Header values preserved exactly
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_header_timestamps_preserved() {
        let sf = parse_state(full_state()).unwrap();
        assert_eq!(sf.started_at, "2026-04-08T15:32:00Z");
        assert_eq!(sf.updated_at, "2026-04-08T15:35:00Z");
    }

    // -----------------------------------------------------------------------
    // L: Optional fields absent when not specified
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_optional_fields_absent_when_not_specified() {
        let input = format!(
            "{}\n\
             state n.minimal\n\
             execution_status: pending\n\
             retry_count: 0\n",
            minimal_state()
        );
        let sf = parse_state(&input).unwrap();
        let node = &sf.nodes["n.minimal"];
        assert!(node.executed_by.is_none());
        assert!(node.executed_at.is_none());
        assert!(node.execution_log.is_none());
    }

    // -----------------------------------------------------------------------
    // M: Empty input is error (no headers)
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_empty_input_returns_error() {
        let result = parse_state("");
        assert!(result.is_err());
    }

    // -----------------------------------------------------------------------
    // N: retry_count defaults to 0 when absent
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_retry_count_defaults_to_zero() {
        let input = format!(
            "{}\n\
             state n.one\n\
             execution_status: pending\n",
            minimal_state()
        );
        let sf = parse_state(&input).unwrap();
        assert_eq!(sf.nodes["n.one"].retry_count, 0);
    }

    // -----------------------------------------------------------------------
    // O: Multiple missing headers all reported
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_state_multiple_missing_headers_all_reported() {
        // Only agm.state header — missing 5 others
        let input = "# agm.state: 1.0\n";
        let errors = parse_state(input).unwrap_err();
        let p001_count = errors.iter().filter(|e| e.code == ErrorCode::P001).count();
        assert!(
            p001_count >= 5,
            "expected at least 5 P001 errors, got {p001_count}"
        );
    }
}