memfork 0.2.0

Git for agent memory, shared by every AI tool on your machine: fork, merge, rewind and hand off work between agents over MCP.
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
//! `memfork doctor` — what this install is, and what it is talking to.
//!
//! The report answers the questions someone asks when the tools are not
//! showing up: which binary is running, how each client was asked, and whether
//! it says MemFork is registered. It also states plainly that nothing is
//! persisted yet, because "my memory is empty again" is the other question
//! this command exists to answer.
//!
//! Registration comes from [`clients::registration`], which asks a client's
//! own command whenever it has one rather than reading its config file. A
//! client owns its configuration; reading around it is how this command used
//! to report a registered server as missing.

use serde_json::{json, Value as Json};

use crate::clients::{self, Checked, Registration, Scope};
use crate::init;
use crate::launch;
use crate::tools;

/// One client's entry in the report.
#[derive(Debug)]
struct ClientReport {
    id: String,
    display: String,
    docs: String,
    verified: String,
    /// The client's own command, and whether it is on `PATH`.
    cli: Option<(String, bool)>,
    /// Whether MemFork is registered.
    registration: Registration,
    /// How that was established.
    checked: Checked,
    /// Whether the client appears to be installed at all.
    installed: bool,
    /// The user-scope config path, when the registry carries one. `None` for
    /// a client whose user configuration MemFork deliberately knows nothing
    /// about.
    user_path: Option<String>,
    /// The project-scope config path, which MemFork always knows.
    project_path: Option<String>,
}

impl ClientReport {
    /// Whether this client is installed and `memfork init` would help it —
    /// the only case where suggesting it is useful.
    ///
    /// A registration pointing at another MemFork counts. It is the case most
    /// worth catching: everything looks configured, and no tools appear.
    fn needs_init(&self) -> bool {
        self.installed
            && matches!(
                self.registration,
                Registration::No | Registration::Stale { .. }
            )
    }
}

/// What durability means here, said once, in one place.
pub const DURABILITY_NOTE: &str = "\
Memory is written to the data directory below and survives restarts. Several \
clients can share it: the first one that needs the store starts a daemon that \
owns it, and the rest connect to that. The daemon exits once nothing has \
needed it for a while, and `memfork stop` ends it now. A client run with \
--ephemeral keeps nothing and shares nothing.";

/// Build the report.
fn gather(home: Option<&str>) -> Vec<ClientReport> {
    let launch = launch::resolve();
    clients::all()
        .into_iter()
        .map(|c| {
            let cli = c
                .cli
                .as_ref()
                .map(|cli| (cli.binary.clone(), init::which(&cli.binary).is_some()));
            let path_for = |scope| {
                home.and_then(|h| c.file.as_ref().and_then(|f| f.path_here(scope, h)))
                    .map(|p| p.display().to_string())
            };
            let user_path = path_for(Scope::User);
            let project_path = path_for(Scope::Project);

            let (registration, checked) = match home {
                Some(h) => clients::registration(&c, Scope::User, h, &launch),
                None => (
                    Registration::Unknown("no home directory".to_owned()),
                    Checked::Nothing,
                ),
            };

            ClientReport {
                installed: home.is_some_and(|h| init::is_installed(&c, h)),
                id: c.id.clone(),
                display: c.display.clone(),
                docs: c.docs.clone(),
                verified: c.verified.clone(),
                cli,
                registration,
                checked,
                user_path,
                project_path,
            }
        })
        .collect()
}

/// Where data is kept, and whether anything has it open.
#[derive(Debug)]
struct Storage {
    path: Option<std::path::PathBuf>,
    source: Option<crate::persist::Source>,
    /// Why there is no path, when there is none.
    why: Option<String>,
    owner: Option<crate::persist::Endpoint>,
}

