formal-ai 0.38.0

Formal symbolic AI proof of concept with OpenAI-compatible APIs
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
//! Full-memory bundle export / import (`formal_ai_bundle` Links Notation).
//!
//! A bundle is the self-contained `.lino` document the browser's
//! **Export memory** topbar button now writes by default — seed files,
//! UI preferences, environment metadata, and the entire append-only
//! `demo_memory` event log in a single file. The CLI mirrors the same
//! defaults (`formal-ai memory export` writes a bundle; `--events-only`
//! opts back into the legacy `demo_memory` shape).

use std::collections::BTreeMap;

use super::{
    escape_value, format_event_into, isoformat_now, parse_links_notation, parse_quoted,
    split_first_token, MemoryEvent, BUNDLE_HEADER, ROOT_HEADER,
};

/// Build a single Links Notation bundle document.
///
/// Contains the static seed plus the dynamic memory log plus arbitrary
/// environment metadata. Mirrors the browser's `FormalAiMemory.exportBundle`
/// so a user can drop the same file into any interface.
#[must_use]
pub fn export_bundle(seed_files: &[(&str, &str)], events: &[MemoryEvent]) -> String {
    let mut out = String::from(BUNDLE_HEADER);
    out.push('\n');
    out.push_str("  exported_at \"");
    out.push_str(&escape_value(&isoformat_now()));
    out.push_str("\"\n");
    if !seed_files.is_empty() {
        out.push_str("  seed_files\n");
        for (name, contents) in seed_files {
            out.push_str("    file \"");
            out.push_str(&escape_value(name));
            out.push_str("\"\n");
            for line in contents.lines() {
                if line.is_empty() {
                    continue;
                }
                out.push_str("      ");
                out.push_str(line);
                out.push('\n');
            }
        }
    }
    out.push_str("  ");
    out.push_str(ROOT_HEADER);
    out.push('\n');
    for event in events {
        // Indent each event one level deeper than the standalone memory
        // export so it nests inside the bundle.
        let mut block = String::new();
        format_event_into(event, &mut block);
        for line in block.lines() {
            if line.is_empty() {
                continue;
            }
            out.push_str("  ");
            out.push_str(line);
            out.push('\n');
        }
    }
    out
}

/// Recover the memory log section from a `formal_ai_bundle` document.
///
/// Returns `None` if the input is not a recognised bundle. Used by
/// `formal-ai bundle import` so a user can drag the web demo's
/// `formal-ai-bundle.lino` into the CLI and get back just the events.
#[must_use]
pub fn extract_memory_from_bundle(text: &str) -> Option<Vec<MemoryEvent>> {
    if !text.trim_start().starts_with(BUNDLE_HEADER) {
        return None;
    }
    let mut inner = String::new();
    let mut inside = false;
    for line in text.lines() {
        let indent = line.chars().take_while(|c| *c == ' ').count();
        let content = &line[indent..];
        if !inside {
            if indent == 2 && content == ROOT_HEADER {
                inside = true;
                inner.push_str(content);
                inner.push('\n');
            }
            continue;
        }
        if indent <= 2 && !content.starts_with("event ") && !content.is_empty() {
            // A sibling section at the same depth as the memory header ends
            // the memory block.
            if indent == 2 {
                break;
            }
        }
        if indent < 2 {
            break;
        }
        // Strip two spaces of bundle indentation so the inner doc looks like
        // a standalone `demo_memory` file the existing parser understands.
        let stripped = line.strip_prefix("  ").unwrap_or(line);
        inner.push_str(stripped);
        inner.push('\n');
    }
    if !inside {
        return None;
    }
    Some(parse_links_notation(&inner))
}

/// Environment metadata embedded at the top of a `formal_ai_bundle` document.
///
/// Mirrors the `info` object passed by the browser to
/// `FormalAiMemory.exportBundle({ info })`: a small free-form record that lets
/// the maintainer reconstruct the runtime context in which the export was
/// produced (app version, URL, user agent, worker state, demo/manual mode).
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct BundleInfo {
    pub exported_at: Option<String>,
    pub version: Option<String>,
    pub url: Option<String>,
    pub user_agent: Option<String>,
    pub worker_state: Option<String>,
    pub mode: Option<String>,
}

