memfork 0.3.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
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
//! Handing work from one agent to another (DESIGN §6.3).
//!
//! `memfork_handoff` records where things stand when an agent stops;
//! `memfork_resume` gives the next agent — the same client tomorrow, or a
//! different one from a different vendor — one compact briefing to start from.
//! Both work in the session's project namespace.
//!
//! Everything lives in ordinary keys under that namespace, so nothing here is
//! hidden from the raw tools:
//!
//! | key                         | what                                   |
//! |-----------------------------|----------------------------------------|
//! | `<ns>:handoff:<8 digits>`   | one handoff note, numbered from 1      |
//! | `<ns>:decision:<topic>`     | a decision and its reason              |
//! | `<ns>:task:<id>`            | an open task; `"status":"done"` closes it |
//!
//! A briefing is bounded: it is read at the start of every piece of work, so
//! it has to stay cheap however much a project has accumulated. What does not
//! fit is counted, not silently lost, and the caller is told where to look.

use std::sync::Mutex;

use memfork_core::{Db, Entry, Value, WRITTEN_BY};
use serde_json::{json, Map, Value as Json};

use crate::namespace;

/// Most bytes of JSON a briefing may take.
pub const MAX_BRIEFING_BYTES: usize = 6 * 1024;

/// Longest single piece of text in a briefing, in characters.
pub const MAX_TEXT_CHARS: usize = 300;

/// How many recent decisions a briefing includes at most.
pub const MAX_DECISIONS: usize = 10;

/// How many open tasks a briefing includes at most.
pub const MAX_TASKS: usize = 20;

/// How many items of each list in a handoff a briefing includes at most.
pub const MAX_LIST_ITEMS: usize = 10;

/// Handoffs keep the eviction policy's attention: the latest one is the most
/// useful thing a project has.
const HANDOFF_IMPORTANCE: f32 = 0.9;

/// Digits in a handoff number, so key order is number order.
const HANDOFF_DIGITS: usize = 8;

/// Serialises numbering. Every session in the daemon shares one database, and
/// two agents handing off at the same moment must not both take number 7.
static NUMBERING: Mutex<()> = Mutex::new(());

/// A handoff as the tool receives it.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Handoff {
    /// Where things stand, in a sentence or two.
    pub summary: String,
    /// What was finished.
    pub done: Vec<String>,
    /// What should happen next, most important first.
    pub next: Vec<String>,
    /// What is in the way.
    pub blockers: Vec<String>,
    /// What needs an answer from someone.
    pub questions: Vec<String>,
}

impl Handoff {
    fn to_json(&self) -> Json {
        json!({
            "summary": self.summary,
            "done": self.done,
            "next": self.next,
            "blockers": self.blockers,
            "questions": self.questions,
        })
    }
}

/// What writing a handoff produced.
#[derive(Debug, Clone)]
pub struct Written {
    /// The key it was stored under.
    pub key: String,
    /// Its number in the namespace, from 1.
    pub number: u64,
    /// The commit that stored it.
    pub commit: memfork_core::CommitId,
}

/// Store a handoff as the next one in `ns`.
pub fn write(
    db: &Db,
    branch: &str,
    ns: &str,
    note: &Handoff,
    written_by: Option<&str>,
) -> Result<Written, memfork_core::Error> {
    let _numbering = NUMBERING.lock().unwrap_or_else(|e| e.into_inner());
    let prefix = namespace::prefix(ns, "handoff");
    let number = numbered(
        db.list(branch, &prefix, None)?
            .iter()
            .map(|(k, _)| k.as_str()),
        &prefix,
    )
    .map(|(n, _)| n)
    .max()
    .unwrap_or(0)
        + 1;
    let key = format!("{prefix}{number:0width$}", width = HANDOFF_DIGITS);
    let mut value = Value::new(note.to_json().to_string()).with_importance(HANDOFF_IMPORTANCE);
    if let Some(by) = written_by {
        value = value.with_meta(WRITTEN_BY, by);
    }
    let commit = db.put(branch, &key, value)?;
    Ok(Written {
        key,
        number,
        commit,
    })
}

/// Handoff keys under `prefix`, with their numbers. Anything under the prefix
/// that is not a number — written by hand with the raw tools — is ignored
/// rather than trusted.
fn numbered<'a>(
    keys: impl Iterator<Item = &'a str> + 'a,
    prefix: &'a str,
) -> impl Iterator<Item = (u64, &'a str)> + 'a {
    keys.filter_map(move |k| {
        let rest = k.strip_prefix(prefix)?;
        (!rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))
            .then(|| rest.parse::<u64>().ok().map(|n| (n, k)))
            .flatten()
    })
}

/// What a caller may ask of a briefing.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Ask {
    /// What the caller is about to do, to rank what is most relevant to it.
    pub task: Option<String>,
    /// Most bytes of JSON the briefing may take; [`MAX_BRIEFING_BYTES`] if
    /// unset, and never below [`MIN_BUDGET`] or above [`MAX_BUDGET`].
    pub budget: Option<usize>,
    /// The asking session's current branch, which every tool result carries.
    /// Given here so the briefing counts it against the budget.
    pub current_branch: Option<String>,
    /// The head the asking client last saw on this branch, and its number,
    /// for what has changed since.
    pub since: Option<(String, u64)>,
    /// Only what has changed since, when there is a record to go by.
    pub since_only: bool,
    /// Who is asking, so their own handoffs are not news to them.
    pub me: Option<String>,
}

