1use super::*;
8
9impl Mnemo {
10 #[cfg_attr(not(feature = "dev-hooks"), allow(dead_code))]
17 pub(super) fn put_coordination(
18 &mut self,
19 kind: &str,
20 content: String,
21 metadata: Map<String, Value>,
22 ) -> Result<Ulid> {
23 self.put_coordination_with_id(Ulid::new(), kind, content, metadata)
24 }
25
26 pub(super) fn put_coordination_with_id(
29 &mut self,
30 id: Ulid,
31 kind: &str,
32 content: String,
33 mut metadata: Map<String, Value>,
34 ) -> Result<Ulid> {
35 if self.read_only {
36 return Err(MnemoError::ReadOnly);
37 }
38 if !crate::memory::COORDINATION_KINDS.contains(&kind) {
39 return Err(MnemoError::Invalid(format!(
40 "{kind:?} isn't a coordination kind"
41 )));
42 }
43 metadata.insert(MNEMO_META_KIND.into(), Value::String(kind.to_string()));
44 let mut m = Memory::new(content, MemoryType::Episodic, self.sentinel_vector())
45 .with_scope(Scope::Shared);
46 m.id = id;
47 m.metadata = metadata;
48 self.put(m)
49 }
50}
51
52#[derive(Debug, Clone, PartialEq)]
54pub struct Message {
55 pub id: Ulid,
57 pub to: String,
59 pub from: String,
61 pub subject: String,
63 pub body: String,
65 pub refs: Vec<String>,
67 pub conversation: String,
69 pub hops: u64,
71 pub status: String,
73 pub delivery: String,
75 pub created_at: i64,
77 pub acked_at: Option<i64>,
79}
80
81impl Message {
82 pub fn from_memory(m: &Memory) -> Option<Message> {
84 if m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str)
85 != Some(crate::memory::MNEMO_META_KIND_MESSAGE)
86 {
87 return None;
88 }
89 let s = |k: &str| {
90 m.metadata
91 .get(k)
92 .and_then(Value::as_str)
93 .unwrap_or("")
94 .to_string()
95 };
96 let (subject, body) = match m.content.split_once("\n\n") {
97 Some((a, b)) => (a.to_string(), b.to_string()),
98 None => (m.content.clone(), String::new()),
99 };
100 Some(Message {
101 id: m.id,
102 to: s(MNEMO_META_TO),
103 from: s(MNEMO_META_FROM),
104 subject,
105 body,
106 refs: m
107 .metadata
108 .get(MNEMO_META_REFS)
109 .and_then(Value::as_array)
110 .map(|a| {
111 a.iter()
112 .filter_map(|v| v.as_str().map(str::to_string))
113 .collect()
114 })
115 .unwrap_or_default(),
116 conversation: s(MNEMO_META_CONVERSATION),
117 hops: m
118 .metadata
119 .get(MNEMO_META_HOPS)
120 .and_then(Value::as_u64)
121 .unwrap_or(0),
122 status: s(MNEMO_META_STATUS),
123 delivery: s(MNEMO_META_DELIVERY),
124 created_at: m.created_at,
125 acked_at: m.metadata.get(MNEMO_META_ACKED_AT).and_then(Value::as_i64),
126 })
127 }
128
129 pub fn is_for(&self, agent: Option<&str>, role: Option<&str>) -> bool {
132 if agent.is_some_and(|a| a == self.from) {
133 return false;
134 }
135 self.to == "all"
136 || agent.is_some_and(|a| a == self.to)
137 || role.is_some_and(|r| self.to.strip_prefix("role:") == Some(r))
138 }
139}
140
141fn valid_address(to: &str) -> bool {
143 to == "all"
144 || crate::memory::valid_agent_id(to) && !to.starts_with("role:")
145 || to
146 .strip_prefix("role:")
147 .is_some_and(crate::memory::valid_agent_id)
148}
149
150fn seen_by(m: &Memory) -> Vec<String> {
153 m.metadata
154 .get(crate::memory::MNEMO_META_SEEN_BY)
155 .and_then(Value::as_array)
156 .map(|a| {
157 a.iter()
158 .filter_map(|v| v.as_str().map(str::to_string))
159 .collect()
160 })
161 .unwrap_or_default()
162}
163
164fn add_seen_by(m: &mut Memory, agent: &str) -> bool {
166 let mut v = seen_by(m);
167 if v.iter().any(|a| a == agent) {
168 return false;
169 }
170 v.push(agent.to_string());
171 m.metadata.insert(
172 crate::memory::MNEMO_META_SEEN_BY.into(),
173 Value::Array(v.into_iter().map(Value::String).collect()),
174 );
175 true
176}
177
178impl Mnemo {
179 fn coordination_records(&mut self, kind: &str, locator: Option<&str>) -> Result<Vec<Memory>> {
183 let want = locator.map(|l| locator_hash_of(kind, l));
184 let legacy = self.legacy_coordination_ids()?;
185 let entries: Vec<CatalogEntry> = self
186 .catalog
187 .iter()
188 .filter(|e| !e.deleted)
189 .filter(|e| {
190 legacy.contains(&e.id)
191 || e.v9.is_none_or(|r| {
192 r.kind == ROW_KIND_COORDINATION && want.is_none_or(|h| r.thread_hash == h)
193 })
194 })
195 .cloned()
196 .collect();
197 let mut out = Vec::new();
198 for e in entries {
199 let m = self.read_memory(&e)?;
200 if m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str) != Some(kind) {
201 continue;
202 }
203 if let Some(l) = locator {
204 if locator_of(&m) != Some(l) {
205 continue;
206 }
207 }
208 out.push(m);
209 }
210 Ok(out)
211 }
212
213 fn legacy_coordination_ids(&mut self) -> Result<std::collections::HashSet<u128>> {
219 if let Some(ids) = &self.legacy_coordination {
220 return Ok(ids.clone());
221 }
222 let episodic = super::records::memory_type_code(MemoryType::Episodic);
223 let candidates: Vec<CatalogEntry> = self
224 .catalog
225 .iter()
226 .filter(|e| !e.deleted)
227 .filter(|e| {
228 e.v9.is_some_and(|r| {
229 r.kind == super::records::ROW_KIND_FACT && r.memory_type == episodic
230 })
231 })
232 .cloned()
233 .collect();
234 let mut ids = std::collections::HashSet::new();
235 for e in candidates {
236 if is_coordination(&self.read_memory(&e)?) {
237 ids.insert(e.id);
238 }
239 }
240 self.legacy_coordination = Some(ids.clone());
241 Ok(ids)
242 }
243
244 pub fn mistagged_coordination(&mut self) -> Result<usize> {
248 let ids = self.legacy_coordination_ids()?;
249 Ok(self
250 .catalog
251 .iter()
252 .filter(|e| !e.deleted && ids.contains(&e.id))
253 .filter(|e| {
254 e.v9.is_some_and(|r| r.kind == super::records::ROW_KIND_FACT)
255 })
256 .count())
257 }
258
259 fn messages(&mut self) -> Result<Vec<Memory>> {
261 let mut out = self.coordination_records(crate::memory::MNEMO_META_KIND_MESSAGE, None)?;
262 out.sort_by_key(|m| m.created_at);
265 Ok(out)
266 }
267
268 #[allow(clippy::too_many_arguments)]
280 pub fn post(
281 &mut self,
282 to: &str,
283 subject: &str,
284 body: &str,
285 refs: &[String],
286 conversation: Option<&str>,
287 from: Option<&str>,
288 from_role: Option<&str>,
289 ) -> Result<Message> {
290 if self.read_only {
291 return Err(MnemoError::ReadOnly);
292 }
293 if !valid_address(to) {
294 return Err(MnemoError::Invalid(format!(
295 "{to:?} isn't an address: an agent id, role:<role>, or all"
296 )));
297 }
298 let subject = subject.trim();
299 if subject.is_empty() || subject.contains('\n') {
300 return Err(MnemoError::Invalid(
301 "a message's subject is one line, and not empty".into(),
302 ));
303 }
304 if subject.len() > crate::memory::MESSAGE_SUBJECT_MAX {
305 return Err(MnemoError::Invalid(format!(
306 "a message's subject is at most {} bytes",
307 crate::memory::MESSAGE_SUBJECT_MAX
308 )));
309 }
310 if body.len() > crate::memory::MESSAGE_BODY_MAX {
311 return Err(MnemoError::Invalid(format!(
312 "a message's body is at most {} bytes; put a longer one in a fact and send its id \
313 in refs",
314 crate::memory::MESSAGE_BODY_MAX
315 )));
316 }
317 let from = from
318 .map(str::to_string)
319 .or_else(|| self.author.clone())
320 .unwrap_or_else(|| "anonymous".to_string());
321 let now = memory::now_secs();
322 let earlier: Vec<Message> = self
323 .messages()?
324 .iter()
325 .filter_map(Message::from_memory)
326 .collect();
327 let mut hops = 0u64;
328 if let Some(c) = conversation {
329 if let Some(h) = earlier
330 .iter()
331 .filter(|m| m.conversation == c)
332 .map(|m| m.hops)
333 .max()
334 {
335 hops = h + 1;
336 }
337 }
338 if let Some(h) = earlier
341 .iter()
342 .filter(|m| now - m.created_at <= crate::memory::MESSAGE_PAIR_CARRY_SECS)
343 .filter(|m| (m.from == from && m.to == to) || (m.from == to && m.to == from))
344 .map(|m| m.hops)
345 .max()
346 {
347 hops = hops.max(h + 1);
348 }
349 let id = Ulid::new();
350 let conversation = conversation
351 .map(str::to_string)
352 .unwrap_or_else(|| id.to_string());
353 let mut meta = Map::new();
354 meta.insert(MNEMO_META_TO.into(), Value::String(to.into()));
355 meta.insert(MNEMO_META_FROM.into(), Value::String(from));
356 if let Some(r) = from_role {
357 meta.insert("_mnemo.from_role".into(), Value::String(r.to_string()));
358 }
359 meta.insert(MNEMO_META_CONVERSATION.into(), Value::String(conversation));
360 meta.insert(MNEMO_META_HOPS.into(), Value::from(hops));
361 meta.insert(
362 MNEMO_META_REFS.into(),
363 Value::Array(refs.iter().map(|r| Value::String(r.clone())).collect()),
364 );
365 meta.insert(
366 MNEMO_META_STATUS.into(),
367 Value::String(crate::memory::MESSAGE_UNREAD.into()),
368 );
369 meta.insert(
370 MNEMO_META_DELIVERY.into(),
371 Value::String(crate::memory::delivery::SENT.into()),
372 );
373 let content = if body.is_empty() {
374 subject.to_string()
375 } else {
376 format!("{subject}\n\n{body}")
377 };
378 let id = self.put_coordination_with_id(
379 id,
380 crate::memory::MNEMO_META_KIND_MESSAGE,
381 content,
382 meta,
383 )?;
384 let m = self.get(&id)?;
385 Ok(Message::from_memory(&m).expect("just written"))
386 }
387
388 pub fn inbox(
393 &mut self,
394 agent: Option<&str>,
395 role: Option<&str>,
396 unread_only: bool,
397 ) -> Result<Vec<Message>> {
398 self.inbox_in(
399 agent,
400 role,
401 unread_only,
402 crate::memory::VisibilitySet::DEFAULT,
403 )
404 }
405
406 pub fn inbox_in(
409 &mut self,
410 agent: Option<&str>,
411 role: Option<&str>,
412 unread_only: bool,
413 visibility: crate::memory::VisibilitySet,
414 ) -> Result<Vec<Message>> {
415 Ok(self
416 .messages()?
417 .iter()
418 .filter(|m| visibility.shows(m))
419 .filter_map(Message::from_memory)
420 .filter(|m| m.is_for(agent, role))
421 .filter(|m| !unread_only || m.status == crate::memory::MESSAGE_UNREAD)
422 .collect())
423 }
424
425 pub fn mark_seen(&mut self, ids: &[Ulid]) -> Result<usize> {
428 if self.read_only {
429 return Err(MnemoError::ReadOnly);
430 }
431 let mut changed = 0;
432 for id in ids {
433 let mut m = self.get(id)?;
434 let Some(msg) = Message::from_memory(&m) else {
435 continue;
436 };
437 let mut dirty = false;
438 if msg.delivery == crate::memory::delivery::SENT
439 || msg.delivery == crate::memory::delivery::DELIVERED
440 {
441 m.metadata.insert(
442 MNEMO_META_DELIVERY.into(),
443 Value::String(crate::memory::delivery::SEEN.into()),
444 );
445 dirty = true;
446 }
447 if msg.to == "all" || msg.to.starts_with("role:") {
450 if let Some(a) = self.author.clone() {
451 dirty |= add_seen_by(&mut m, &a);
452 }
453 }
454 if dirty {
455 self.put(m)?;
456 changed += 1;
457 }
458 }
459 Ok(changed)
460 }
461
462 pub fn ack(&mut self, id: &Ulid, note: Option<&str>, by: Option<&str>) -> Result<WriteOutcome> {
467 if self.read_only {
468 return Err(MnemoError::ReadOnly);
469 }
470 let mut m = self.get(id)?;
471 let Some(msg) = Message::from_memory(&m) else {
472 return Err(MnemoError::Invalid(format!("{id} isn't a message")));
473 };
474 if msg.status == crate::memory::MESSAGE_ACKED {
475 return Ok(WriteOutcome::Unchanged);
476 }
477 let now = memory::now_secs();
478 let by = by
479 .map(str::to_string)
480 .or_else(|| self.author.clone())
481 .unwrap_or_else(|| "anonymous".to_string());
482 let mut entry = Map::new();
483 entry.insert("from".into(), Value::String(msg.status.clone()));
484 entry.insert(
485 "to".into(),
486 Value::String(crate::memory::MESSAGE_ACKED.into()),
487 );
488 entry.insert("at".into(), Value::from(now));
489 entry.insert("by".into(), Value::String(by));
490 if let Some(n) = note {
491 entry.insert("note".into(), Value::String(n.to_string()));
492 }
493 let mut history = m
494 .metadata
495 .get(MNEMO_META_STATUS_HISTORY)
496 .and_then(Value::as_array)
497 .cloned()
498 .unwrap_or_default();
499 history.push(Value::Object(entry));
500 m.metadata
501 .insert(MNEMO_META_STATUS_HISTORY.into(), Value::Array(history));
502 m.metadata.insert(
503 MNEMO_META_STATUS.into(),
504 Value::String(crate::memory::MESSAGE_ACKED.into()),
505 );
506 m.metadata.insert(
507 MNEMO_META_DELIVERY.into(),
508 Value::String(crate::memory::delivery::DONE.into()),
509 );
510 m.metadata
511 .insert(MNEMO_META_ACKED_AT.into(), Value::from(now));
512 self.put(m)?;
513 Ok(WriteOutcome::Updated)
514 }
515
516 pub fn prune_messages(&mut self, older_than_secs: i64) -> Result<usize> {
520 if self.read_only {
521 return Err(MnemoError::ReadOnly);
522 }
523 let now = memory::now_secs();
524 let old: Vec<Ulid> = self
525 .messages()?
526 .iter()
527 .filter_map(Message::from_memory)
528 .filter(|m| prunable(m, now, older_than_secs))
529 .map(|m| m.id)
530 .collect();
531 for id in &old {
532 self.delete(id)?;
533 }
534 Ok(old.len())
535 }
536}
537
538fn prunable(m: &Message, now: i64, keep: i64) -> bool {
540 m.status == crate::memory::MESSAGE_ACKED && m.acked_at.is_some_and(|t| now - t > keep)
541}
542
543pub(super) fn compact_drops(m: &Memory, now: i64) -> bool {
546 Message::from_memory(m)
547 .is_some_and(|msg| prunable(&msg, now, crate::memory::MESSAGE_ACKED_KEEP_SECS))
548}
549
550use crate::memory::{
553 CLAIM_LAPSE_GRACE_SECS, CLAIM_TOPIC_MAX, CLAIM_TTL_DEFAULT, CLAIM_TTL_MAX, CLAIM_TTL_MIN,
554 MNEMO_META_AGENT, MNEMO_META_CLAIM_TOKEN, MNEMO_META_DEAD_SEEN_AT, MNEMO_META_EXPIRES_AT,
555 MNEMO_META_HOLDER, MNEMO_META_HOLDER_LOCK, MNEMO_META_KIND_CLAIM, MNEMO_META_KIND_PRESENCE,
556 MNEMO_META_LAST_ACTIVE, MNEMO_META_LEASE, MNEMO_META_PRESENCE_LOCK, MNEMO_META_TOOL,
557 MNEMO_META_TOPIC, PRESENCE_EVERY_SECS,
558};
559
560fn locator_of(m: &Memory) -> Option<&str> {
562 let key = match m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str)? {
563 MNEMO_META_KIND_CLAIM => MNEMO_META_TOPIC,
564 MNEMO_META_KIND_PRESENCE => MNEMO_META_AGENT,
565 crate::memory::MNEMO_META_KIND_TASK => crate::memory::MNEMO_META_SLUG,
566 _ => return None,
567 };
568 m.metadata.get(key).and_then(Value::as_str)
569}
570
571fn locator_hash_of(kind: &str, locator: &str) -> u32 {
572 super::records::fnv1a32(&[b"_mnemo.coordination", kind.as_bytes(), locator.as_bytes()])
573}
574
575pub(super) fn locator_hash(m: &Memory) -> u32 {
579 match (
580 m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str),
581 locator_of(m),
582 ) {
583 (Some(kind), Some(l)) => locator_hash_of(kind, l),
584 _ => 0,
585 }
586}
587
588#[derive(Debug, Clone, PartialEq, Eq)]
590pub enum ClaimOutcome {
591 Claimed {
594 token: String,
596 expires_at: i64,
598 },
599 HeldBy {
601 agent: String,
603 expires_at: i64,
605 },
606}
607
608#[derive(Debug, Clone, Copy, PartialEq, Eq)]
610pub enum ClaimStatus {
611 Held {
613 expires_at: i64,
615 },
616 Released,
618 Lost,
622}
623
624#[derive(Debug, Clone, PartialEq, Eq)]
626pub struct Claim {
627 pub topic: String,
629 pub holder: String,
631 pub expires_at: i64,
633 pub lease: i64,
635}
636
637#[derive(Debug, Clone, Copy, PartialEq, Eq)]
639pub enum Alive {
640 Yes,
642 No,
644 Unknown,
647}
648
649#[derive(Debug, Clone, PartialEq, Eq)]
651pub struct Presence {
652 pub agent: String,
654 pub role: Option<String>,
656 pub tool: Option<String>,
658 pub last_active: i64,
660 pub alive: Alive,
662 pub claims: Vec<String>,
664}
665
666fn meta_i64(m: &Memory, k: &str) -> Option<i64> {
667 m.metadata.get(k).and_then(Value::as_i64)
668}
669
670fn meta_string(m: &Memory, k: &str) -> Option<String> {
671 m.metadata
672 .get(k)
673 .and_then(Value::as_str)
674 .map(str::to_string)
675}
676
677fn effective_expiry(m: &Memory, now: i64) -> Option<i64> {
680 let token = m
681 .metadata
682 .get(MNEMO_META_CLAIM_TOKEN)
683 .and_then(Value::as_str)?;
684 if token.is_empty() {
685 return None;
686 }
687 let expires = meta_i64(m, MNEMO_META_EXPIRES_AT)?;
688 let lease = meta_i64(m, MNEMO_META_LEASE).unwrap_or(CLAIM_TTL_DEFAULT);
689 Some(expires.min(now.saturating_add(lease)))
690}
691
692fn is_live(m: &Memory, now: i64) -> bool {
694 effective_expiry(m, now).is_some_and(|e| now < e)
695}
696
697fn new_token() -> String {
698 format!(
699 "{:016x}{:016x}",
700 crate::crypto::random_u64(),
701 crate::crypto::random_u64()
702 )
703}
704
705fn check_topic(topic: &str) -> Result<()> {
706 if topic.trim().is_empty() || topic.contains('\n') || topic.len() > CLAIM_TOPIC_MAX {
707 return Err(MnemoError::Invalid(format!(
708 "a claim's topic is one line, not empty, at most {CLAIM_TOPIC_MAX} bytes"
709 )));
710 }
711 Ok(())
712}
713
714fn check_ttl(ttl: Option<i64>) -> Result<i64> {
715 let t = ttl.unwrap_or(CLAIM_TTL_DEFAULT);
716 if !(CLAIM_TTL_MIN..=CLAIM_TTL_MAX).contains(&t) {
717 return Err(MnemoError::Invalid(format!(
718 "a claim's ttl is {CLAIM_TTL_MIN} s to {CLAIM_TTL_MAX} s (24 h); got {t}"
719 )));
720 }
721 Ok(t)
722}
723
724impl Mnemo {
725 pub fn coordination_now(&self) -> i64 {
728 #[cfg(feature = "dev-hooks")]
729 let env: i64 = std::env::var("MNEMO_DEV_CLOCK_OFFSET")
730 .ok()
731 .and_then(|v| v.parse().ok())
732 .unwrap_or(0);
733 #[cfg(not(feature = "dev-hooks"))]
734 let env: i64 = 0;
735 memory::now_secs() + self.clock_offset + env
736 }
737
738 #[cfg(feature = "dev-hooks")]
741 #[doc(hidden)]
742 pub fn __set_clock_offset_for_testing(&mut self, secs: i64) {
743 self.clock_offset = secs;
744 }
745
746 fn claim_agent(&self) -> Result<String> {
747 self.author.clone().ok_or_else(|| {
748 MnemoError::Invalid(
749 "a claim needs an agent: set MNEMO_AGENT (or --as), or call set_author".into(),
750 )
751 })
752 }
753
754 fn find_claim(&mut self, topic: &str) -> Result<Option<Memory>> {
755 Ok(self
756 .coordination_records(MNEMO_META_KIND_CLAIM, Some(topic))?
757 .into_iter()
758 .next())
759 }
760
761 pub fn claim(&mut self, topic: &str, ttl: Option<i64>) -> Result<ClaimOutcome> {
776 if self.read_only {
777 return Err(MnemoError::ReadOnly);
778 }
779 check_topic(topic)?;
780 let ttl = check_ttl(ttl)?;
781 let agent = self.claim_agent()?;
782 let now = self.coordination_now();
783 let existing = self.find_claim(topic)?;
784 if let Some(mut m) = existing.clone() {
785 if is_live(&m, now) {
786 let holder = meta_string(&m, MNEMO_META_HOLDER).unwrap_or_default();
787 let expires = effective_expiry(&m, now).unwrap_or(now);
788 let mut changed = false;
789 let mut lapse = false;
790 let had_lock = m
791 .metadata
792 .get(MNEMO_META_HOLDER_LOCK)
793 .and_then(Value::as_bool)
794 .unwrap_or(false);
795 if had_lock && holder != agent {
796 match crate::shared::probe_presence_once(&self.path, &holder) {
797 Some(false) => match meta_i64(&m, MNEMO_META_DEAD_SEEN_AT) {
798 Some(t) if now - t >= CLAIM_LAPSE_GRACE_SECS => lapse = true,
799 Some(_) => {}
800 None => {
801 m.metadata
802 .insert(MNEMO_META_DEAD_SEEN_AT.into(), Value::from(now));
803 changed = true;
804 }
805 },
806 _ => {
807 changed |= m.metadata.remove(MNEMO_META_DEAD_SEEN_AT).is_some();
808 }
809 }
810 }
811 if !lapse {
812 if meta_i64(&m, MNEMO_META_EXPIRES_AT) != Some(expires) {
815 m.metadata
816 .insert(MNEMO_META_EXPIRES_AT.into(), Value::from(expires));
817 changed = true;
818 }
819 if changed {
820 self.put(m)?;
821 }
822 return Ok(ClaimOutcome::HeldBy {
823 agent: holder,
824 expires_at: expires,
825 });
826 }
827 }
828 }
829 let token = new_token();
830 let expires_at = now + ttl;
831 let mut meta = existing
832 .as_ref()
833 .map(|m| m.metadata.clone())
834 .unwrap_or_default();
835 meta.remove(MNEMO_META_DEAD_SEEN_AT);
836 meta.insert(MNEMO_META_TOPIC.into(), Value::String(topic.to_string()));
837 meta.insert(MNEMO_META_HOLDER.into(), Value::String(agent));
838 meta.insert(MNEMO_META_CLAIM_TOKEN.into(), Value::String(token.clone()));
839 meta.insert(MNEMO_META_EXPIRES_AT.into(), Value::from(expires_at));
840 meta.insert(MNEMO_META_LEASE.into(), Value::from(ttl));
841 meta.insert(
842 MNEMO_META_HOLDER_LOCK.into(),
843 Value::Bool(self.presence_held),
844 );
845 match existing {
846 Some(mut m) => {
847 m.metadata = meta;
848 self.put(m)?;
849 }
850 None => {
851 self.put_coordination_with_id(
852 Ulid::new(),
853 MNEMO_META_KIND_CLAIM,
854 format!("claim {topic}"),
855 meta,
856 )?;
857 }
858 }
859 Ok(ClaimOutcome::Claimed { token, expires_at })
860 }
861
862 pub fn renew(&mut self, topic: &str, token: &str, ttl: Option<i64>) -> Result<ClaimStatus> {
865 if self.read_only {
866 return Err(MnemoError::ReadOnly);
867 }
868 let now = self.coordination_now();
869 let Some(mut m) = self.find_claim(topic)? else {
870 return Ok(ClaimStatus::Lost);
871 };
872 if !is_live(&m, now) || meta_string(&m, MNEMO_META_CLAIM_TOKEN).as_deref() != Some(token) {
873 return Ok(ClaimStatus::Lost);
874 }
875 let lease = match ttl {
876 Some(t) => check_ttl(Some(t))?,
877 None => meta_i64(&m, MNEMO_META_LEASE).unwrap_or(CLAIM_TTL_DEFAULT),
878 };
879 let expires_at = now + lease;
880 m.metadata
881 .insert(MNEMO_META_EXPIRES_AT.into(), Value::from(expires_at));
882 m.metadata
883 .insert(MNEMO_META_LEASE.into(), Value::from(lease));
884 m.metadata.remove(MNEMO_META_DEAD_SEEN_AT);
885 self.put(m)?;
886 Ok(ClaimStatus::Held { expires_at })
887 }
888
889 pub fn release(&mut self, topic: &str, token: &str) -> Result<ClaimStatus> {
892 if self.read_only {
893 return Err(MnemoError::ReadOnly);
894 }
895 let now = self.coordination_now();
896 let Some(mut m) = self.find_claim(topic)? else {
897 return Ok(ClaimStatus::Lost);
898 };
899 if !is_live(&m, now) || meta_string(&m, MNEMO_META_CLAIM_TOKEN).as_deref() != Some(token) {
900 return Ok(ClaimStatus::Lost);
901 }
902 m.metadata.remove(MNEMO_META_CLAIM_TOKEN);
903 m.metadata.remove(MNEMO_META_DEAD_SEEN_AT);
904 m.metadata
905 .insert(MNEMO_META_EXPIRES_AT.into(), Value::from(now));
906 self.put(m)?;
907 Ok(ClaimStatus::Released)
908 }
909
910 pub fn check_claim(&mut self, topic: &str, token: &str) -> Result<ClaimStatus> {
913 let now = self.coordination_now();
914 let Some(m) = self.find_claim(topic)? else {
915 return Ok(ClaimStatus::Lost);
916 };
917 if meta_string(&m, MNEMO_META_CLAIM_TOKEN).as_deref() != Some(token) {
918 return Ok(ClaimStatus::Lost);
919 }
920 match effective_expiry(&m, now) {
921 Some(e) if now < e => Ok(ClaimStatus::Held { expires_at: e }),
922 _ => Ok(ClaimStatus::Lost),
923 }
924 }
925
926 pub fn claims(&mut self) -> Result<Vec<Claim>> {
928 let now = self.coordination_now();
929 let mut out: Vec<Claim> = self
930 .coordination_records(MNEMO_META_KIND_CLAIM, None)?
931 .iter()
932 .filter(|m| is_live(m, now))
933 .map(|m| Claim {
934 topic: meta_string(m, MNEMO_META_TOPIC).unwrap_or_default(),
935 holder: meta_string(m, MNEMO_META_HOLDER).unwrap_or_default(),
936 expires_at: effective_expiry(m, now).unwrap_or(now),
937 lease: meta_i64(m, MNEMO_META_LEASE).unwrap_or(CLAIM_TTL_DEFAULT),
938 })
939 .collect();
940 out.sort_by(|a, b| a.topic.cmp(&b.topic));
941 Ok(out)
942 }
943
944 pub fn touch_presence(&mut self, role: Option<&str>, tool: Option<&str>) -> Result<bool> {
951 if self.read_only {
952 return Err(MnemoError::ReadOnly);
953 }
954 let Some(agent) = self.author.clone() else {
955 return Ok(false);
956 };
957 let now = self.coordination_now();
958 let existing = self
959 .coordination_records(MNEMO_META_KIND_PRESENCE, Some(&agent))?
960 .into_iter()
961 .next();
962 let role_v = role.map(|r| Value::String(r.to_string()));
963 let tool_v = tool.map(|t| Value::String(t.to_string()));
964 let defer = !self.presence_held
968 && existing.as_ref().is_some_and(|m| {
969 m.metadata
970 .get(MNEMO_META_PRESENCE_LOCK)
971 .and_then(Value::as_bool)
972 .unwrap_or(false)
973 });
974 if let Some(m) = &existing {
975 let fresh = meta_i64(m, MNEMO_META_LAST_ACTIVE)
976 .is_some_and(|t| now >= t && now - t < PRESENCE_EVERY_SECS);
977 let same = defer
978 || (m.metadata.get(crate::memory::MNEMO_META_ROLE) == role_v.as_ref()
979 && m.metadata.get(MNEMO_META_TOOL) == tool_v.as_ref()
980 && m.metadata
981 .get(MNEMO_META_PRESENCE_LOCK)
982 .and_then(Value::as_bool)
983 == Some(self.presence_held));
984 if fresh && same {
985 return Ok(false);
986 }
987 }
988 if defer {
989 let mut m = existing.expect("checked");
990 m.metadata
991 .insert(MNEMO_META_LAST_ACTIVE.into(), Value::from(now));
992 self.put(m)?;
993 return Ok(true);
994 }
995 let mut meta = existing
996 .as_ref()
997 .map(|m| m.metadata.clone())
998 .unwrap_or_default();
999 meta.insert(MNEMO_META_AGENT.into(), Value::String(agent.clone()));
1000 for (k, v) in [
1001 (crate::memory::MNEMO_META_ROLE, role_v),
1002 (MNEMO_META_TOOL, tool_v),
1003 ] {
1004 match v {
1005 Some(v) => {
1006 meta.insert(k.into(), v);
1007 }
1008 None => {
1009 meta.remove(k);
1010 }
1011 }
1012 }
1013 meta.insert(MNEMO_META_LAST_ACTIVE.into(), Value::from(now));
1014 meta.insert(
1015 MNEMO_META_PRESENCE_LOCK.into(),
1016 Value::Bool(self.presence_held),
1017 );
1018 match existing {
1019 Some(mut m) => {
1020 m.metadata = meta;
1021 self.put(m)?;
1022 }
1023 None => {
1024 self.put_coordination_with_id(
1025 Ulid::new(),
1026 MNEMO_META_KIND_PRESENCE,
1027 format!("presence {agent}"),
1028 meta,
1029 )?;
1030 }
1031 }
1032 Ok(true)
1033 }
1034
1035 pub fn who(&mut self) -> Result<Vec<Presence>> {
1040 let claims = self.claims()?;
1041 let records = self.coordination_records(MNEMO_META_KIND_PRESENCE, None)?;
1042 let mut out: Vec<Presence> = records
1043 .iter()
1044 .map(|m| {
1045 let agent = meta_string(m, MNEMO_META_AGENT).unwrap_or_default();
1046 let locked = m
1047 .metadata
1048 .get(MNEMO_META_PRESENCE_LOCK)
1049 .and_then(Value::as_bool)
1050 .unwrap_or(false);
1051 let alive = if !locked {
1052 Alive::Unknown
1053 } else {
1054 match crate::shared::probe_presence(&self.path, &agent) {
1055 Some(true) => Alive::Yes,
1056 Some(false) => Alive::No,
1057 None => Alive::Unknown,
1058 }
1059 };
1060 Presence {
1061 claims: claims
1062 .iter()
1063 .filter(|c| c.holder == agent)
1064 .map(|c| c.topic.clone())
1065 .collect(),
1066 role: meta_string(m, crate::memory::MNEMO_META_ROLE),
1067 tool: meta_string(m, MNEMO_META_TOOL),
1068 last_active: meta_i64(m, MNEMO_META_LAST_ACTIVE).unwrap_or(0),
1069 alive,
1070 agent,
1071 }
1072 })
1073 .collect();
1074 out.sort_by(|a, b| {
1075 b.last_active
1076 .cmp(&a.last_active)
1077 .then(a.agent.cmp(&b.agent))
1078 });
1079 Ok(out)
1080 }
1081}
1082
1083use crate::memory::{
1086 task_status, MNEMO_META_AFTER, MNEMO_META_CREATOR, MNEMO_META_KIND_TASK, MNEMO_META_OWNER,
1087 MNEMO_META_PRE_APPROVED, MNEMO_META_SLUG, TASK_CLAIM_TTL, TASK_SLUG_MAX, TASK_TRANSITIONS,
1088};
1089
1090#[derive(Debug, Clone, Default, PartialEq, Eq)]
1092pub struct TaskSpec {
1093 pub title: String,
1095 pub body: String,
1097 pub role: Option<String>,
1099 pub after: Vec<String>,
1101 pub pre_approved: bool,
1103 pub slug: Option<String>,
1105}
1106
1107#[derive(Debug, Clone, PartialEq)]
1109pub struct Task {
1110 pub id: Ulid,
1112 pub slug: String,
1114 pub title: String,
1116 pub body: String,
1118 pub role: Option<String>,
1120 pub status: String,
1122 pub owner: Option<String>,
1124 pub creator: String,
1126 pub after: Vec<String>,
1128 pub pre_approved: bool,
1130 pub created_at: i64,
1132 pub history: Vec<Value>,
1135}
1136
1137impl Task {
1138 pub fn from_memory(m: &Memory) -> Option<Task> {
1140 if m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str) != Some(MNEMO_META_KIND_TASK) {
1141 return None;
1142 }
1143 let (title, body) = match m.content.split_once("\n\n") {
1144 Some((a, b)) => (a.to_string(), b.to_string()),
1145 None => (m.content.clone(), String::new()),
1146 };
1147 Some(Task {
1148 id: m.id,
1149 slug: meta_string(m, MNEMO_META_SLUG).unwrap_or_default(),
1150 title,
1151 body,
1152 role: meta_string(m, crate::memory::MNEMO_META_ROLE),
1153 status: meta_string(m, MNEMO_META_STATUS).unwrap_or_default(),
1154 owner: meta_string(m, MNEMO_META_OWNER),
1155 creator: meta_string(m, MNEMO_META_CREATOR).unwrap_or_default(),
1156 after: m
1157 .metadata
1158 .get(MNEMO_META_AFTER)
1159 .and_then(Value::as_array)
1160 .map(|a| {
1161 a.iter()
1162 .filter_map(|v| v.as_str().map(str::to_string))
1163 .collect()
1164 })
1165 .unwrap_or_default(),
1166 pre_approved: m
1167 .metadata
1168 .get(MNEMO_META_PRE_APPROVED)
1169 .and_then(Value::as_bool)
1170 .unwrap_or(false),
1171 created_at: m.created_at,
1172 history: m
1173 .metadata
1174 .get(MNEMO_META_STATUS_HISTORY)
1175 .and_then(Value::as_array)
1176 .cloned()
1177 .unwrap_or_default(),
1178 })
1179 }
1180
1181 fn for_role(&self, role: Option<&str>) -> bool {
1184 self.role.is_none() || self.role.as_deref() == role
1185 }
1186}
1187
1188#[derive(Debug, Clone, PartialEq)]
1190pub struct TaskTaken {
1191 pub task: Task,
1193 pub token: String,
1196 pub expires_at: i64,
1198 pub reclaimed_from: Option<String>,
1200}
1201
1202#[derive(Debug, Clone, PartialEq, Eq)]
1205pub struct TaskClaim {
1206 pub token: String,
1208 pub expires_at: i64,
1210 pub retaken: bool,
1213}
1214
1215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1217pub enum TaskLost {
1218 TakenBack,
1220 OtherToken,
1223}
1224
1225#[derive(Debug, Clone, PartialEq)]
1227pub enum TaskOutcome {
1228 Updated(Box<Task>, Option<TaskClaim>),
1232 Lost(TaskLost),
1234}
1235
1236pub fn slug_of(title: &str) -> String {
1239 let mut out = String::new();
1240 for c in title.chars() {
1241 if c.is_ascii_alphanumeric() {
1242 out.push(c.to_ascii_lowercase());
1243 } else if !out.ends_with('-') && !out.is_empty() {
1244 out.push('-');
1245 }
1246 if out.len() >= TASK_SLUG_MAX {
1247 break;
1248 }
1249 }
1250 out.trim_end_matches('-').to_string()
1251}
1252
1253fn valid_slug(s: &str) -> bool {
1254 !s.is_empty()
1255 && s.len() <= TASK_SLUG_MAX
1256 && s.bytes()
1257 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b))
1258}
1259
1260fn task_topic(slug: &str) -> String {
1261 format!("task:{slug}")
1262}
1263
1264impl Mnemo {
1265 fn task_records(&mut self, slug: Option<&str>) -> Result<Vec<Memory>> {
1266 let mut v = self.coordination_records(MNEMO_META_KIND_TASK, slug)?;
1267 v.sort_by_key(|m| m.created_at);
1268 Ok(v)
1269 }
1270
1271 fn task_record(&mut self, slug: &str) -> Result<Option<Memory>> {
1272 Ok(self.task_records(Some(slug))?.into_iter().next())
1273 }
1274
1275 pub fn task(&mut self, slug: &str) -> Result<Option<Task>> {
1277 Ok(self.task_record(slug)?.as_ref().and_then(Task::from_memory))
1278 }
1279
1280 pub fn tasks(&mut self, status: Option<&str>, role: Option<&str>) -> Result<Vec<Task>> {
1283 Ok(self
1284 .task_records(None)?
1285 .iter()
1286 .filter_map(Task::from_memory)
1287 .filter(|t| status.is_none_or(|s| t.status == s))
1288 .filter(|t| role.is_none() || t.for_role(role))
1289 .collect())
1290 }
1291
1292 pub fn ready_tasks(&mut self, role: Option<&str>) -> Result<Vec<Task>> {
1295 let all: Vec<Task> = self
1296 .task_records(None)?
1297 .iter()
1298 .filter_map(Task::from_memory)
1299 .collect();
1300 let done: std::collections::HashSet<&str> = all
1301 .iter()
1302 .filter(|t| t.status == task_status::DONE)
1303 .map(|t| t.slug.as_str())
1304 .collect();
1305 Ok(all
1306 .iter()
1307 .filter(|t| t.status == task_status::QUEUED && t.for_role(role))
1308 .filter(|t| t.after.iter().all(|a| done.contains(a.as_str())))
1309 .cloned()
1310 .collect())
1311 }
1312
1313 pub fn task_add(&mut self, spec: &TaskSpec) -> Result<(Task, WriteOutcome)> {
1319 if self.read_only {
1320 return Err(MnemoError::ReadOnly);
1321 }
1322 let title = spec.title.trim();
1323 if title.is_empty()
1324 || title.contains('\n')
1325 || title.len() > crate::memory::MESSAGE_SUBJECT_MAX
1326 {
1327 return Err(MnemoError::Invalid(format!(
1328 "a task's title is one line, not empty, at most {} bytes",
1329 crate::memory::MESSAGE_SUBJECT_MAX
1330 )));
1331 }
1332 if spec.body.len() > crate::memory::MESSAGE_BODY_MAX {
1333 return Err(MnemoError::Invalid(format!(
1334 "a task's body is at most {} bytes; put more in a fact and name it",
1335 crate::memory::MESSAGE_BODY_MAX
1336 )));
1337 }
1338 let slug = match &spec.slug {
1339 Some(s) => s.clone(),
1340 None => slug_of(title),
1341 };
1342 if !valid_slug(&slug) {
1343 return Err(MnemoError::Invalid(format!(
1344 "{slug:?} isn't a slug: 1 to {TASK_SLUG_MAX} of a-z, 0-9, '.', '_' and '-' \
1345 (give one with --slug)"
1346 )));
1347 }
1348 if let Some(r) = &spec.role {
1349 if !crate::memory::valid_agent_id(r) {
1350 return Err(MnemoError::Invalid(format!("{r:?} isn't a role")));
1351 }
1352 }
1353 for a in &spec.after {
1354 if a == &slug {
1355 return Err(MnemoError::Invalid("a task can't wait for itself".into()));
1356 }
1357 if self.task_record(a)?.is_none() {
1358 return Err(MnemoError::Invalid(format!("after: no task {a:?}")));
1359 }
1360 }
1361 let content = if spec.body.is_empty() {
1362 title.to_string()
1363 } else {
1364 format!("{title}\n\n{}", spec.body)
1365 };
1366 let set = |meta: &mut Map<String, Value>| {
1367 match &spec.role {
1368 Some(r) => {
1369 meta.insert(
1370 crate::memory::MNEMO_META_ROLE.into(),
1371 Value::String(r.clone()),
1372 );
1373 }
1374 None => {
1375 meta.remove(crate::memory::MNEMO_META_ROLE);
1376 }
1377 }
1378 meta.insert(
1379 MNEMO_META_AFTER.into(),
1380 Value::Array(
1381 spec.after
1382 .iter()
1383 .map(|a| Value::String(a.clone()))
1384 .collect(),
1385 ),
1386 );
1387 meta.insert(
1388 MNEMO_META_PRE_APPROVED.into(),
1389 Value::Bool(spec.pre_approved),
1390 );
1391 };
1392 if let Some(mut m) = self.task_record(&slug)? {
1393 let t = Task::from_memory(&m).expect("a task");
1394 let mut meta = m.metadata.clone();
1395 set(&mut meta);
1396 if meta == m.metadata && m.content == content {
1397 return Ok((t, WriteOutcome::Unchanged));
1398 }
1399 if t.status == task_status::DONE {
1402 let mut n = 2;
1403 while self.task_record(&format!("{slug}-{n}"))?.is_some() {
1404 n += 1;
1405 }
1406 return Err(MnemoError::Invalid(format!(
1407 "{slug} is done; give a new slug ({slug}-{n}?)"
1408 )));
1409 }
1410 let caller = self.author.clone().unwrap_or_else(|| "anonymous".into());
1411 if caller != t.creator {
1412 return Err(MnemoError::Invalid(format!(
1413 "that slug is {}'s task; it wasn't changed",
1414 t.creator
1415 )));
1416 }
1417 if self.closes_cycle(&slug, &spec.after)? {
1419 return Err(MnemoError::Invalid(format!(
1420 "after: that would make {slug} wait for itself, through the tasks it waits for"
1421 )));
1422 }
1423 m.metadata = meta;
1424 m.content = content;
1425 let id = m.id;
1426 self.put(m)?;
1427 let t = Task::from_memory(&self.get(&id)?).expect("a task");
1428 return Ok((t, WriteOutcome::Updated));
1429 }
1430 let mut meta = Map::new();
1431 meta.insert(MNEMO_META_SLUG.into(), Value::String(slug));
1432 meta.insert(
1433 MNEMO_META_STATUS.into(),
1434 Value::String(task_status::QUEUED.into()),
1435 );
1436 meta.insert(
1437 MNEMO_META_CREATOR.into(),
1438 Value::String(self.author.clone().unwrap_or_else(|| "anonymous".into())),
1439 );
1440 meta.insert(
1441 MNEMO_META_DELIVERY.into(),
1442 Value::String(crate::memory::delivery::SENT.into()),
1443 );
1444 set(&mut meta);
1445 let id = self.put_coordination_with_id(Ulid::new(), MNEMO_META_KIND_TASK, content, meta)?;
1446 let t = Task::from_memory(&self.get(&id)?).expect("a task");
1447 Ok((t, WriteOutcome::Added))
1448 }
1449
1450 fn closes_cycle(&mut self, slug: &str, after: &[String]) -> Result<bool> {
1453 let all: std::collections::HashMap<String, Vec<String>> = self
1454 .task_records(None)?
1455 .iter()
1456 .filter_map(Task::from_memory)
1457 .map(|t| (t.slug, t.after))
1458 .collect();
1459 let mut stack: Vec<&str> = after.iter().map(String::as_str).collect();
1460 let mut seen = std::collections::HashSet::new();
1461 while let Some(s) = stack.pop() {
1462 if s == slug {
1463 return Ok(true);
1464 }
1465 if seen.insert(s.to_string()) {
1466 if let Some(next) = all.get(s) {
1467 stack.extend(next.iter().map(String::as_str));
1468 }
1469 }
1470 }
1471 Ok(false)
1472 }
1473
1474 fn task_history(
1476 m: &mut Memory,
1477 from: &str,
1478 to: &str,
1479 by: &str,
1480 at: i64,
1481 extra: &[(&str, &str)],
1482 ) {
1483 let mut e = Map::new();
1484 e.insert("from".into(), Value::String(from.into()));
1485 e.insert("to".into(), Value::String(to.into()));
1486 e.insert("at".into(), Value::from(at));
1487 e.insert("by".into(), Value::String(by.into()));
1488 for (k, v) in extra {
1489 e.insert((*k).into(), Value::String((*v).into()));
1490 }
1491 let mut h = m
1492 .metadata
1493 .get(MNEMO_META_STATUS_HISTORY)
1494 .and_then(Value::as_array)
1495 .cloned()
1496 .unwrap_or_default();
1497 h.push(Value::Object(e));
1498 m.metadata
1499 .insert(MNEMO_META_STATUS_HISTORY.into(), Value::Array(h));
1500 }
1501
1502 pub fn task_next(&mut self, role: Option<&str>) -> Result<Option<TaskTaken>> {
1510 if self.read_only {
1511 return Err(MnemoError::ReadOnly);
1512 }
1513 let agent = self.claim_agent()?;
1514 let now = self.coordination_now();
1515 let ready: Vec<Ulid> = self.ready_tasks(role)?.iter().map(|t| t.id).collect();
1516 let taken: Vec<Task> = self
1521 .task_records(None)?
1522 .iter()
1523 .filter_map(Task::from_memory)
1524 .filter(|t| t.status == task_status::ACTIVE || t.status == task_status::BLOCKED)
1525 .filter(|t| t.for_role(role))
1526 .collect();
1527 let (own, others): (Vec<&Task>, Vec<&Task>) = taken
1528 .iter()
1529 .partition(|t| t.owner.as_deref() == Some(agent.as_str()));
1530 for (id, back) in own
1531 .iter()
1532 .map(|t| (t.id, true))
1533 .chain(ready.into_iter().map(|i| (i, false)))
1534 .chain(others.iter().map(|t| (t.id, true)))
1535 {
1536 let mut m = self.get(&id)?;
1537 let t = Task::from_memory(&m).expect("a task");
1538 let (token, expires_at) =
1539 match self.claim(&task_topic(&t.slug), Some(TASK_CLAIM_TTL))? {
1540 ClaimOutcome::Claimed { token, expires_at } => (token, expires_at),
1541 ClaimOutcome::HeldBy { .. } => continue,
1542 };
1543 m = self.get(&id)?;
1546 let old = t.owner.clone();
1547 let own = old.as_deref() == Some(agent.as_str());
1548 if back && own {
1549 Self::task_history(
1550 &mut m,
1551 &t.status,
1552 task_status::ACTIVE,
1553 &agent,
1554 now,
1555 &[("note", "taken again after its claim lapsed")],
1556 );
1557 } else if back {
1558 let from = old.clone().unwrap_or_default();
1559 Self::task_history(
1560 &mut m,
1561 &t.status,
1562 task_status::ACTIVE,
1563 &agent,
1564 now,
1565 &[("reclaimed_from", from.as_str())],
1566 );
1567 } else {
1568 Self::task_history(
1569 &mut m,
1570 task_status::QUEUED,
1571 task_status::ACTIVE,
1572 &agent,
1573 now,
1574 &[],
1575 );
1576 }
1577 m.metadata.insert(
1578 MNEMO_META_STATUS.into(),
1579 Value::String(task_status::ACTIVE.into()),
1580 );
1581 m.metadata
1582 .insert(MNEMO_META_OWNER.into(), Value::String(agent.clone()));
1583 self.put(m)?;
1584 let task = Task::from_memory(&self.get(&id)?).expect("a task");
1585 return Ok(Some(TaskTaken {
1586 task,
1587 token,
1588 expires_at,
1589 reclaimed_from: if back && !own { old } else { None },
1590 }));
1591 }
1592 Ok(None)
1593 }
1594
1595 pub fn task_update(
1610 &mut self,
1611 slug: &str,
1612 status: Option<&str>,
1613 note: Option<&str>,
1614 token: Option<&str>,
1615 ) -> Result<TaskOutcome> {
1616 if self.read_only {
1617 return Err(MnemoError::ReadOnly);
1618 }
1619 let agent = self.claim_agent()?;
1620 let now = self.coordination_now();
1621 let Some(m) = self.task_record(slug)? else {
1622 return Err(MnemoError::Invalid(format!("no task {slug:?}")));
1623 };
1624 let t = Task::from_memory(&m).expect("a task");
1625 let to = status.unwrap_or(&t.status).to_string();
1626 if status.is_none() && note.is_none() {
1627 return Err(MnemoError::Invalid("give a status or a note".into()));
1628 }
1629 if token.is_some() && t.owner.as_deref() != Some(agent.as_str()) {
1632 return Ok(TaskOutcome::Lost(TaskLost::TakenBack));
1633 }
1634 let changing = to != t.status;
1635 if changing && !TASK_TRANSITIONS.contains(&(t.status.as_str(), to.as_str())) {
1636 return Err(MnemoError::Invalid(format!(
1637 "a task can't go from {} to {to}",
1638 t.status
1639 )));
1640 }
1641 if changing && t.status == task_status::QUEUED {
1642 return Err(MnemoError::Invalid(
1643 "a queued task is taken with `task next`".into(),
1644 ));
1645 }
1646 let topic = task_topic(slug);
1647 let claim = self.find_claim(&topic)?;
1648 let live = claim.as_ref().filter(|c| is_live(c, now));
1649 let claim_token = claim
1650 .as_ref()
1651 .and_then(|c| meta_string(c, MNEMO_META_CLAIM_TOKEN));
1652 let held_by_owner = live.is_some_and(|c| meta_string(c, MNEMO_META_HOLDER) == t.owner);
1653 let is_owner = t.owner.as_deref() == Some(agent.as_str());
1654 let is_creator = t.creator == agent;
1655 let by_owner = if changing && t.status == task_status::READY {
1657 if !(is_creator || (is_owner && t.pre_approved)) {
1659 return Err(MnemoError::Invalid(format!(
1660 "{slug} waits for its creator ({}) to set done",
1661 t.creator
1662 )));
1663 }
1664 false
1665 } else if changing && to == task_status::QUEUED && !is_owner {
1666 if let Some(c) = live {
1668 return Err(MnemoError::Invalid(format!(
1669 "{slug} is {}'s, and its claim is live until {}; only its owner can hand \
1670 it back before then",
1671 t.owner.as_deref().unwrap_or("its owner"),
1672 crate::memory::date_time_of(effective_expiry(c, now).unwrap_or(now))
1673 )));
1674 }
1675 false
1676 } else if t.status == task_status::DONE || (!changing && t.status == task_status::READY) {
1677 if !(is_creator || is_owner) {
1679 return Err(MnemoError::Invalid(format!("{slug} isn't yours")));
1680 }
1681 false
1682 } else if !changing && is_creator && !is_owner {
1683 false } else if t.status == task_status::QUEUED {
1685 if !is_creator {
1687 return Err(MnemoError::Invalid(format!("{slug} isn't yours")));
1688 }
1689 false
1690 } else {
1691 if !is_owner {
1692 return Ok(TaskOutcome::Lost(TaskLost::TakenBack));
1693 }
1694 true
1695 };
1696 let mut renew_token = None;
1703 if by_owner {
1704 let token_ok = token.is_none_or(|tk| claim_token.as_deref() == Some(tk));
1705 if live.is_some() && !held_by_owner {
1706 return Ok(TaskOutcome::Lost(TaskLost::TakenBack));
1707 }
1708 if !token_ok {
1709 return Ok(TaskOutcome::Lost(TaskLost::OtherToken));
1710 }
1711 if held_by_owner {
1712 renew_token = claim_token.clone();
1713 }
1714 }
1715 let mut m = m;
1716 let mut extra: Vec<(&str, &str)> = Vec::new();
1717 if let Some(n) = note {
1718 extra.push(("note", n));
1719 }
1720 Self::task_history(&mut m, &t.status, &to, &agent, now, &extra);
1721 m.metadata
1722 .insert(MNEMO_META_STATUS.into(), Value::String(to.clone()));
1723 if to == task_status::QUEUED {
1724 m.metadata.remove(MNEMO_META_OWNER);
1725 }
1726 let id = m.id;
1727 self.put(m)?;
1728 let releases =
1729 [task_status::READY, task_status::DONE, task_status::QUEUED].contains(&to.as_str());
1730 let mut held: Option<TaskClaim> = None;
1731 match (releases, by_owner, renew_token) {
1732 (true, _, Some(tk)) => {
1733 self.release(&topic, &tk)?;
1734 }
1735 (true, _, None) => {
1736 if let Some(mut c) = self.find_claim(&topic)? {
1738 if is_live(&c, now)
1739 && meta_string(&c, MNEMO_META_HOLDER) == t.owner
1740 && to == task_status::DONE
1741 {
1742 c.metadata.remove(MNEMO_META_CLAIM_TOKEN);
1743 c.metadata
1744 .insert(MNEMO_META_EXPIRES_AT.into(), Value::from(now));
1745 self.put(c)?;
1746 }
1747 }
1748 }
1749 (false, true, Some(tk)) => {
1750 if let ClaimStatus::Held { expires_at } =
1751 self.renew(&topic, &tk, Some(TASK_CLAIM_TTL))?
1752 {
1753 held = Some(TaskClaim {
1754 token: tk,
1755 expires_at,
1756 retaken: false,
1757 });
1758 }
1759 }
1760 (false, true, None) => {
1761 if let ClaimOutcome::Claimed { token, expires_at } =
1764 self.claim(&topic, Some(TASK_CLAIM_TTL))?
1765 {
1766 held = Some(TaskClaim {
1767 token,
1768 expires_at,
1769 retaken: true,
1770 });
1771 }
1772 }
1773 (false, false, _) => {}
1774 }
1775 Ok(TaskOutcome::Updated(
1776 Box::new(Task::from_memory(&self.get(&id)?).expect("a task")),
1777 held,
1778 ))
1779 }
1780}
1781
1782use crate::memory::{
1785 HOP_CAP, MNEMO_META_WAKES, MNEMO_META_WAKE_PAUSED, MNEMO_META_WARNED_EXPIRY, PAIR_BURST,
1786 PAIR_BURST_SECS, TASK_CLAIM_WARN_SECS, WAKE_COOLDOWN_SECS, WAKE_PER_HOUR,
1787};
1788
1789#[derive(Debug, Clone, Default, PartialEq)]
1792pub struct NewWork {
1793 pub messages: Vec<Message>,
1795 pub tasks: Vec<Task>,
1797 pub lapsing: Vec<Claim>,
1801 pub agent: Option<String>,
1804}
1805
1806impl NewWork {
1807 pub fn is_empty(&self) -> bool {
1809 self.messages.is_empty() && self.tasks.is_empty() && self.lapsing.is_empty()
1810 }
1811}
1812
1813#[derive(Debug, Clone, PartialEq, Eq)]
1815pub enum Wake {
1816 Now {
1819 tasks: usize,
1821 messages: usize,
1823 },
1824 Nothing,
1826 Held(&'static str),
1829}
1830
1831impl Mnemo {
1832 pub fn new_work(&mut self, agent: Option<&str>, role: Option<&str>) -> Result<NewWork> {
1835 let now = self.coordination_now();
1836 let unseen =
1837 |d: &str| d == crate::memory::delivery::SENT || d == crate::memory::delivery::DELIVERED;
1838 let mut messages = Vec::new();
1842 for msg in self.inbox(agent, role, true)? {
1843 let broadcast = msg.to == "all" || msg.to.starts_with("role:");
1844 let new = match (broadcast, agent) {
1845 (true, Some(a)) => !seen_by(&self.get(&msg.id)?).iter().any(|s| s == a),
1846 _ => unseen(&msg.delivery),
1847 };
1848 if new {
1849 messages.push(msg);
1850 }
1851 }
1852 let mut tasks = Vec::new();
1853 for t in self.ready_tasks(role)? {
1854 let m = self.get(&t.id)?;
1855 let new = match agent {
1856 Some(a) => !seen_by(&m).iter().any(|s| s == a),
1857 None => meta_string(&m, MNEMO_META_DELIVERY).is_none_or(|d| unseen(&d)),
1858 };
1859 if new {
1860 tasks.push(t);
1861 }
1862 }
1863 let mut lapsing = Vec::new();
1864 if let Some(a) = agent {
1865 for m in self.coordination_records(MNEMO_META_KIND_CLAIM, None)? {
1866 let topic = meta_string(&m, MNEMO_META_TOPIC).unwrap_or_default();
1867 if !topic.starts_with("task:")
1868 || meta_string(&m, MNEMO_META_HOLDER).as_deref() != Some(a)
1869 || !is_live(&m, now)
1870 {
1871 continue;
1872 }
1873 let e = effective_expiry(&m, now).unwrap_or(now);
1874 if e - now <= TASK_CLAIM_WARN_SECS
1875 && meta_i64(&m, MNEMO_META_WARNED_EXPIRY) != Some(e)
1876 {
1877 lapsing.push(Claim {
1878 topic,
1879 holder: a.to_string(),
1880 expires_at: e,
1881 lease: meta_i64(&m, MNEMO_META_LEASE).unwrap_or(CLAIM_TTL_DEFAULT),
1882 });
1883 }
1884 }
1885 }
1886 Ok(NewWork {
1887 messages,
1888 tasks,
1889 lapsing,
1890 agent: agent.map(str::to_string),
1891 })
1892 }
1893
1894 pub fn mark_shown(&mut self, work: &NewWork) -> Result<()> {
1897 if self.read_only {
1898 return Err(MnemoError::ReadOnly);
1899 }
1900 let ids: Vec<Ulid> = work.messages.iter().map(|m| m.id).collect();
1901 let who = work.agent.clone().or_else(|| self.author.clone());
1903 let author = std::mem::replace(&mut self.author, who.clone());
1904 let r = self.mark_seen(&ids);
1905 self.author = author;
1906 r?;
1907 for t in &work.tasks {
1908 let mut m = self.get(&t.id)?;
1909 match who.clone() {
1910 Some(a) => {
1912 if add_seen_by(&mut m, &a) {
1913 self.put(m)?;
1914 }
1915 }
1916 None => {
1917 m.metadata.insert(
1918 MNEMO_META_DELIVERY.into(),
1919 Value::String(crate::memory::delivery::SEEN.into()),
1920 );
1921 self.put(m)?;
1922 }
1923 }
1924 }
1925 for c in &work.lapsing {
1926 if let Some(mut m) = self.find_claim(&c.topic)? {
1927 m.metadata
1928 .insert(MNEMO_META_WARNED_EXPIRY.into(), Value::from(c.expires_at));
1929 self.put(m)?;
1930 }
1931 }
1932 Ok(())
1933 }
1934
1935 pub fn wake_paused(&mut self) -> Result<Option<(String, i64)>> {
1938 let Some(m) = self
1939 .about_in(crate::memory::VisibilitySet::ALL)?
1940 .into_iter()
1941 .find(is_manifest)
1942 else {
1943 return Ok(None);
1944 };
1945 Ok(m.metadata.get(MNEMO_META_WAKE_PAUSED).map(|v| {
1946 (
1947 v.get("by")
1948 .and_then(Value::as_str)
1949 .unwrap_or("")
1950 .to_string(),
1951 v.get("at").and_then(Value::as_i64).unwrap_or(0),
1952 )
1953 }))
1954 }
1955
1956 pub fn set_wake_paused(&mut self, paused: bool) -> Result<WriteOutcome> {
1960 if self.read_only {
1961 return Err(MnemoError::ReadOnly);
1962 }
1963 let Some(mut m) = self
1964 .about_in(crate::memory::VisibilitySet::ALL)?
1965 .into_iter()
1966 .find(is_manifest)
1967 else {
1968 return Err(MnemoError::Invalid(
1969 "this brain has no manifest to record the pause on".into(),
1970 ));
1971 };
1972 if m.metadata.contains_key(MNEMO_META_WAKE_PAUSED) == paused {
1973 return Ok(WriteOutcome::Unchanged);
1974 }
1975 if paused {
1976 let mut v = Map::new();
1977 v.insert(
1978 "by".into(),
1979 Value::String(self.author.clone().unwrap_or_else(|| "anonymous".into())),
1980 );
1981 v.insert("at".into(), Value::from(self.coordination_now()));
1982 m.metadata
1983 .insert(MNEMO_META_WAKE_PAUSED.into(), Value::Object(v));
1984 } else {
1985 m.metadata.remove(MNEMO_META_WAKE_PAUSED);
1986 }
1987 self.put(m)?;
1988 Ok(WriteOutcome::Updated)
1989 }
1990
1991 pub fn wake(&mut self, agent: &str, role: Option<&str>) -> Result<Wake> {
2006 if self.read_only {
2007 return Err(MnemoError::ReadOnly);
2008 }
2009 let now = self.coordination_now();
2010 let sent = crate::memory::delivery::SENT;
2011 let mut tasks = Vec::new();
2012 for t in self.ready_tasks(role)? {
2013 let m = self.get(&t.id)?;
2014 if t.pre_approved
2015 && meta_string(&m, MNEMO_META_DELIVERY).as_deref() == Some(sent)
2016 && !seen_by(&m).iter().any(|s| s == agent)
2017 {
2018 tasks.push(t.id);
2019 }
2020 }
2021 let all_msgs: Vec<Message> = self
2022 .messages()?
2023 .iter()
2024 .filter_map(Message::from_memory)
2025 .collect();
2026 let candidates: Vec<&Message> = all_msgs
2027 .iter()
2028 .filter(|m| m.to == agent && m.from != agent)
2029 .filter(|m| m.status == crate::memory::MESSAGE_UNREAD && m.delivery == sent)
2030 .collect();
2031 if tasks.is_empty() && candidates.is_empty() {
2032 return Ok(Wake::Nothing);
2033 }
2034 if self.wake_paused()?.is_some() {
2035 return Ok(Wake::Held("paused"));
2036 }
2037 let burst = |a: &str, b: &str| {
2038 all_msgs
2039 .iter()
2040 .filter(|m| now - m.created_at <= PAIR_BURST_SECS)
2041 .filter(|m| (m.from == a && m.to == b) || (m.from == b && m.to == a))
2042 .count()
2043 >= PAIR_BURST
2044 };
2045 let mut reason = None;
2046 let messages: Vec<Ulid> = candidates
2047 .iter()
2048 .filter(|m| {
2049 let reply = m.conversation != m.id.to_string();
2050 if reply && m.hops > HOP_CAP {
2051 reason = Some("the thread reached its hop cap");
2052 return false;
2053 }
2054 if burst(&m.from, &m.to) {
2055 reason = Some("a burst of messages between two agents");
2056 return false;
2057 }
2058 true
2059 })
2060 .map(|m| m.id)
2061 .collect();
2062 if tasks.is_empty() && messages.is_empty() {
2063 return Ok(Wake::Held(reason.unwrap_or("a guardrail")));
2064 }
2065 let presence = self
2067 .coordination_records(MNEMO_META_KIND_PRESENCE, Some(agent))?
2068 .into_iter()
2069 .next();
2070 let mut wakes: Vec<i64> = presence
2071 .as_ref()
2072 .and_then(|m| m.metadata.get(MNEMO_META_WAKES))
2073 .and_then(Value::as_array)
2074 .map(|a| a.iter().filter_map(Value::as_i64).collect())
2075 .unwrap_or_default();
2076 wakes.retain(|t| now - t < 3600 && *t <= now);
2077 if wakes.len() >= WAKE_PER_HOUR {
2078 return Ok(Wake::Held("the hourly limit of wake-ups"));
2079 }
2080 if wakes.iter().any(|t| now - t < WAKE_COOLDOWN_SECS) {
2081 return Ok(Wake::Held("the cooldown between wake-ups"));
2082 }
2083 wakes.push(now);
2084 let delivered = Value::String(crate::memory::delivery::DELIVERED.into());
2085 for id in tasks.iter().chain(messages.iter()) {
2086 let mut m = self.get(id)?;
2087 m.metadata
2088 .insert(MNEMO_META_DELIVERY.into(), delivered.clone());
2089 self.put(m)?;
2090 }
2091 let w = Value::Array(wakes.into_iter().map(Value::from).collect());
2092 match presence {
2093 Some(mut m) => {
2094 m.metadata.insert(MNEMO_META_WAKES.into(), w);
2095 self.put(m)?;
2096 }
2097 None => {
2098 let mut meta = Map::new();
2099 meta.insert(MNEMO_META_AGENT.into(), Value::String(agent.to_string()));
2100 meta.insert(MNEMO_META_LAST_ACTIVE.into(), Value::from(0));
2101 meta.insert(MNEMO_META_PRESENCE_LOCK.into(), Value::Bool(false));
2102 meta.insert(MNEMO_META_WAKES.into(), w);
2103 self.put_coordination_with_id(
2104 Ulid::new(),
2105 MNEMO_META_KIND_PRESENCE,
2106 format!("presence {agent}"),
2107 meta,
2108 )?;
2109 }
2110 }
2111 Ok(Wake::Now {
2112 tasks: tasks.len(),
2113 messages: messages.len(),
2114 })
2115 }
2116}
2117
2118#[derive(Debug, Clone, PartialEq, Eq)]
2122pub struct Stale {
2123 pub id: Ulid,
2125 pub what: String,
2129 pub since: i64,
2131 pub text: String,
2133 pub whose: Option<String>,
2135 pub visibility: String,
2137}
2138
2139impl Mnemo {
2140 pub fn stale(&mut self) -> Result<Vec<Stale>> {
2147 use super::records::{ROW_KIND_ESSENCE, ROW_REVIEW};
2148 let now = self.coordination_now();
2149 let entries: Vec<CatalogEntry> = self
2150 .catalog
2151 .iter()
2152 .filter(|e| !e.deleted)
2153 .filter(|e| {
2154 e.v9.is_none_or(|r| {
2155 r.kind == ROW_KIND_ESSENCE
2156 || r.kind == ROW_KIND_COORDINATION
2157 || r.flags & ROW_REVIEW != 0
2158 })
2159 })
2160 .cloned()
2161 .collect();
2162 let mut out = Vec::new();
2163 for e in entries {
2164 let m = self.read_memory(&e)?;
2165 let Some(since) = crate::memory::stale_since(&m, now) else {
2166 continue;
2167 };
2168 let s = |k: &str| meta_string(&m, k);
2169 let kind = s(MNEMO_META_KIND);
2170 let what = match kind.as_deref() {
2171 Some("essence") => format!(
2172 "essence {}",
2173 s(crate::memory::MNEMO_META_SECTION).unwrap_or_default()
2174 ),
2175 Some(k @ ("task" | "message")) => {
2176 format!("{k} {}", s(MNEMO_META_STATUS).unwrap_or_default())
2177 }
2178 Some(k) => k.to_string(),
2179 None => "fact".to_string(),
2180 };
2181 let whose = match kind.as_deref() {
2182 Some("task") => s(MNEMO_META_OWNER),
2183 Some("message") => s(MNEMO_META_TO),
2184 _ => s(crate::memory::MNEMO_META_AUTHOR),
2185 };
2186 out.push(Stale {
2187 id: m.id,
2188 what,
2189 since,
2190 text: m.content.lines().next().unwrap_or("").to_string(),
2191 whose,
2192 visibility: crate::memory::visibility_of(&m).to_string(),
2193 });
2194 }
2195 out.sort_by_key(|x| (x.since, x.id.0));
2196 Ok(out)
2197 }
2198}
2199
2200#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2202pub struct KindCounts {
2203 pub facts: usize,
2205 pub turns: usize,
2207 pub essence: usize,
2209 pub coordination: usize,
2211}
2212
2213impl Mnemo {
2214 pub fn kind_counts(&self) -> KindCounts {
2218 use super::records::{ROW_KIND_ESSENCE, ROW_KIND_THREAD_LINK, ROW_KIND_TURN};
2219 let mut c = KindCounts::default();
2220 for e in self.catalog.iter().filter(|e| !e.deleted) {
2221 match e.v9.map(|r| r.kind) {
2222 Some(ROW_KIND_TURN | ROW_KIND_THREAD_LINK) => c.turns += 1,
2223 Some(ROW_KIND_ESSENCE) => c.essence += 1,
2224 Some(ROW_KIND_COORDINATION) => c.coordination += 1,
2225 _ => c.facts += 1,
2226 }
2227 }
2228 c
2229 }
2230}