/// Structured view of a parsed `formal_ai_bundle` document.
///
/// Returned by [`import_full_memory`]. `seed_files` and `preferences` keep
/// insertion order; `agent_info` is the parsed key/value map recovered from
/// the embedded `data/seed/agent-info.lino` (or `seed/agent-info.lino`) file,
/// when present — it powers [`suggest_migrations`].
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ParsedBundle {
    pub events: Vec<MemoryEvent>,
    pub seed_files: Vec<(String, String)>,
    pub preferences: Vec<(String, String)>,
    pub info: BundleInfo,
    pub agent_info: BTreeMap<String, String>,
}

/// Build the canonical full-memory `.lino` document — the same shape the
/// browser's "Export memory" button now produces.
///
/// Contains, in order: bundle metadata (`exported_at`, `version`, `url`,
/// `user_agent`, `worker_state`, `mode`), every seed file, optional UI
/// preferences, then the entire `demo_memory` event log. A single file is
/// enough to replay the agent's state on any interface.
#[must_use]
pub fn export_full_memory(
    seed_files: &[(&str, &str)],
    events: &[MemoryEvent],
    preferences: &[(&str, &str)],
    info: &BundleInfo,
) -> String {
    let mut out = String::from(BUNDLE_HEADER);
    out.push('\n');
    let exported_at = info.exported_at.clone().unwrap_or_else(isoformat_now);
    out.push_str("  exported_at \"");
    out.push_str(&escape_value(&exported_at));
    out.push_str("\"\n");
    push_optional_info(&mut out, "version", info.version.as_deref());
    push_optional_info(&mut out, "url", info.url.as_deref());
    push_optional_info(&mut out, "user_agent", info.user_agent.as_deref());
    push_optional_info(&mut out, "worker_state", info.worker_state.as_deref());
    push_optional_info(&mut out, "mode", info.mode.as_deref());
    if !seed_files.is_empty() {
        out.push_str("  seed_files\n");
        for (name, contents) in seed_files {
            out.push_str("    file \"");
            out.push_str(&escape_value(name));
            out.push_str("\"\n");
            for line in contents.lines() {
                if line.is_empty() {
                    continue;
                }
                out.push_str("      ");
                out.push_str(line);
                out.push('\n');
            }
        }
    }
    if !preferences.is_empty() {
        out.push_str("  preferences\n");
        for (key, value) in preferences {
            if key.is_empty() {
                continue;
            }
            out.push_str("    ");
            out.push_str(key);
            out.push_str(" \"");
            out.push_str(&escape_value(value));
            out.push_str("\"\n");
        }
    }
    out.push_str("  ");
    out.push_str(ROOT_HEADER);
    out.push('\n');
    for event in events {
        let mut block = String::new();
        format_event_into(event, &mut block);
        for line in block.lines() {
            if line.is_empty() {
                continue;
            }
            out.push_str("  ");
            out.push_str(line);
            out.push('\n');
        }
    }
    out
}

fn push_optional_info(out: &mut String, key: &str, value: Option<&str>) {
    let Some(value) = value else { return };
    if value.is_empty() {
        return;
    }
    out.push_str("  ");
    out.push_str(key);
    out.push_str(" \"");
    out.push_str(&escape_value(value));
    out.push_str("\"\n");
}

/// Parse a bundle into its structured pieces.
///
/// The function is forgiving: unknown subsections are ignored, and a legacy
/// `demo_memory` document returns a `ParsedBundle` whose `events` are
/// populated and every other field empty (matching
/// `FormalAiMemory.importFullMemory` in the browser).
#[must_use]
pub fn import_full_memory(text: &str) -> ParsedBundle {
    let trimmed = text.trim_start();
    if !trimmed.starts_with(BUNDLE_HEADER) {
        return ParsedBundle {
            events: parse_links_notation(text),
            ..ParsedBundle::default()
        };
    }
    parse_bundle_document(text)
}