/// Most flags a briefing shows; the rest are counted.
pub const MAX_BRIEF_FLAGS: usize = 5;

/// Most items in each list of what changed since the asker last looked.
pub const MAX_SINCE_ITEMS: usize = 10;

/// What changed in a project since a client last looked: its header, and
/// lists that can be trimmed to fit a budget.
struct Since {
    header: Map<String, Json>,
    lists: Vec<(&'static str, Vec<Json>)>,
    omitted: std::collections::BTreeMap<&'static str, usize>,
}

impl Since {
    fn unavailable(reason: &str) -> Self {
        let mut header = Map::new();
        header.insert("available".to_owned(), json!(false));
        header.insert("reason".to_owned(), json!(reason));
        Since {
            header,
            lists: Vec::new(),
            omitted: std::collections::BTreeMap::new(),
        }
    }

    fn available(&self) -> bool {
        self.header.get("available") == Some(&json!(true))
    }

    fn render(&self) -> Json {
        let mut out = self.header.clone();
        for (name, items) in &self.lists {
            out.insert((*name).to_owned(), json!(items));
        }
        if self.omitted.values().any(|n| *n > 0) {
            out.insert("omitted".to_owned(), json!(self.omitted));
        }
        Json::Object(out)
    }

    /// Drop the last item of the first list that has one, in the order the
    /// lists matter least: facts, then decisions, tasks, lessons, handoffs.
    fn give_up_one(&mut self) -> bool {
        for wanted in [
            "facts",
            "decisions",
            "tasks",
            "lessons",
            "handoffs_by_others",
        ] {
            if let Some((name, items)) = self.lists.iter_mut().find(|(n, _)| *n == wanted) {
                if items.pop().is_some() {
                    *self.omitted.entry(name).or_insert(0) += 1;
                    return true;
                }
            }
        }
        false
    }
}

/// A task's status and holder, for telling what happened to it.
fn task_state(entry: &Entry) -> (String, Option<String>, Option<String>, String) {
    let v: Json = serde_json::from_slice(&entry.value).unwrap_or(Json::Null);
    let text = |k: &str| v.get(k).and_then(Json::as_str).map(str::to_owned);
    (
        text("status").unwrap_or_else(|| "open".to_owned()),
        text("holder"),
        text("done_by"),
        text("title").unwrap_or_else(|| String::from_utf8_lossy(&entry.value).into_owned()),
    )
}

/// What changed in `ns` on `branch` since `ask.since`, if that commit is
/// still in the branch's history.
fn since_last(
    db: &Db,
    branch: &str,
    ns: &str,
    ask: &Ask,
    shared: &crate::shared::Shared,
    truncated: &mut bool,
) -> Result<Since, memfork_core::Error> {
    let Some((commit, seq)) = &ask.since else {
        return Ok(Since::unavailable(
            "no record of this client on this branch yet; this is the whole briefing",
        ));
    };
    let then = match db.at(branch, *seq) {
        Ok(view) if view.commit_id().to_hex() == *commit => view,
        _ => {
            return Ok(Since::unavailable(
                "the commit this client last saw is no longer in this branch's history; \
                 this is the whole briefing",
            ))
        }
    };
    let head_seq = db.commit(db.head(branch)?)?.seq;
    let prefix = format!("{ns}{}", namespace::SEPARATOR);
    let before: std::collections::BTreeMap<String, std::sync::Arc<Entry>> =
        then.list(&prefix, None).into_iter().collect();
    let now = db.list(branch, &prefix, None)?;
    let changed = |key: &str, entry: &Entry| match before.get(key) {
        None => Some("new"),
        Some(old) if old.value != entry.value || old.meta != entry.meta => Some("changed"),
        Some(_) => None,
    };
    let family = |f: &str| namespace::prefix(ns, f);
    let (decision, lesson, handoff, task) = (
        family("decision"),
        family("lesson"),
        family("handoff"),
        family("task"),
    );
    let mut decisions = Vec::new();
    let mut lessons_new = Vec::new();
    let mut handoffs = Vec::new();
    let mut tasks = Vec::new();
    let mut facts = Vec::new();
    for (key, entry) in &now {
        let change = changed(key, entry);
        let by = entry.meta.get(WRITTEN_BY).cloned();
        if key.starts_with(&decision) {
            if let Some(change) = change {
                decisions.push(json!({
                    "key": key,
                    "change": change,
                    "value": clip(&String::from_utf8_lossy(&entry.value), truncated),
                    "by": by,
                }));
            }
        } else if key.starts_with(&lesson) {
            if change == Some("new") {
                lessons_new.push(crate::lessons::view(key, entry));
            }
        } else if key.starts_with(&handoff) {
            if change == Some("new") && by.is_some() && by != ask.me {
                let note: Json = serde_json::from_slice(&entry.value).unwrap_or(Json::Null);
                let summary = note["summary"].as_str().map_or_else(
                    || String::from_utf8_lossy(&entry.value).into_owned(),
                    str::to_owned,
                );
                handoffs.push(json!({
                    "key": key,
                    "by": by,
                    "summary": clip(&summary, truncated),
                }));
            }
        } else if key.starts_with(&task) {
            let Some(change) = change else { continue };
            let (status, holder, done_by, title) = task_state(entry);
            let old = before.get(key.as_str()).map(|e| task_state(e));
            let what = match (&old, status.as_str()) {
                (None, _) => "added".to_owned(),
                (Some((was, ..)), "done") if was != "done" => {
                    format!("finished by {}", done_by.as_deref().unwrap_or("someone"))
                }
                (Some((_, was_holder, ..)), _) if *was_holder != holder => match &holder {
                    Some(h) => format!("claimed by {h}"),
                    None => "released".to_owned(),
                },
                _ => change.to_owned(),
            };
            tasks.push(json!({
                "id": key.strip_prefix(&task).unwrap_or(key),
                "key": key,
                "title": clip(&title, truncated),
                "change": what,
            }));
        } else if crate::facts::sources_of(&entry.meta).is_some() {
            let mut fact = item_json(key, entry, truncated);
            fact["change"] = json!(change.unwrap_or("unchanged"));
            with_fact_fields(&mut fact, key, entry, &shared.sidecar);
            facts.push((change.is_some(), entry.last_access_seq, fact));
        }
    }
    // Facts: the changed ones first, then the rest, each with its verdict as
    // checked on the way out, so one gone stale since shows as stale.
    facts.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
    let facts: Vec<Json> = facts.into_iter().map(|(_, _, f)| f).collect();

    let mut omitted = std::collections::BTreeMap::new();
    let mut cap = |name: &'static str, mut list: Vec<Json>| {
        let over = list.len().saturating_sub(MAX_SINCE_ITEMS);
        if over > 0 {
            list.truncate(MAX_SINCE_ITEMS);
            omitted.insert(name, over);
        }
        (name, list)
    };
    let lists = vec![
        cap("handoffs_by_others", handoffs),
        cap("decisions", decisions),
        cap("lessons", lessons_new),
        cap("tasks", tasks),
        cap("facts", facts),
    ];
    let mut header = Map::new();
    header.insert("available".to_owned(), json!(true));
    header.insert("since_commit".to_owned(), json!(commit));
    header.insert("commits".to_owned(), json!(head_seq.saturating_sub(*seq)));
    let nothing = lists
        .iter()
        .filter(|(n, _)| *n != "facts")
        .all(|(_, l)| l.is_empty());
    header.insert("nothing_new".to_owned(), json!(nothing));
    Ok(Since {
        header,
        lists,
        omitted,
    })
}