impl Storage {
    fn describe_dir(&self) -> String {
        match (&self.path, self.source) {
            (Some(path), Some(source)) => {
                let why = match source {
                    crate::persist::Source::Environment => "from MEMFORK_DATA_DIR",
                    crate::persist::Source::Project => "this project's own",
                    crate::persist::Source::PerUser => "per-user",
                };
                format!("{} ({why})", path.display())
            }
            _ => match &self.why {
                Some(why) => format!("(none: {})", why.lines().next().unwrap_or(why)),
                None => "(cannot be determined)".to_owned(),
            },
        }
    }

    fn describe_lock(&self) -> String {
        match &self.owner {
            Some(owner) => format!("held by process {}", owner.pid),
            None => "free".to_owned(),
        }
    }

    /// What is serving this data directory, if anything.
    fn describe_daemon(&self) -> String {
        match &self.owner {
            None => "not running (one starts when a client needs it)".to_owned(),
            Some(owner) => match owner.port {
                None => format!(
                    "not running; process {} holds the directory without serving",
                    owner.pid
                ),
                Some(port) => {
                    let version = owner.memfork_version.as_deref().unwrap_or("unknown");
                    let mine = if version == crate::VERSION {
                        ""
                    } else {
                        "  <- a different version from this one; run `memfork stop`"
                    };
                    format!(
                        "127.0.0.1:{port}, process {}, version {version}{mine}",
                        owner.pid
                    )
                }
            },
        }
    }

    fn source_name(&self) -> Option<&'static str> {
        self.source.map(|s| match s {
            crate::persist::Source::Environment => "environment",
            crate::persist::Source::Project => "project",
            crate::persist::Source::PerUser => "per-user",
        })
    }
}

fn storage() -> Storage {
    match crate::persist::datadir::here() {
        Ok(dir) => {
            let owner = crate::persist::lock::owner(&dir.path);
            Storage {
                path: Some(dir.path),
                source: Some(dir.source),
                why: None,
                owner,
            }
        }
        Err(why) => Storage {
            path: None,
            source: None,
            why: Some(why.to_string()),
            owner: None,
        },
    }
}

fn describe(checked: &Checked) -> String {
    match checked {
        Checked::Command(cmd) => format!("asked `{cmd}`"),
        Checked::File(path) => format!("read {}", path.display()),
        Checked::Nothing => "not checked".to_owned(),
    }
}