#[allow(clippy::too_many_lines)]
fn parse_bundle_document(text: &str) -> ParsedBundle {
    let mut bundle = ParsedBundle::default();
    let mut section: Option<&'static str> = None;
    let mut current_seed_file: Option<String> = None;
    let mut current_seed_body = String::new();
    let mut memory_lines: Vec<String> = Vec::new();
    for line in text.lines() {
        if line.is_empty() {
            if section == Some("seed_files") && current_seed_file.is_some() {
                current_seed_body.push('\n');
            }
            continue;
        }
        let indent = line.chars().take_while(|c| *c == ' ').count();
        let content = &line[indent..];
        if indent == 0 {
            // Top-level header; reset any open seed file before continuing.
            if let Some(name) = current_seed_file.take() {
                bundle
                    .seed_files
                    .push((name, std::mem::take(&mut current_seed_body)));
            }
            section = None;
            continue;
        }
        if indent == 2 {
            if let Some(name) = current_seed_file.take() {
                bundle
                    .seed_files
                    .push((name, std::mem::take(&mut current_seed_body)));
            }
            if content == "seed_files" {
                section = Some("seed_files");
                continue;
            }
            if content == "preferences" {
                section = Some("preferences");
                continue;
            }
            if content == ROOT_HEADER {
                section = Some("memory");
                memory_lines.push(String::from(ROOT_HEADER));
                continue;
            }
            // Free-form info field, e.g. `version "0.22.0"`.
            if let Some((key, rest)) = split_first_token(content) {
                if let Some(value) = parse_quoted(rest) {
                    match key {
                        "exported_at" => bundle.info.exported_at = Some(value),
                        "version" => bundle.info.version = Some(value),
                        "url" => bundle.info.url = Some(value),
                        "user_agent" => bundle.info.user_agent = Some(value),
                        "worker_state" => bundle.info.worker_state = Some(value),
                        "mode" => bundle.info.mode = Some(value),
                        _ => {}
                    }
                }
            }
            section = None;
            continue;
        }
        match section {
            Some("seed_files") => {
                if indent == 4 {
                    if let Some(name) = current_seed_file.take() {
                        bundle
                            .seed_files
                            .push((name, std::mem::take(&mut current_seed_body)));
                    }
                    if let Some(rest) = content.strip_prefix("file ") {
                        if let Some(value) = parse_quoted(rest) {
                            current_seed_file = Some(value);
                            current_seed_body = String::new();
                        }
                    }
                } else if current_seed_file.is_some() && indent >= 6 {
                    let body = if line.len() >= 6 { &line[6..] } else { "" };
                    if !current_seed_body.is_empty() {
                        current_seed_body.push('\n');
                    }
                    current_seed_body.push_str(body);
                }
            }
            Some("preferences") if indent == 4 => {
                if let Some((key, rest)) = split_first_token(content) {
                    if let Some(value) = parse_quoted(rest) {
                        bundle.preferences.push((key.to_string(), value));
                    }
                }
            }
            Some("memory") => {
                // Strip the 2 spaces of bundle indentation so the captured
                // block matches the standalone `demo_memory` shape parsed by
                // `parse_links_notation`.
                let stripped = if line.len() >= 2 { &line[2..] } else { line };
                memory_lines.push(stripped.to_string());
            }
            _ => {}
        }
    }
    if let Some(name) = current_seed_file.take() {
        bundle.seed_files.push((name, current_seed_body));
    }
    if !memory_lines.is_empty() {
        bundle.events = parse_links_notation(&memory_lines.join("\n"));
    }
    bundle.agent_info = extract_agent_info(&bundle.seed_files);
    bundle
}

fn extract_agent_info(seed_files: &[(String, String)]) -> BTreeMap<String, String> {
    for (name, contents) in seed_files {
        if name == "data/seed/agent-info.lino" || name == "seed/agent-info.lino" {
            return parse_agent_info(contents);
        }
    }
    BTreeMap::new()
}