/// The smallest budget a briefing accepts: room for its own frame, a handoff
/// and its next steps once everything else has been left out.
pub const MIN_BUDGET: usize = 1024;

/// What a briefing says about its token figure.
pub const ESTIMATE: &str = "approx_tokens = bytes / 4, rounded up";

/// The largest budget a briefing accepts.
pub const MAX_BUDGET: usize = 64 * 1024;

/// How many recent lessons a briefing includes at most.
pub const MAX_LESSONS: usize = 5;

/// How many facts a briefing includes at most.
pub const MAX_FACTS: usize = 10;

/// Build the briefing for `ns` on `branch`, as it was before briefings could
/// be asked for anything.
pub fn briefing(db: &Db, branch: &str, ns: &str) -> Result<Json, memfork_core::Error> {
    briefing_with(db, branch, ns, &Ask::default(), None)
}

/// The kinds of thing a briefing carries after the handoff, in the order they
/// are kept when room runs out: lessons longest, open tasks shortest.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Kind {
    Task,
    Fact,
    Decision,
    Lesson,
}

/// One candidate for a briefing, with what decides whether it stays.
#[derive(Debug, Clone)]
struct Item {
    kind: Kind,
    json: Json,
    /// Relevance to the caller's task; zero without one.
    score: u64,
    /// Position in its kind's default order: newest first.
    pos: usize,
}

impl Item {
    /// Lower is given up first.
    fn keep_order(&self) -> (u64, Kind, std::cmp::Reverse<usize>) {
        (self.score, self.kind, std::cmp::Reverse(self.pos))
    }
}