/// The report as text.
pub fn text() -> String {
    let home = clients::home_dir();
    let mut out = String::new();

    out.push_str(&format!("memfork {}\n", env!("CARGO_PKG_VERSION")));
    // The path on its own. Printing the whole command line here made the
    // binary look as though it were called `memfork.exe mcp`.
    let launch = launch::resolve();
    out.push_str(&format!("  binary        {}\n", launch.program.display()));
    // And the command, when the command is more than that path: a wheel
    // installed without a console script is launched as `python -m memfork`,
    // and a client has to be told so. Appending the subcommand is not a
    // difference worth a line of its own.
    if !launch.args.is_empty() {
        out.push_str(&format!(
            "  launches as   {}\n",
            launch.display(clients::SERVER_ARGS)
        ));
    }
    out.push_str(&format!(
        "  home          {}\n",
        home.as_deref().unwrap_or("(not found)")
    ));
    out.push_str(&format!(
        "  engine        memfork-core {}\n",
        memfork_core::VERSION
    ));
    out.push_str(&format!("  mcp tools     {}\n", tools::all().len()));
    let storage = storage();
    out.push_str(&format!("  data dir      {}\n", storage.describe_dir()));
    out.push_str(&format!("  lock          {}\n", storage.describe_lock()));
    out.push_str(&format!("  daemon        {}\n", storage.describe_daemon()));
    out.push('\n');

    out.push_str("Persistence\n");
    for line in wrap(DURABILITY_NOTE, 74) {
        out.push_str(&format!("  {line}\n"));
    }
    out.push('\n');

    let reports = gather(home.as_deref());
    out.push_str("Clients\n");
    for r in &reports {
        let status = match &r.registration {
            Registration::Yes => "registered",
            // Not a detail: a client in this state shows no MemFork tools at
            // all, and calling it "registered" is how somebody spends an hour
            // wondering why.
            Registration::Stale { .. } => "registered, but not to this MemFork",
            Registration::No if r.installed => "not registered",
            Registration::No => "not installed",
            Registration::Unknown(_) => "unknown",
        };
        out.push_str(&format!("  {} ({})  [{status}]\n", r.display, r.id));

        match &r.cli {
            Some((binary, true)) => {
                out.push_str(&format!("    command     {binary} (found on PATH)\n"));
            }
            Some((binary, false)) => {
                out.push_str(&format!("    command     {binary} (not on PATH)\n"));
            }
            None => out.push_str("    command     (this client ships none)\n"),
        }
        out.push_str(&format!("    checked     {}\n", describe(&r.checked)));
        if let Registration::Unknown(why) = &r.registration {
            out.push_str(&format!("    why         {why}\n"));
        }
        if let Registration::Stale { found } = &r.registration {
            out.push_str(&format!(
                "    points at   {}\n",
                found.as_deref().unwrap_or("another MemFork")
            ));
            out.push_str("    fix         run `memfork init` to point it here\n");
        }
        match &r.user_path {
            Some(path) => out.push_str(&format!("    user        {path}\n")),
            None => out.push_str(
                "    user        (kept by the client; MemFork neither reads nor writes it)\n",
            ),
        }
        if let Some(path) = &r.project_path {
            out.push_str(&format!("    project     {path}\n"));
        }
        out.push_str(&format!("    verified    {} — {}\n", r.verified, r.docs));
    }

    // Only suggest `memfork init` when there is something for it to do.
    // Printing it unconditionally told people to fix what was not broken.
    let pending: Vec<&str> = reports
        .iter()
        .filter(|r| r.needs_init())
        .map(|r| r.display.as_str())
        .collect();
    out.push('\n');
    if !pending.is_empty() {
        out.push_str(&format!(
            "Run `memfork init` to register with: {}.\n",
            pending.join(", ")
        ));
    } else if reports.iter().any(|r| r.registration == Registration::Yes) {
        out.push_str("Every detected client has MemFork registered.\n");
    } else {
        out.push_str("No MCP clients were detected here.\n");
    }
    out
}

/// The report as JSON.
pub fn json() -> Json {
    let home = clients::home_dir();
    let reports = gather(home.as_deref());
    json!({
        "version": env!("CARGO_PKG_VERSION"),
        "engine": memfork_core::VERSION,
        "binary": launch::resolve().program.display().to_string(),
        "launch_command": init::command_line(),
        "home": home,
        "mcp_tools": tools::all().len(),
        "data_dir": storage().path.as_ref().map(|p| p.display().to_string()),
        "data_dir_source": storage().source_name(),
        "lock": storage().owner.as_ref().map(|o| json!({ "pid": o.pid, "port": o.port })),
        "daemon": storage().owner.as_ref().and_then(|o| o.port.map(|port| json!({
            "port": port,
            "pid": o.pid,
            "version": o.memfork_version,
            "version_matches": o.memfork_version.as_deref() == Some(crate::VERSION),
        }))),
        "persistence": {
            "enabled": true,
            "note": DURABILITY_NOTE,
        },
        "needs_init": reports.iter().any(ClientReport::needs_init),
        "clients": reports.iter().map(|r| json!({
            "id": r.id,
            "display": r.display,
            "command": r.cli.as_ref().map(|(b, _)| b.clone()),
            "command_on_path": r.cli.as_ref().map(|(_, found)| *found),
            "installed": r.installed,
            "registered": r.registration.as_bool(),
            "points_at": match r.registration.points_at() {
                Some(path) => json!(path),
                None => Json::Null,
            },
            "unknown_because": match &r.registration {
                Registration::Unknown(why) => json!(why),
                _ => Json::Null,
            },
            "checked": match &r.checked {
                Checked::Command(cmd) => json!({ "how": "command", "detail": cmd }),
                Checked::File(path) => {
                    json!({ "how": "file", "detail": path.display().to_string() })
                }
                Checked::Nothing => json!({ "how": "nothing", "detail": Json::Null }),
            },
            "user_config": r.user_path,
            "project_config": r.project_path,
            "verified": r.verified,
            "docs": r.docs,
        })).collect::<Vec<_>>(),
    })
}

