use std::sync::Mutex;
use memfork_core::{Db, Entry, Value, WRITTEN_BY};
use serde_json::{json, Map, Value as Json};
use crate::namespace;
pub const MAX_BRIEFING_BYTES: usize = 6 * 1024;
pub const MAX_TEXT_CHARS: usize = 300;
pub const MAX_DECISIONS: usize = 10;
pub const MAX_TASKS: usize = 20;
pub const MAX_LIST_ITEMS: usize = 10;
const HANDOFF_IMPORTANCE: f32 = 0.9;
const HANDOFF_DIGITS: usize = 8;
static NUMBERING: Mutex<()> = Mutex::new(());
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Handoff {
pub summary: String,
pub done: Vec<String>,
pub next: Vec<String>,
pub blockers: Vec<String>,
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,
})
}
}
#[derive(Debug, Clone)]
pub struct Written {
pub key: String,
pub number: u64,
pub commit: memfork_core::CommitId,
}
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,
})
}
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()
})
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Ask {
pub task: Option<String>,
pub budget: Option<usize>,
pub current_branch: Option<String>,
pub since: Option<(String, u64)>,
pub since_only: bool,
pub me: Option<String>,
}
pub const MAX_BRIEF_FLAGS: usize = 5;
pub const MAX_SINCE_ITEMS: usize = 10;
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)
}
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
}
}
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()),
)
}
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.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,
})
}
pub const MIN_BUDGET: usize = 1024;
pub const ESTIMATE: &str = "approx_tokens = bytes / 4, rounded up";
pub const MAX_BUDGET: usize = 64 * 1024;
pub const MAX_LESSONS: usize = 5;
pub const MAX_FACTS: usize = 10;
pub fn briefing(db: &Db, branch: &str, ns: &str) -> Result<Json, memfork_core::Error> {
briefing_with(db, branch, ns, &Ask::default(), None)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Kind {
Task,
Fact,
Decision,
Lesson,
}
#[derive(Debug, Clone)]
struct Item {
kind: Kind,
json: Json,
score: u64,
pos: usize,
}
impl Item {
fn keep_order(&self) -> (u64, Kind, std::cmp::Reverse<usize>) {
(self.score, self.kind, std::cmp::Reverse(self.pos))
}
}
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>)>| {
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();
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."
),
}));
}
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();
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);
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();
}
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,
};
while measure(&brief.render(budget)) > budget && brief.give_up_one() {}
let mut out = brief.render(budget);
restate_size(&mut out);
Ok(out)
}
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())
}
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;
}
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));
}
}
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);
}
}
struct Brief {
ns: String,
branch: String,
task: Option<String>,
current_branch: Option<String>,
since: Option<Since>,
since_only: bool,
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 {
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;
}
}
}
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)
}
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));
}
}
}
#[derive(Default)]
struct Items {
items: Vec<String>,
omitted: usize,
}
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 {
(
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,
}
}
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() {
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),
})
}
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)
}
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", ¬e("first"), Some("a")).unwrap();
let second = write(&db, "main", "shop", ¬e("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);
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", ¬e("shop work"), None).unwrap();
db.put("main", "shop:decision:db", Value::new("postgres"))
.unwrap();
assert_eq!(briefing(&db, "main", "blog").unwrap()["empty"], true);
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:"));
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", ¬e("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", ¬e("n"), None).unwrap();
assert_eq!(next.number, 2);
}
}