/// Build a briefing for `ns` on `branch`, ranked for `ask.task` and within
/// `ask.budget` bytes.
///
/// The latest handoff comes first. Then lessons, decisions, facts and open
/// tasks, each ranked by how well it matches the task (see [`crate::find`])
/// and, without a task or among equals, newest first. When the whole will not
/// fit, the least relevant item goes first, and among equals a task before a
/// fact, a fact before a decision, a decision before a lesson. The same store
/// and the same ask always give the same briefing.
pub fn briefing_with(
    db: &Db,
    branch: &str,
    ns: &str,
    ask: &Ask,
    shared: Option<&crate::shared::Shared>,
) -> Result<Json, memfork_core::Error> {
    let budget = ask
        .budget
        .unwrap_or(MAX_BRIEFING_BYTES)
        .clamp(MIN_BUDGET, MAX_BUDGET);
    let handoff_prefix = namespace::prefix(ns, "handoff");
    let handoffs = db.list(branch, &handoff_prefix, None)?;
    let latest = numbered(handoffs.iter().map(|(k, _)| k.as_str()), &handoff_prefix)
        .max_by_key(|(n, _)| *n)
        .and_then(|(n, key)| {
            handoffs
                .iter()
                .find(|(k, _)| k == key)
                .map(|(k, e)| (n, k.clone(), e.clone()))
        });
    let handoff_count = numbered(handoffs.iter().map(|(k, _)| k.as_str()), &handoff_prefix).count();

    let newest_first = |mut entries: Vec<(String, std::sync::Arc<Entry>)>| {
        // Newest write first; key order breaks ties, so the same store always
        // gives the same briefing.
        entries.sort_by(|(ka, a), (kb, b)| {
            b.last_access_seq
                .cmp(&a.last_access_seq)
                .then_with(|| ka.cmp(kb))
        });
        entries
    };
    let decisions = newest_first(db.list(branch, &namespace::prefix(ns, "decision"), None)?);
    let mut lessons = db.list(branch, &namespace::prefix(ns, "lesson"), None)?;
    lessons.reverse();
    let task_prefix = namespace::prefix(ns, "task");
    let tasks: Vec<_> = db
        .list(branch, &task_prefix, None)?
        .into_iter()
        .filter(|(k, e)| match shared {
            Some(s) => s.board.view(k, e, &task_prefix)["status"] != "done",
            None => !is_done(e),
        })
        .collect();
    // Facts outside the families above: a finding stored with its sources.
    let families = ["handoff", "decision", "lesson", "task"].map(|f| namespace::prefix(ns, f));
    let facts = newest_first(
        db.list(branch, &format!("{ns}{}", namespace::SEPARATOR), None)?
            .into_iter()
            .filter(|(k, e)| {
                !families.iter().any(|f| k.starts_with(f.as_str()))
                    && crate::facts::sources_of(&e.meta).is_some()
            })
            .collect(),
    );

    if latest.is_none()
        && decisions.is_empty()
        && tasks.is_empty()
        && lessons.is_empty()
        && facts.is_empty()
    {
        return Ok(json!({
            "namespace": ns,
            "branch": branch,
            "empty": true,
            "hint": format!(
                "Nothing is recorded for `{ns}` yet, so there is no earlier work to \
                 pick up. As you work, store each decision and its reason with \
                 memfork_put under `{ns}:decision:<topic>`, open tasks with \
                 memfork_task, and call memfork_handoff before you stop."
            ),
        }));
    }

    // Relevance to the task, if one was given.
    let scores: std::collections::BTreeMap<String, u64> = match ask
        .task
        .as_deref()
        .filter(|t| !crate::find::words(t).is_empty())
    {
        Some(task) => {
            let texts: Vec<(String, String)> = lessons
                .iter()
                .chain(&decisions)
                .chain(&facts)
                .chain(&tasks)
                .map(|(k, e)| (k.clone(), String::from_utf8_lossy(&e.value).into_owned()))
                .collect();
            let docs: Vec<crate::find::Doc<'_>> = texts
                .iter()
                .map(|(k, t)| crate::find::Doc { key: k, text: t })
                .collect();
            crate::find::rank(&docs, task, usize::MAX)
                .into_iter()
                .map(|h| (h.key, h.score))
                .collect()
        }
        None => std::collections::BTreeMap::new(),
    };

    let mut truncated = false;
    let mut omitted = std::collections::BTreeMap::new();
    let mut items = Vec::new();
    // Ready or blocked, and by what, once the project's tasks depend on
    // one another; a board without a plan is shown as it always was.
    let readiness = shared
        .filter(|s| s.board.uses_plans(db, branch, ns))
        .and_then(|s| s.board.readiness(db, branch, ns).ok());
    let mut take = |kind: Kind,
                    name: &'static str,
                    list: &[(String, std::sync::Arc<Entry>)],
                    cap: usize,
                    truncated: &mut bool| {
        let mut ranked: Vec<(usize, &(String, std::sync::Arc<Entry>))> =
            list.iter().enumerate().collect();
        ranked.sort_by(|(pa, (ka, _)), (pb, (kb, _))| {
            let sa = scores.get(ka).copied().unwrap_or(0);
            let sb = scores.get(kb).copied().unwrap_or(0);
            sb.cmp(&sa).then(pa.cmp(pb))
        });
        for (pos, (key, entry)) in ranked.into_iter().take(cap) {
            let mut json = match kind {
                Kind::Lesson => {
                    let mut view = crate::lessons::view(key, entry);
                    if let Some(text) = view["lesson"].as_str().map(|t| clip(t, truncated)) {
                        view["lesson"] = json!(text);
                    }
                    view
                }
                Kind::Task => match shared {
                    Some(s) => {
                        let mut view = s.board.view(key, entry, &task_prefix);
                        if let Some(readiness) = &readiness {
                            crate::board::annotate(&mut view, readiness);
                        }
                        view
                    }
                    None => item_json(key, entry, truncated),
                },
                Kind::Decision | Kind::Fact => item_json(key, entry, truncated),
            };
            if let Some(s) = shared {
                with_fact_fields(&mut json, key, entry, &s.sidecar);
            }
            items.push(Item {
                kind,
                json,
                score: scores.get(key).copied().unwrap_or(0),
                pos,
            });
        }
        omitted.insert(name, list.len().saturating_sub(cap));
    };
    take(
        Kind::Lesson,
        "lessons",
        &lessons,
        MAX_LESSONS,
        &mut truncated,
    );
    take(
        Kind::Decision,
        "decisions",
        &decisions,
        MAX_DECISIONS,
        &mut truncated,
    );
    take(Kind::Fact, "facts", &facts, MAX_FACTS, &mut truncated);
    take(Kind::Task, "tasks", &tasks, MAX_TASKS, &mut truncated);

    // What changed since this client last looked, for a session asking.
    let since = match shared {
        Some(s) => Some(since_last(db, branch, ns, ask, s, &mut truncated)?),
        None => None,
    };
    let since_only = ask.since_only && since.as_ref().is_some_and(Since::available);
    if since_only {
        items.clear();
        omitted.clear();
    }
    // Things worth a look, for a session asking; never fixed here.
    let mut flags = match shared {
        Some(_) => crate::flags::scan(db, branch, ns)?,
        None => Vec::new(),
    };
    let flags_omitted = flags.len().saturating_sub(MAX_BRIEF_FLAGS);
    flags.truncate(MAX_BRIEF_FLAGS);
    let mut brief = Brief {
        ns: ns.to_owned(),
        branch: branch.to_owned(),
        task: ask.task.clone(),
        current_branch: ask.current_branch.clone(),
        since,
        since_only,
        flags,
        flags_omitted,
        budget,
        handoff: latest
            .as_ref()
            .filter(|_| !since_only)
            .map(|(number, key, entry)| HandoffView::read(*number, key, entry, &mut truncated)),
        earlier_handoffs: handoff_count.saturating_sub(usize::from(latest.is_some())),
        items,
        omitted,
        truncated,
    };

    // Over budget: give things up one at a time, least useful to the next
    // agent first, until it fits. The size is measured with the budget's own
    // figures at their largest, so filling them in cannot push it over, and
    // with every fact as large as checking it can make it.
    while measure(&brief.render(budget)) > budget && brief.give_up_one() {}
    let mut out = brief.render(budget);
    restate_size(&mut out);
    Ok(out)
}