/// Wrap text to a width, for the fixed-width report.
fn wrap(text: &str, width: usize) -> Vec<String> {
    let mut lines = Vec::new();
    let mut current = String::new();
    for word in text.split_whitespace() {
        if !current.is_empty() && current.len() + 1 + word.len() > width {
            lines.push(std::mem::take(&mut current));
        }
        if !current.is_empty() {
            current.push(' ');
        }
        current.push_str(word);
    }
    if !current.is_empty() {
        lines.push(current);
    }
    lines
}

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

    #[test]
    fn the_report_says_where_memory_is_kept() {
        // What someone asks this command when their memory seems wrong: where
        // is it, and has something else got hold of it.
        let text = text();
        assert!(text.contains("survives restarts"), "{text}");
        // This paragraph described the earlier one-process-at-a-time behaviour
        // for a whole phase after the daemon replaced it.
        assert!(text.contains("Several clients can share it"), "{text}");
        assert!(
            !text.contains("is refused, and told which process"),
            "the persistence note still describes the behaviour the daemon replaced"
        );
        // The binary is a path. It briefly carried the whole command line,
        // subcommand and all, which read as though the program were named
        // `memfork.exe mcp`.
        let binary_line = text
            .lines()
            .find(|l| l.trim_start().starts_with("binary "))
            .unwrap_or_default();
        assert!(
            !binary_line.trim_end().ends_with(" mcp"),
            "the binary line is a command line, not a path: {binary_line}"
        );
        assert!(
            !text.contains("launches as"),
            "this build is its own binary, so there is nothing extra to say: {text}"
        );

        assert!(text.contains("data dir      "), "{text}");
        assert!(text.contains("lock          "), "{text}");
        assert!(text.contains("daemon        "), "{text}");

        let json = json();
        assert_eq!(json["persistence"]["enabled"], true);
        assert!(json["persistence"]["note"].is_string());
    }

    #[test]
    fn the_report_covers_every_client_in_the_registry() {
        let text = text();
        for client in clients::all() {
            assert!(text.contains(&client.display), "{} is missing", client.id);
            assert!(
                text.contains(&client.docs),
                "{} has no docs link",
                client.id
            );
        }
        assert_eq!(
            json()["clients"].as_array().map(Vec::len),
            Some(clients::all().len())
        );
    }

    #[test]
    fn the_report_states_the_version_and_tool_count() {
        let text = text();
        assert!(text.contains(env!("CARGO_PKG_VERSION")));
        assert!(text.contains(&tools::all().len().to_string()));
    }

    #[test]
    fn the_report_says_how_it_asked() {
        // Whether registration was read off a command or a file is part of the
        // answer: it is what tells someone where to look next.
        let text = text();
        assert!(text.contains("    checked     "), "{text}");
    }

    #[test]
    fn wrapping_never_loses_or_splits_a_word() {
        let words: Vec<&str> = DURABILITY_NOTE.split_whitespace().collect();
        let wrapped = wrap(DURABILITY_NOTE, 40);
        let rejoined: Vec<&str> = wrapped.iter().flat_map(|l| l.split_whitespace()).collect();
        assert_eq!(words, rejoined);
        assert!(wrapped.iter().all(|l| l.len() <= 40 || !l.contains(' ')));
    }
}