fn parse_agent_info(text: &str) -> BTreeMap<String, String> {
    let mut out = BTreeMap::new();
    let mut current_field: Option<String> = None;
    for line in text.lines() {
        let indent = line.chars().take_while(|c| *c == ' ').count();
        let content = &line[indent..];
        if indent == 2 {
            if let Some(rest) = content.strip_prefix("field ") {
                if let Some(value) = parse_quoted(rest) {
                    current_field = Some(value);
                }
            }
        } else if indent == 4 {
            if let Some(rest) = content.strip_prefix("value ") {
                if let Some(value) = parse_quoted(rest) {
                    if let Some(key) = current_field.take() {
                        out.insert(key, value);
                    }
                }
            }
        }
    }
    out
}

/// Suggest data migrations between an imported bundle and the running app.
///
/// The first migration check covers the seed version baked into
/// `data/seed/agent-info.lino` (`field "version"`). When the version moved
/// forward, the returned suggestion tells the user where to look. A legacy
/// `demo_memory`-only import also yields a suggestion explaining that the
/// seed-of-origin is unknown. Returns an empty vector when no migration is
/// needed so the caller can branch on emptiness.
#[must_use]
pub fn suggest_migrations(
    imported: &ParsedBundle,
    current_agent_info: &BTreeMap<String, String>,
) -> Vec<String> {
    let mut out = Vec::new();
    let imported_version = imported
        .agent_info
        .get("version")
        .cloned()
        .or_else(|| imported.info.version.clone());
    let current_version = current_agent_info.get("version").cloned();
    match (imported_version.as_deref(), current_version.as_deref()) {
        (Some(imported_v), Some(current_v)) if imported_v != current_v => {
            out.push(format!(
                "Seed version {imported_v}{current_v}: review the new entries in data/seed/ \
                 (multilingual responses, concepts, tools) — your imported memory was \
                 authored against an older seed.",
            ));
        }
        (Some(imported_v), None) => {
            out.push(format!(
                "Imported bundle was authored against seed version {imported_v} but the \
                 running app does not expose a seed version. Update the app to compare.",
            ));
        }
        _ => {}
    }
    if imported.seed_files.is_empty() && !imported.events.is_empty() {
        out.push(String::from(
            "Imported file is a legacy demo_memory log (no seed). The events were \
             imported, but the seed at the time of capture is unknown — export from \
             this session to upgrade to a full bundle.",
        ));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::super::{export_links_notation, MemoryEvent};
    use super::{
        export_bundle, export_full_memory, extract_memory_from_bundle, import_full_memory,
        suggest_migrations, BundleInfo,
    };
    use std::collections::BTreeMap;

    fn sample_events() -> Vec<MemoryEvent> {
        vec![
            MemoryEvent {
                id: String::from("1"),
                role: Some(String::from("user")),
                content: Some(String::from("Hi")),
                sent_at: Some(String::from("2026-05-15T12:00:00.000Z")),
                ..MemoryEvent::default()
            },
            MemoryEvent {
                id: String::from("2"),
                role: Some(String::from("assistant")),
                intent: Some(String::from("greeting")),
                content: Some(String::from("Hi, how may I help you?")),
                sent_at: Some(String::from("2026-05-15T12:00:01.000Z")),
                ..MemoryEvent::default()
            },
        ]
    }

    #[test]
    fn bundle_export_embeds_seed_and_memory() {
        let seed_files: Vec<(&str, &str)> =
            vec![("data/seed/example.lino", "example\n  key \"v\"")];
        let events = sample_events();
        let bundle = export_bundle(&seed_files, &events);
        assert!(bundle.starts_with("formal_ai_bundle\n"));
        assert!(bundle.contains("seed_files"));
        assert!(bundle.contains("data/seed/example.lino"));
        assert!(bundle.contains("demo_memory"));
        assert!(bundle.contains("Hi, how may I help you?"));
    }

    #[test]
    fn extract_memory_from_bundle_recovers_events() {
        let seed_files: Vec<(&str, &str)> =
            vec![("data/seed/example.lino", "example\n  key \"v\"")];
        let events = sample_events();
        let bundle = export_bundle(&seed_files, &events);
        let recovered = extract_memory_from_bundle(&bundle).expect("recover");
        assert_eq!(recovered, events);
    }

    #[test]
    fn full_memory_round_trip_preserves_seed_preferences_and_events() {
        let seed: Vec<(&str, &str)> = vec![
            (
                "data/seed/agent-info.lino",
                "agent_info\n  field \"version\"\n    value \"0.22.0\"\n",
            ),
            ("data/seed/example.lino", "example\n  key \"v\"\n"),
        ];
        let prefs: Vec<(&str, &str)> = vec![("demoMode", "off"), ("diagnosticsMode", "on")];
        let events = sample_events();
        let info = BundleInfo {
            version: Some(String::from("0.22.0")),
            url: Some(String::from("https://example.test/")),
            user_agent: Some(String::from("playwright/1.0")),
            worker_state: Some(String::from("wasm worker")),
            mode: Some(String::from("manual")),
            ..BundleInfo::default()
        };
        let bundle = export_full_memory(&seed, &events, &prefs, &info);
        assert!(bundle.starts_with("formal_ai_bundle\n"));
        assert!(bundle.contains("version \"0.22.0\""));
        assert!(bundle.contains("user_agent \"playwright/1.0\""));
        assert!(bundle.contains("seed_files"));
        assert!(bundle.contains("data/seed/agent-info.lino"));
        assert!(bundle.contains("preferences"));
        assert!(bundle.contains("demoMode \"off\""));
        assert!(bundle.contains("demo_memory"));
        let parsed = import_full_memory(&bundle);
        assert_eq!(parsed.events, events);
        assert_eq!(parsed.info.version.as_deref(), Some("0.22.0"));
        assert_eq!(parsed.info.mode.as_deref(), Some("manual"));
        assert_eq!(
            parsed.agent_info.get("version").map(String::as_str),
            Some("0.22.0")
        );
        let prefs_map: BTreeMap<String, String> = parsed.preferences.iter().cloned().collect();
        assert_eq!(prefs_map.get("demoMode").map(String::as_str), Some("off"));
        assert_eq!(
            prefs_map.get("diagnosticsMode").map(String::as_str),
            Some("on")
        );
        assert_eq!(parsed.seed_files.len(), 2);
    }

    #[test]
    fn import_full_memory_accepts_legacy_demo_memory() {
        let text = export_links_notation(&sample_events());
        let parsed = import_full_memory(&text);
        assert_eq!(parsed.events, sample_events());
        assert!(parsed.seed_files.is_empty());
        assert!(parsed.preferences.is_empty());
        assert!(parsed.agent_info.is_empty());
    }

    #[test]
    fn suggest_migrations_flags_seed_version_drift() {
        let seed: Vec<(&str, &str)> = vec![(
            "data/seed/agent-info.lino",
            "agent_info\n  field \"version\"\n    value \"0.21.0\"\n",
        )];
        let bundle = export_full_memory(&seed, &sample_events(), &[], &BundleInfo::default());
        let imported = import_full_memory(&bundle);
        let mut current = BTreeMap::new();
        current.insert(String::from("version"), String::from("0.22.0"));
        let suggestions = suggest_migrations(&imported, &current);
        assert_eq!(suggestions.len(), 1);
        assert!(suggestions[0].contains("0.21.0"));
        assert!(suggestions[0].contains("0.22.0"));
    }

    #[test]
    fn suggest_migrations_flags_legacy_only_import() {
        let imported = import_full_memory(&export_links_notation(&sample_events()));
        let mut current = BTreeMap::new();
        current.insert(String::from("version"), String::from("0.22.0"));
        let suggestions = suggest_migrations(&imported, &current);
        assert!(suggestions
            .iter()
            .any(|message| message.contains("legacy demo_memory")));
    }

    #[test]
    fn suggest_migrations_is_quiet_when_versions_match() {
        let seed: Vec<(&str, &str)> = vec![(
            "data/seed/agent-info.lino",
            "agent_info\n  field \"version\"\n    value \"0.22.0\"\n",
        )];
        let bundle = export_full_memory(&seed, &sample_events(), &[], &BundleInfo::default());
        let imported = import_full_memory(&bundle);
        let mut current = BTreeMap::new();
        current.insert(String::from("version"), String::from("0.22.0"));
        assert!(suggest_migrations(&imported, &current).is_empty());
    }
}