/// The size a briefing may reach on its way to the agent: as built, or once
/// whoever holds the files has turned each fact's `recorded` hashes into a
/// verdict, whichever is larger.
fn measure(brief: &Json) -> usize {
    fn worst(value: &mut Json) {
        match value {
            Json::Object(map) => {
                if map.contains_key("recorded") {
                    map.remove("recorded");
                    map.insert("fact".to_owned(), json!("unverified"));
                    let sources = map.get("sources").cloned().unwrap_or(Json::Null);
                    map.insert("stale_sources".to_owned(), sources);
                }
                map.values_mut().for_each(worst);
            }
            Json::Array(items) => items.iter_mut().for_each(worst),
            _ => {}
        }
    }
    let mut checked = brief.clone();
    worst(&mut checked);
    brief.to_string().len().max(checked.to_string().len())
}

/// Set a briefing's `budget.bytes` and `approx_tokens` to its size as it now
/// stands. Called after anything changes it, such as checking its facts;
/// anything else is left alone.
pub fn restate_size(json: &mut Json) {
    let is_briefing = json
        .get("budget")
        .and_then(|b| b.get("limit_bytes"))
        .is_some();
    if !is_briefing {
        return;
    }
    // Writing the figures can change their own width; a few rounds settle it.
    for _ in 0..4 {
        let size = json.to_string().len();
        if json["budget"]["bytes"] == json!(size) {
            return;
        }
        json["budget"]["bytes"] = json!(size);
        json["budget"]["approx_tokens"] = json!(size.div_ceil(4));
    }
}

/// Add a fact's sources, and the hashes they were recorded with, to its
/// entry in an answer. Whoever holds the files — a proxy, an `--ephemeral`
/// server, the command line — turns `recorded` into fresh or stale.
pub fn with_fact_fields(
    json: &mut Json,
    key: &str,
    entry: &Entry,
    sidecar: &crate::sidecar::Sidecar,
) {
    let Some(sources) = crate::facts::sources_of(&entry.meta) else {
        return;
    };
    let id = crate::facts::record_id(key, &entry.value, &sources);
    let recorded = sidecar.fact(&id).map_or(Json::Null, |h| json!(h));
    if let Json::Object(map) = json {
        map.insert("sources".to_owned(), json!(sources));
        map.insert("recorded".to_owned(), recorded);
    }
}

/// A briefing being assembled, kept in parts so it can be trimmed to fit.
struct Brief {
    ns: String,
    branch: String,
    task: Option<String>,
    current_branch: Option<String>,
    since: Option<Since>,
    since_only: bool,
    /// Duplicates and contradictions worth a look, and how many more.
    flags: Vec<Json>,
    flags_omitted: usize,
    budget: usize,
    handoff: Option<HandoffView>,
    earlier_handoffs: usize,
    items: Vec<Item>,
    omitted: std::collections::BTreeMap<&'static str, usize>,
    truncated: bool,
}

impl Brief {
    /// Drop the least useful remaining item. `false` when nothing is left to
    /// drop.
    fn give_up_one(&mut self) -> bool {
        self.truncated = true;
        if let Some(h) = &mut self.handoff {
            for list in [&mut h.done, &mut h.questions] {
                if list.items.pop().is_some() {
                    list.omitted += 1;
                    return true;
                }
            }
        }
        if let Some(weakest) = self
            .items
            .iter()
            .enumerate()
            .min_by_key(|(_, item)| item.keep_order())
            .map(|(i, _)| i)
        {
            let item = self.items.remove(weakest);
            let name = match item.kind {
                Kind::Lesson => "lessons",
                Kind::Decision => "decisions",
                Kind::Fact => "facts",
                Kind::Task => "tasks",
            };
            *self.omitted.entry(name).or_insert(0) += 1;
            return true;
        }
        if self.flags.pop().is_some() {
            self.flags_omitted += 1;
            return true;
        }
        if self.since.as_mut().is_some_and(Since::give_up_one) {
            return true;
        }
        if let Some(h) = &mut self.handoff {
            for list in [&mut h.blockers, &mut h.next] {
                if list.items.pop().is_some() {
                    list.omitted += 1;
                    return true;
                }
            }
        }
        // Last of all, the long free text: the caller's own task, which it
        // knows, then the handoff's summary, a half at a time.
        if self.task.take().is_some() {
            return true;
        }
        if let Some(summary) = self.handoff.as_mut().and_then(|h| h.summary.as_mut()) {
            let chars = summary.chars().count();
            if chars > 1 {
                let mut cut: String = summary.chars().take(chars / 2).collect();
                cut.push('…');
                *summary = cut;
                return true;
            }
        }
        false
    }

    fn of(&self, kind: Kind) -> Vec<Json> {
        let mut chosen: Vec<&Item> = self.items.iter().filter(|i| i.kind == kind).collect();
        chosen.sort_by(|a, b| b.score.cmp(&a.score).then(a.pos.cmp(&b.pos)));
        chosen.into_iter().map(|i| i.json.clone()).collect()
    }

    fn render(&self, bytes: usize) -> Json {
        let ns = &self.ns;
        let mut map = Map::new();
        map.insert("namespace".to_owned(), json!(ns));
        map.insert("branch".to_owned(), json!(self.branch));
        map.insert("empty".to_owned(), json!(false));
        if let Some(task) = &self.task {
            map.insert("task".to_owned(), json!(task));
        }
        if let Some(since) = &self.since {
            map.insert("since_last".to_owned(), since.render());
        }
        let left_out: usize = self.omitted.values().sum();
        if self.since_only {
            map.insert(
                "hint".to_owned(),
                json!(
                    "Only what changed since you last looked; call memfork_resume without \
                       since_last_only for the whole briefing."
                ),
            );
        } else {
            self.render_whole(&mut map, left_out);
        }
        if !self.flags.is_empty() || self.flags_omitted > 0 {
            map.insert(
                "flags".to_owned(),
                json!({
                    "items": self.flags,
                    "omitted": self.flags_omitted,
                    "hint": "Worth a look, and never fixed by MemFork: `memfork flags` lists them all.",
                }),
            );
        }
        let since_cut = self
            .since
            .as_ref()
            .is_some_and(|s| s.omitted.values().any(|n| *n > 0));
        let handoff_cut = self.handoff.as_ref().is_some_and(HandoffView::cut);
        map.insert(
            "truncated".to_owned(),
            json!(self.truncated || handoff_cut || since_cut || left_out > 0),
        );
        map.insert(
            "budget".to_owned(),
            json!({
                "limit_bytes": self.budget,
                "bytes": bytes,
                "approx_tokens": bytes.div_ceil(4),
                "estimate": ESTIMATE,
            }),
        );
        if let Some(branch) = &self.current_branch {
            map.insert("current_branch".to_owned(), json!(branch));
        }
        Json::Object(map)
    }

    /// The whole briefing's sections, when it is not only what changed.
    fn render_whole(&self, map: &mut Map<String, Json>, left_out: usize) {
        let ns = &self.ns;
        map.insert(
            "latest_handoff".to_owned(),
            self.handoff
                .as_ref()
                .map_or(Json::Null, HandoffView::render),
        );
        map.insert("earlier_handoffs".to_owned(), json!(self.earlier_handoffs));
        map.insert("lessons".to_owned(), json!(self.of(Kind::Lesson)));
        map.insert(
            "recent_decisions".to_owned(),
            json!(self.of(Kind::Decision)),
        );
        map.insert("facts".to_owned(), json!(self.of(Kind::Fact)));
        map.insert("open_tasks".to_owned(), json!(self.of(Kind::Task)));
        if left_out > 0 {
            let mut omitted = Map::new();
            for (name, count) in &self.omitted {
                omitted.insert((*name).to_owned(), json!(count));
            }
            omitted.insert(
                "hint".to_owned(),
                json!(format!(
                    "memfork_search with text, or memfork_list with a prefix such \
                     as `{ns}:decision:`, shows the rest."
                )),
            );
            map.insert("omitted".to_owned(), Json::Object(omitted));
        }
    }
}

/// One list from a handoff, and how many of its items did not fit.
#[derive(Default)]
struct Items {
    items: Vec<String>,
    omitted: usize,
}

/// The latest handoff, as a briefing shows it.
struct HandoffView {
    key: String,
    number: u64,
    by: Option<String>,
    summary: Option<String>,
    next: Items,
    blockers: Items,
    questions: Items,
    done: Items,
}

impl HandoffView {
    fn read(number: u64, key: &str, entry: &Entry, truncated: &mut bool) -> Self {
        let raw = String::from_utf8_lossy(&entry.value);
        let parsed: Json = serde_json::from_str(&raw).unwrap_or(Json::Null);
        let list = |field: &str, truncated: &mut bool| -> Items {
            let all: Vec<&str> = parsed
                .get(field)
                .and_then(Json::as_array)
                .map(|a| a.iter().filter_map(Json::as_str).collect())
                .unwrap_or_default();
            Items {
                items: all
                    .iter()
                    .take(MAX_LIST_ITEMS)
                    .map(|s| clip(s, truncated))
                    .collect(),
                omitted: all.len().saturating_sub(MAX_LIST_ITEMS),
            }
        };
        let (summary, next, blockers, questions, done) = if parsed.is_object() {
            (
                parsed
                    .get("summary")
                    .and_then(Json::as_str)
                    .map(|s| clip(s, truncated)),
                list("next", truncated),
                list("blockers", truncated),
                list("questions", truncated),
                list("done", truncated),
            )
        } else {
            // Written by hand under a handoff key, not by memfork_handoff:
            // show it as text rather than pretend it has the structure.
            (
                Some(clip(&raw, truncated)),
                Items::default(),
                Items::default(),
                Items::default(),
                Items::default(),
            )
        };
        HandoffView {
            key: key.to_owned(),
            number,
            by: entry.meta.get(WRITTEN_BY).cloned(),
            summary,
            next,
            blockers,
            questions,
            done,
        }
    }

    /// Whether any list lost items.
    fn cut(&self) -> bool {
        [&self.next, &self.blockers, &self.questions, &self.done]
            .iter()
            .any(|l| l.omitted > 0)
    }

    fn render(&self) -> Json {
        let mut map = Map::new();
        map.insert("key".to_owned(), json!(self.key));
        map.insert("number".to_owned(), json!(self.number));
        map.insert("by".to_owned(), json!(self.by));
        map.insert("summary".to_owned(), json!(self.summary));
        let mut omitted = Map::new();
        for (name, list) in [
            ("next", &self.next),
            ("blockers", &self.blockers),
            ("questions", &self.questions),
            ("done", &self.done),
        ] {
            map.insert(name.to_owned(), json!(list.items));
            if list.omitted > 0 {
                omitted.insert(name.to_owned(), json!(list.omitted));
            }
        }
        if !omitted.is_empty() {
            // Counted, so the reader knows there was more; the full note is
            // under `key`, for memfork_get.
            map.insert("omitted_items".to_owned(), Json::Object(omitted));
        }
        Json::Object(map)
    }
}

fn item_json(key: &str, entry: &Entry, truncated: &mut bool) -> Json {
    json!({
        "key": key,
        "value": clip(&String::from_utf8_lossy(&entry.value), truncated),
        "by": entry.meta.get(WRITTEN_BY),
    })
}

/// A task is closed when its value is a JSON object whose `status` is `done`.
/// Anything else — plain text included — is open.
fn is_done(entry: &Entry) -> bool {
    serde_json::from_slice::<Json>(&entry.value)
        .ok()
        .and_then(|v| {
            v.get("status")
                .and_then(Json::as_str)
                .map(|s| s.eq_ignore_ascii_case("done"))
        })
        .unwrap_or(false)
}

/// Cut text to [`MAX_TEXT_CHARS`] characters, marking that it was cut.
fn clip(s: &str, truncated: &mut bool) -> String {
    if s.chars().count() <= MAX_TEXT_CHARS {
        return s.to_owned();
    }
    *truncated = true;
    let mut out: String = s.chars().take(MAX_TEXT_CHARS - 1).collect();
    out.push('…');
    out
}

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

    fn note(summary: &str) -> Handoff {
        Handoff {
            summary: summary.to_owned(),
            done: vec!["one".to_owned()],
            next: vec!["two".to_owned()],
            ..Handoff::default()
        }
    }

    #[test]
    fn an_empty_project_says_so_and_how_to_start() {
        let db = Db::new();
        let b = briefing(&db, "main", "shop").unwrap();
        assert_eq!(b["empty"], true);
        let hint = b["hint"].as_str().unwrap();
        assert!(hint.contains("shop:decision:"), "{hint}");
        assert!(hint.contains("memfork_handoff"), "{hint}");
    }

    #[test]
    fn handoffs_are_numbered_and_the_newest_wins() {
        let db = Db::new();
        let first = write(&db, "main", "shop", &note("first"), Some("a")).unwrap();
        let second = write(&db, "main", "shop", &note("second"), Some("b")).unwrap();
        assert_eq!(first.key, "shop:handoff:00000001");
        assert_eq!(second.number, 2);

        let b = briefing(&db, "main", "shop").unwrap();
        assert_eq!(b["latest_handoff"]["summary"], "second");
        assert_eq!(b["latest_handoff"]["by"], "b");
        assert_eq!(b["earlier_handoffs"], 1);
        // The first is still there, as history.
        assert!(db.get("main", &first.key).unwrap().is_some());
    }

    #[test]
    fn namespaces_do_not_see_each_other() {
        let db = Db::new();
        write(&db, "main", "shop", &note("shop work"), None).unwrap();
        db.put("main", "shop:decision:db", Value::new("postgres"))
            .unwrap();
        assert_eq!(briefing(&db, "main", "blog").unwrap()["empty"], true);
        // Nor does a namespace that is a prefix of another's name.
        db.put("main", "shopfront:decision:x", Value::new("y"))
            .unwrap();
        let b = briefing(&db, "main", "shop").unwrap();
        assert_eq!(b["recent_decisions"].as_array().unwrap().len(), 1);
    }

    #[test]
    fn decisions_are_newest_first_with_key_order_breaking_ties() {
        let db = Db::new();
        db.put("main", "p:decision:b", Value::new("1")).unwrap();
        db.put("main", "p:decision:a", Value::new("2")).unwrap();
        memfork_core::with_txn(&db, "main", "two at once", 1, |t| {
            t.put("p:decision:z", Value::new("3"))?;
            t.put("p:decision:y", Value::new("4"))?;
            Ok(())
        })
        .unwrap();
        let b = briefing(&db, "main", "p").unwrap();
        let keys: Vec<&str> = b["recent_decisions"]
            .as_array()
            .unwrap()
            .iter()
            .map(|d| d["key"].as_str().unwrap())
            .collect();
        assert_eq!(
            keys,
            [
                "p:decision:y",
                "p:decision:z",
                "p:decision:a",
                "p:decision:b"
            ]
        );
    }

    #[test]
    fn done_tasks_are_left_out() {
        let db = Db::new();
        db.put("main", "p:task:1", Value::new("plain text is open"))
            .unwrap();
        db.put("main", "p:task:2", Value::new(r#"{"status":"done"}"#))
            .unwrap();
        db.put(
            "main",
            "p:task:3",
            Value::new(r#"{"status":"open","what":"x"}"#),
        )
        .unwrap();
        let b = briefing(&db, "main", "p").unwrap();
        let keys: Vec<&str> = b["open_tasks"]
            .as_array()
            .unwrap()
            .iter()
            .map(|d| d["key"].as_str().unwrap())
            .collect();
        assert_eq!(keys, ["p:task:1", "p:task:3"]);
    }

    #[test]
    fn a_briefing_stays_small_however_much_is_stored() {
        let db = Db::new();
        let long = "x".repeat(5_000);
        let big = Handoff {
            summary: long.clone(),
            done: vec![long.clone(); 50],
            next: vec![long.clone(); 50],
            blockers: vec![long.clone(); 50],
            questions: vec![long.clone(); 50],
        };
        write(&db, "main", "p", &big, None).unwrap();
        for i in 0..200 {
            db.put(
                "main",
                &format!("p:decision:{i:03}"),
                Value::new(long.clone()),
            )
            .unwrap();
            db.put("main", &format!("p:task:{i:03}"), Value::new(long.clone()))
                .unwrap();
        }
        let b = briefing(&db, "main", "p").unwrap();
        assert!(
            b.to_string().len() <= MAX_BRIEFING_BYTES,
            "{}",
            b.to_string().len()
        );
        assert_eq!(b["truncated"], true);
        assert!(b["omitted"]["decisions"].as_u64().unwrap() >= 190);
        assert!(b["omitted"]["hint"]
            .as_str()
            .unwrap()
            .contains("p:decision:"));
        // What was done went first; what comes next survived.
        let handoff = &b["latest_handoff"];
        assert!(!handoff["next"].as_array().unwrap().is_empty(), "{handoff}");
        assert!(handoff["done"].as_array().unwrap().is_empty(), "{handoff}");
        assert!(handoff["omitted_items"]["done"].as_u64().unwrap() >= 10);
    }

    #[test]
    fn the_same_store_gives_the_same_briefing() {
        let build = || {
            let db = Db::new();
            write(&db, "main", "p", &note("n"), Some("a")).unwrap();
            for i in 0..30 {
                db.put(
                    "main",
                    &format!("p:decision:{i}"),
                    Value::new(format!("{i}")),
                )
                .unwrap();
            }
            briefing(&db, "main", "p").unwrap().to_string()
        };
        assert_eq!(build(), build());
    }

    #[test]
    fn a_hand_written_handoff_key_is_shown_as_text() {
        let db = Db::new();
        db.put("main", "p:handoff:00000001", Value::new("just words"))
            .unwrap();
        db.put(
            "main",
            "p:handoff:notes",
            Value::new("not numbered, ignored"),
        )
        .unwrap();
        let b = briefing(&db, "main", "p").unwrap();
        assert_eq!(b["latest_handoff"]["summary"], "just words");
        assert_eq!(b["earlier_handoffs"], 0);
        let next = write(&db, "main", "p", &note("n"), None).unwrap();
        assert_eq!(next.number, 2);
    }
}