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 is_sentinel(h: &[u16]) -> bool {
167 let Some(&first) = h.first() else {
168 return false;
169 };
170 let want = 1.0 / (h.len() as f32).sqrt();
171 h.iter().all(|&x| x == first) && (crate::veccol::f16_to_f32(first) - want).abs() < 1e-3
172}
173
174fn ready_seen_by(m: &Memory) -> Vec<String> {
177 m.metadata
178 .get(crate::memory::MNEMO_META_READY_SEEN_BY)
179 .and_then(Value::as_array)
180 .map(|a| {
181 a.iter()
182 .filter_map(|v| v.as_str().map(str::to_string))
183 .collect()
184 })
185 .unwrap_or_default()
186}
187
188fn add_seen_by(m: &mut Memory, agent: &str) -> bool {
190 let mut v = seen_by(m);
191 if v.iter().any(|a| a == agent) {
192 return false;
193 }
194 v.push(agent.to_string());
195 m.metadata.insert(
196 crate::memory::MNEMO_META_SEEN_BY.into(),
197 Value::Array(v.into_iter().map(Value::String).collect()),
198 );
199 true
200}
201
202impl Mnemo {
203 pub(super) fn coordination_records(
207 &mut self,
208 kind: &str,
209 locator: Option<&str>,
210 ) -> Result<Vec<Memory>> {
211 let want = locator.map(|l| locator_hash_of(kind, l));
212 let legacy = self.legacy_coordination_ids()?;
213 let entries: Vec<CatalogEntry> = self
214 .catalog
215 .iter()
216 .filter(|e| !e.deleted)
217 .filter(|e| {
218 legacy.contains(&e.id)
219 || e.v9.is_none_or(|r| {
220 r.kind == ROW_KIND_COORDINATION && want.is_none_or(|h| r.thread_hash == h)
221 })
222 })
223 .cloned()
224 .collect();
225 let mut out = Vec::new();
226 for e in entries {
227 let m = self.read_memory(&e)?;
228 if m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str) != Some(kind) {
229 continue;
230 }
231 if let Some(l) = locator {
232 if locator_of(&m) != Some(l) {
233 continue;
234 }
235 }
236 out.push(m);
237 }
238 Ok(out)
239 }
240
241 fn legacy_coordination_ids(&mut self) -> Result<std::collections::HashSet<u128>> {
249 if let Some(ids) = &self.legacy_coordination {
250 return Ok(ids.clone());
251 }
252 let episodic = super::records::memory_type_code(MemoryType::Episodic);
253 let candidates: Vec<CatalogEntry> = self
254 .catalog
255 .iter()
256 .filter(|e| !e.deleted)
257 .filter(|e| {
258 e.v9.is_some_and(|r| {
259 r.kind == super::records::ROW_KIND_FACT && r.memory_type == episodic
260 })
261 })
262 .cloned()
263 .collect();
264 let mut ids = std::collections::HashSet::new();
265 let mut pages: std::collections::HashMap<(u64, u64), Option<Vec<u8>>> =
267 std::collections::HashMap::new();
268 for e in candidates {
269 let vector = match e.v9 {
270 Some(r) if r.vec_page != 0 && !self.has_hot_vector(&e) => {
271 let page = pages
272 .entry((r.vec_page, r.vec_gen))
273 .or_insert_with(|| self.pager.read_page(r.vec_page, r.vec_gen).ok());
274 page.as_ref().and_then(|p| {
275 crate::veccol::decode_entry(p, self.dimensions, r.vec_slot as usize).ok()
276 })
277 }
278 _ => self.column_entry(&e).ok(),
279 };
280 if matches!(vector, Some((h, _)) if !is_sentinel(&h)) {
281 continue;
282 }
283 if is_coordination(&self.read_memory(&e)?) {
284 ids.insert(e.id);
285 }
286 }
287 self.legacy_coordination = Some(ids.clone());
288 Ok(ids)
289 }
290
291 pub fn mistagged_coordination(&mut self) -> Result<usize> {
295 let ids = self.legacy_coordination_ids()?;
296 Ok(self
297 .catalog
298 .iter()
299 .filter(|e| !e.deleted && ids.contains(&e.id))
300 .filter(|e| {
301 e.v9.is_some_and(|r| r.kind == super::records::ROW_KIND_FACT)
302 })
303 .count())
304 }
305
306 fn messages(&mut self) -> Result<Vec<Memory>> {
308 let mut out = self.coordination_records(crate::memory::MNEMO_META_KIND_MESSAGE, None)?;
309 out.sort_by_key(|m| m.created_at);
312 Ok(out)
313 }
314
315 #[allow(clippy::too_many_arguments)]
327 pub fn post(
328 &mut self,
329 to: &str,
330 subject: &str,
331 body: &str,
332 refs: &[String],
333 conversation: Option<&str>,
334 from: Option<&str>,
335 from_role: Option<&str>,
336 ) -> Result<Message> {
337 if self.read_only {
338 return Err(MnemoError::ReadOnly);
339 }
340 if !valid_address(to) {
341 return Err(MnemoError::Invalid(format!(
342 "{to:?} isn't an address: an agent id, role:<role>, or all"
343 )));
344 }
345 let subject = subject.trim();
346 if subject.is_empty() || subject.contains('\n') {
347 return Err(MnemoError::Invalid(
348 "a message's subject is one line, and not empty".into(),
349 ));
350 }
351 if subject.len() > crate::memory::MESSAGE_SUBJECT_MAX {
352 return Err(MnemoError::Invalid(format!(
353 "a message's subject is at most {} bytes",
354 crate::memory::MESSAGE_SUBJECT_MAX
355 )));
356 }
357 if body.len() > crate::memory::MESSAGE_BODY_MAX {
358 return Err(MnemoError::Invalid(format!(
359 "a message's body is at most {} bytes; put a longer one in a fact and send its id \
360 in refs",
361 crate::memory::MESSAGE_BODY_MAX
362 )));
363 }
364 let from = from
365 .map(str::to_string)
366 .or_else(|| self.author.clone())
367 .unwrap_or_else(|| "anonymous".to_string());
368 let now = memory::now_secs();
369 let earlier: Vec<Message> = self
370 .messages()?
371 .iter()
372 .filter_map(Message::from_memory)
373 .collect();
374 let mut hops = 0u64;
375 if let Some(c) = conversation {
376 if let Some(h) = earlier
377 .iter()
378 .filter(|m| m.conversation == c)
379 .map(|m| m.hops)
380 .max()
381 {
382 hops = h + 1;
383 }
384 }
385 if let Some(h) = earlier
388 .iter()
389 .filter(|m| now - m.created_at <= crate::memory::MESSAGE_PAIR_CARRY_SECS)
390 .filter(|m| (m.from == from && m.to == to) || (m.from == to && m.to == from))
391 .map(|m| m.hops)
392 .max()
393 {
394 hops = hops.max(h + 1);
395 }
396 let id = Ulid::new();
397 let conversation = conversation
398 .map(str::to_string)
399 .unwrap_or_else(|| id.to_string());
400 let mut meta = Map::new();
401 meta.insert(MNEMO_META_TO.into(), Value::String(to.into()));
402 meta.insert(MNEMO_META_FROM.into(), Value::String(from));
403 if let Some(r) = from_role {
404 meta.insert("_mnemo.from_role".into(), Value::String(r.to_string()));
405 }
406 meta.insert(MNEMO_META_CONVERSATION.into(), Value::String(conversation));
407 meta.insert(MNEMO_META_HOPS.into(), Value::from(hops));
408 meta.insert(
409 MNEMO_META_REFS.into(),
410 Value::Array(refs.iter().map(|r| Value::String(r.clone())).collect()),
411 );
412 meta.insert(
413 MNEMO_META_STATUS.into(),
414 Value::String(crate::memory::MESSAGE_UNREAD.into()),
415 );
416 meta.insert(
417 MNEMO_META_DELIVERY.into(),
418 Value::String(crate::memory::delivery::SENT.into()),
419 );
420 let content = if body.is_empty() {
421 subject.to_string()
422 } else {
423 format!("{subject}\n\n{body}")
424 };
425 let id = self.put_coordination_with_id(
426 id,
427 crate::memory::MNEMO_META_KIND_MESSAGE,
428 content,
429 meta,
430 )?;
431 let m = self.get(&id)?;
432 Ok(Message::from_memory(&m).expect("just written"))
433 }
434
435 pub fn inbox(
440 &mut self,
441 agent: Option<&str>,
442 role: Option<&str>,
443 unread_only: bool,
444 ) -> Result<Vec<Message>> {
445 self.inbox_in(
446 agent,
447 role,
448 unread_only,
449 crate::memory::VisibilitySet::DEFAULT,
450 )
451 }
452
453 pub fn inbox_in(
456 &mut self,
457 agent: Option<&str>,
458 role: Option<&str>,
459 unread_only: bool,
460 visibility: crate::memory::VisibilitySet,
461 ) -> Result<Vec<Message>> {
462 Ok(self
463 .messages()?
464 .iter()
465 .filter(|m| visibility.shows(m))
466 .filter_map(Message::from_memory)
467 .filter(|m| m.is_for(agent, role))
468 .filter(|m| !unread_only || m.status == crate::memory::MESSAGE_UNREAD)
469 .collect())
470 }
471
472 pub fn mark_seen(&mut self, ids: &[Ulid]) -> Result<usize> {
475 if self.read_only {
476 return Err(MnemoError::ReadOnly);
477 }
478 let mut changed = 0;
479 for id in ids {
480 let mut m = self.get(id)?;
481 let Some(msg) = Message::from_memory(&m) else {
482 continue;
483 };
484 let mut dirty = false;
485 if msg.delivery == crate::memory::delivery::SENT
486 || msg.delivery == crate::memory::delivery::DELIVERED
487 {
488 m.metadata.insert(
489 MNEMO_META_DELIVERY.into(),
490 Value::String(crate::memory::delivery::SEEN.into()),
491 );
492 dirty = true;
493 }
494 if msg.to == "all" || msg.to.starts_with("role:") {
497 if let Some(a) = self.author.clone() {
498 dirty |= add_seen_by(&mut m, &a);
499 }
500 }
501 if dirty {
502 self.put(m)?;
503 changed += 1;
504 }
505 }
506 Ok(changed)
507 }
508
509 pub fn ack(&mut self, id: &Ulid, note: Option<&str>, by: Option<&str>) -> Result<WriteOutcome> {
514 if self.read_only {
515 return Err(MnemoError::ReadOnly);
516 }
517 let mut m = self.get(id)?;
518 let Some(msg) = Message::from_memory(&m) else {
519 return Err(MnemoError::Invalid(format!("{id} isn't a message")));
520 };
521 if msg.status == crate::memory::MESSAGE_ACKED {
522 return Ok(WriteOutcome::Unchanged);
523 }
524 let now = memory::now_secs();
525 let by = by
526 .map(str::to_string)
527 .or_else(|| self.author.clone())
528 .unwrap_or_else(|| "anonymous".to_string());
529 let mut entry = Map::new();
530 entry.insert("from".into(), Value::String(msg.status.clone()));
531 entry.insert(
532 "to".into(),
533 Value::String(crate::memory::MESSAGE_ACKED.into()),
534 );
535 entry.insert("at".into(), Value::from(now));
536 entry.insert("by".into(), Value::String(by));
537 if let Some(n) = note {
538 entry.insert("note".into(), Value::String(n.to_string()));
539 }
540 let mut history = m
541 .metadata
542 .get(MNEMO_META_STATUS_HISTORY)
543 .and_then(Value::as_array)
544 .cloned()
545 .unwrap_or_default();
546 history.push(Value::Object(entry));
547 m.metadata
548 .insert(MNEMO_META_STATUS_HISTORY.into(), Value::Array(history));
549 m.metadata.insert(
550 MNEMO_META_STATUS.into(),
551 Value::String(crate::memory::MESSAGE_ACKED.into()),
552 );
553 m.metadata.insert(
554 MNEMO_META_DELIVERY.into(),
555 Value::String(crate::memory::delivery::DONE.into()),
556 );
557 m.metadata
558 .insert(MNEMO_META_ACKED_AT.into(), Value::from(now));
559 self.put(m)?;
560 Ok(WriteOutcome::Updated)
561 }
562
563 pub fn prune_messages(&mut self, older_than_secs: i64) -> Result<usize> {
567 if self.read_only {
568 return Err(MnemoError::ReadOnly);
569 }
570 let now = memory::now_secs();
571 let old: Vec<Ulid> = self
572 .messages()?
573 .iter()
574 .filter_map(Message::from_memory)
575 .filter(|m| prunable(m, now, older_than_secs))
576 .map(|m| m.id)
577 .collect();
578 for id in &old {
579 self.delete(id)?;
580 }
581 Ok(old.len())
582 }
583}
584
585fn prunable(m: &Message, now: i64, keep: i64) -> bool {
587 m.status == crate::memory::MESSAGE_ACKED && m.acked_at.is_some_and(|t| now - t > keep)
588}
589
590pub(super) fn compact_drops(m: &Memory, now: i64) -> bool {
593 Message::from_memory(m)
594 .is_some_and(|msg| prunable(&msg, now, crate::memory::MESSAGE_ACKED_KEEP_SECS))
595}
596
597use crate::memory::{
600 CLAIM_LAPSE_GRACE_SECS, CLAIM_TOPIC_MAX, CLAIM_TTL_DEFAULT, CLAIM_TTL_MAX, CLAIM_TTL_MIN,
601 MNEMO_META_AGENT, MNEMO_META_CLAIM_TOKEN, MNEMO_META_DEAD_SEEN_AT, MNEMO_META_EXPIRES_AT,
602 MNEMO_META_HOLDER, MNEMO_META_HOLDER_LOCK, MNEMO_META_KIND_CLAIM, MNEMO_META_KIND_PRESENCE,
603 MNEMO_META_LAST_ACTIVE, MNEMO_META_LEASE, MNEMO_META_PRESENCE_LOCK, MNEMO_META_TOOL,
604 MNEMO_META_TOPIC, PRESENCE_EVERY_SECS,
605};
606
607fn locator_of(m: &Memory) -> Option<&str> {
609 let key = match m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str)? {
610 MNEMO_META_KIND_CLAIM => MNEMO_META_TOPIC,
611 MNEMO_META_KIND_PRESENCE => MNEMO_META_AGENT,
612 crate::memory::MNEMO_META_KIND_TASK => crate::memory::MNEMO_META_SLUG,
613 crate::memory::MNEMO_META_KIND_FINDING => crate::memory::MNEMO_META_FINDING_ID,
614 _ => return None,
615 };
616 m.metadata.get(key).and_then(Value::as_str)
617}
618
619fn locator_hash_of(kind: &str, locator: &str) -> u32 {
620 super::records::fnv1a32(&[b"_mnemo.coordination", kind.as_bytes(), locator.as_bytes()])
621}
622
623pub(super) fn locator_hash(m: &Memory) -> u32 {
627 match (
628 m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str),
629 locator_of(m),
630 ) {
631 (Some(kind), Some(l)) => locator_hash_of(kind, l),
632 _ => 0,
633 }
634}
635
636#[derive(Debug, Clone, PartialEq, Eq)]
638pub enum ClaimOutcome {
639 Claimed {
642 token: String,
644 expires_at: i64,
646 },
647 HeldBy {
649 agent: String,
651 expires_at: i64,
653 },
654}
655
656#[derive(Debug, Clone, Copy, PartialEq, Eq)]
658pub enum ClaimStatus {
659 Held {
661 expires_at: i64,
663 },
664 Released,
666 Lost,
670}
671
672#[derive(Debug, Clone, PartialEq, Eq)]
674pub struct Claim {
675 pub topic: String,
677 pub holder: String,
679 pub expires_at: i64,
681 pub lease: i64,
683}
684
685#[derive(Debug, Clone, Copy, PartialEq, Eq)]
687pub enum Alive {
688 Yes,
690 No,
692 Unknown,
695}
696
697#[derive(Debug, Clone, PartialEq, Eq)]
699pub struct Presence {
700 pub agent: String,
702 pub role: Option<String>,
704 pub tool: Option<String>,
706 pub last_active: i64,
708 pub alive: Alive,
710 pub claims: Vec<String>,
712}
713
714fn meta_i64(m: &Memory, k: &str) -> Option<i64> {
715 m.metadata.get(k).and_then(Value::as_i64)
716}
717
718fn meta_string(m: &Memory, k: &str) -> Option<String> {
719 m.metadata
720 .get(k)
721 .and_then(Value::as_str)
722 .map(str::to_string)
723}
724
725fn effective_expiry(m: &Memory, now: i64) -> Option<i64> {
728 let token = m
729 .metadata
730 .get(MNEMO_META_CLAIM_TOKEN)
731 .and_then(Value::as_str)?;
732 if token.is_empty() {
733 return None;
734 }
735 let expires = meta_i64(m, MNEMO_META_EXPIRES_AT)?;
736 let lease = meta_i64(m, MNEMO_META_LEASE).unwrap_or(CLAIM_TTL_DEFAULT);
737 Some(expires.min(now.saturating_add(lease)))
738}
739
740fn is_live(m: &Memory, now: i64) -> bool {
742 effective_expiry(m, now).is_some_and(|e| now < e)
743}
744
745fn new_token() -> String {
746 format!(
747 "{:016x}{:016x}",
748 crate::crypto::random_u64(),
749 crate::crypto::random_u64()
750 )
751}
752
753fn check_topic(topic: &str) -> Result<()> {
754 if topic.trim().is_empty() || topic.contains('\n') || topic.len() > CLAIM_TOPIC_MAX {
755 return Err(MnemoError::Invalid(format!(
756 "a claim's topic is one line, not empty, at most {CLAIM_TOPIC_MAX} bytes"
757 )));
758 }
759 Ok(())
760}
761
762fn check_ttl(ttl: Option<i64>) -> Result<i64> {
763 let t = ttl.unwrap_or(CLAIM_TTL_DEFAULT);
764 if !(CLAIM_TTL_MIN..=CLAIM_TTL_MAX).contains(&t) {
765 return Err(MnemoError::Invalid(format!(
766 "a claim's ttl is {CLAIM_TTL_MIN} s to {CLAIM_TTL_MAX} s (24 h); got {t}"
767 )));
768 }
769 Ok(t)
770}
771
772impl Mnemo {
773 pub fn coordination_now(&self) -> i64 {
776 #[cfg(feature = "dev-hooks")]
777 let env: i64 = std::env::var("MNEMO_DEV_CLOCK_OFFSET")
778 .ok()
779 .and_then(|v| v.parse().ok())
780 .unwrap_or(0);
781 #[cfg(not(feature = "dev-hooks"))]
782 let env: i64 = 0;
783 memory::now_secs() + self.clock_offset + env
784 }
785
786 #[cfg(feature = "dev-hooks")]
789 #[doc(hidden)]
790 pub fn __set_clock_offset_for_testing(&mut self, secs: i64) {
791 self.clock_offset = secs;
792 }
793
794 fn claim_agent(&self) -> Result<String> {
795 self.author.clone().ok_or_else(|| {
796 MnemoError::Invalid(
797 "a claim needs an agent: set MNEMO_AGENT (or --as), or call set_author".into(),
798 )
799 })
800 }
801
802 fn find_claim(&mut self, topic: &str) -> Result<Option<Memory>> {
803 Ok(self
804 .coordination_records(MNEMO_META_KIND_CLAIM, Some(topic))?
805 .into_iter()
806 .next())
807 }
808
809 pub fn claim(&mut self, topic: &str, ttl: Option<i64>) -> Result<ClaimOutcome> {
824 if self.read_only {
825 return Err(MnemoError::ReadOnly);
826 }
827 check_topic(topic)?;
828 let ttl = check_ttl(ttl)?;
829 let agent = self.claim_agent()?;
830 let now = self.coordination_now();
831 let existing = self.find_claim(topic)?;
832 if let Some(mut m) = existing.clone() {
833 if is_live(&m, now) {
834 let holder = meta_string(&m, MNEMO_META_HOLDER).unwrap_or_default();
835 let expires = effective_expiry(&m, now).unwrap_or(now);
836 let mut changed = false;
837 let mut lapse = false;
838 let had_lock = m
839 .metadata
840 .get(MNEMO_META_HOLDER_LOCK)
841 .and_then(Value::as_bool)
842 .unwrap_or(false);
843 if had_lock && holder != agent {
844 match crate::shared::probe_presence_once(&self.path, &holder) {
845 Some(false) => match meta_i64(&m, MNEMO_META_DEAD_SEEN_AT) {
846 Some(t) if now - t >= CLAIM_LAPSE_GRACE_SECS => lapse = true,
847 Some(_) => {}
848 None => {
849 m.metadata
850 .insert(MNEMO_META_DEAD_SEEN_AT.into(), Value::from(now));
851 changed = true;
852 }
853 },
854 _ => {
855 changed |= m.metadata.remove(MNEMO_META_DEAD_SEEN_AT).is_some();
856 }
857 }
858 }
859 if !lapse {
860 if meta_i64(&m, MNEMO_META_EXPIRES_AT) != Some(expires) {
863 m.metadata
864 .insert(MNEMO_META_EXPIRES_AT.into(), Value::from(expires));
865 changed = true;
866 }
867 if changed {
868 self.put(m)?;
869 }
870 return Ok(ClaimOutcome::HeldBy {
871 agent: holder,
872 expires_at: expires,
873 });
874 }
875 }
876 }
877 let token = new_token();
878 let expires_at = now + ttl;
879 let mut meta = existing
880 .as_ref()
881 .map(|m| m.metadata.clone())
882 .unwrap_or_default();
883 meta.remove(MNEMO_META_DEAD_SEEN_AT);
884 meta.insert(MNEMO_META_TOPIC.into(), Value::String(topic.to_string()));
885 meta.insert(MNEMO_META_HOLDER.into(), Value::String(agent));
886 meta.insert(MNEMO_META_CLAIM_TOKEN.into(), Value::String(token.clone()));
887 meta.insert(MNEMO_META_EXPIRES_AT.into(), Value::from(expires_at));
888 meta.insert(MNEMO_META_LEASE.into(), Value::from(ttl));
889 meta.insert(
890 MNEMO_META_HOLDER_LOCK.into(),
891 Value::Bool(self.presence_held),
892 );
893 match existing {
894 Some(mut m) => {
895 m.metadata = meta;
896 self.put(m)?;
897 }
898 None => {
899 self.put_coordination_with_id(
900 Ulid::new(),
901 MNEMO_META_KIND_CLAIM,
902 format!("claim {topic}"),
903 meta,
904 )?;
905 }
906 }
907 Ok(ClaimOutcome::Claimed { token, expires_at })
908 }
909
910 pub fn renew(&mut self, topic: &str, token: &str, ttl: Option<i64>) -> Result<ClaimStatus> {
913 if self.read_only {
914 return Err(MnemoError::ReadOnly);
915 }
916 let now = self.coordination_now();
917 let Some(mut m) = self.find_claim(topic)? else {
918 return Ok(ClaimStatus::Lost);
919 };
920 if !is_live(&m, now) || meta_string(&m, MNEMO_META_CLAIM_TOKEN).as_deref() != Some(token) {
921 return Ok(ClaimStatus::Lost);
922 }
923 let lease = match ttl {
924 Some(t) => check_ttl(Some(t))?,
925 None => meta_i64(&m, MNEMO_META_LEASE).unwrap_or(CLAIM_TTL_DEFAULT),
926 };
927 let expires_at = now + lease;
928 m.metadata
929 .insert(MNEMO_META_EXPIRES_AT.into(), Value::from(expires_at));
930 m.metadata
931 .insert(MNEMO_META_LEASE.into(), Value::from(lease));
932 m.metadata.remove(MNEMO_META_DEAD_SEEN_AT);
933 self.put(m)?;
934 Ok(ClaimStatus::Held { expires_at })
935 }
936
937 pub fn release(&mut self, topic: &str, token: &str) -> Result<ClaimStatus> {
940 if self.read_only {
941 return Err(MnemoError::ReadOnly);
942 }
943 let now = self.coordination_now();
944 let Some(mut m) = self.find_claim(topic)? else {
945 return Ok(ClaimStatus::Lost);
946 };
947 if !is_live(&m, now) || meta_string(&m, MNEMO_META_CLAIM_TOKEN).as_deref() != Some(token) {
948 return Ok(ClaimStatus::Lost);
949 }
950 m.metadata.remove(MNEMO_META_CLAIM_TOKEN);
951 m.metadata.remove(MNEMO_META_DEAD_SEEN_AT);
952 m.metadata
953 .insert(MNEMO_META_EXPIRES_AT.into(), Value::from(now));
954 self.put(m)?;
955 Ok(ClaimStatus::Released)
956 }
957
958 pub fn check_claim(&mut self, topic: &str, token: &str) -> Result<ClaimStatus> {
961 let now = self.coordination_now();
962 let Some(m) = self.find_claim(topic)? else {
963 return Ok(ClaimStatus::Lost);
964 };
965 if meta_string(&m, MNEMO_META_CLAIM_TOKEN).as_deref() != Some(token) {
966 return Ok(ClaimStatus::Lost);
967 }
968 match effective_expiry(&m, now) {
969 Some(e) if now < e => Ok(ClaimStatus::Held { expires_at: e }),
970 _ => Ok(ClaimStatus::Lost),
971 }
972 }
973
974 pub fn claims(&mut self) -> Result<Vec<Claim>> {
976 let now = self.coordination_now();
977 let mut out: Vec<Claim> = self
978 .coordination_records(MNEMO_META_KIND_CLAIM, None)?
979 .iter()
980 .filter(|m| is_live(m, now))
981 .map(|m| Claim {
982 topic: meta_string(m, MNEMO_META_TOPIC).unwrap_or_default(),
983 holder: meta_string(m, MNEMO_META_HOLDER).unwrap_or_default(),
984 expires_at: effective_expiry(m, now).unwrap_or(now),
985 lease: meta_i64(m, MNEMO_META_LEASE).unwrap_or(CLAIM_TTL_DEFAULT),
986 })
987 .collect();
988 out.sort_by(|a, b| a.topic.cmp(&b.topic));
989 Ok(out)
990 }
991
992 pub fn touch_presence(&mut self, role: Option<&str>, tool: Option<&str>) -> Result<bool> {
999 if self.read_only {
1000 return Err(MnemoError::ReadOnly);
1001 }
1002 let Some(agent) = self.author.clone() else {
1003 return Ok(false);
1004 };
1005 let now = self.coordination_now();
1006 let existing = self
1007 .coordination_records(MNEMO_META_KIND_PRESENCE, Some(&agent))?
1008 .into_iter()
1009 .next();
1010 let role_v = role.map(|r| Value::String(r.to_string()));
1011 let tool_v = tool.map(|t| Value::String(t.to_string()));
1012 let defer = !self.presence_held
1016 && existing.as_ref().is_some_and(|m| {
1017 m.metadata
1018 .get(MNEMO_META_PRESENCE_LOCK)
1019 .and_then(Value::as_bool)
1020 .unwrap_or(false)
1021 });
1022 if let Some(m) = &existing {
1023 let fresh = meta_i64(m, MNEMO_META_LAST_ACTIVE)
1024 .is_some_and(|t| now >= t && now - t < PRESENCE_EVERY_SECS);
1025 let same = defer
1026 || (m.metadata.get(crate::memory::MNEMO_META_ROLE) == role_v.as_ref()
1027 && m.metadata.get(MNEMO_META_TOOL) == tool_v.as_ref()
1028 && m.metadata
1029 .get(MNEMO_META_PRESENCE_LOCK)
1030 .and_then(Value::as_bool)
1031 == Some(self.presence_held));
1032 if fresh && same {
1033 return Ok(false);
1034 }
1035 }
1036 if defer {
1037 let mut m = existing.expect("checked");
1038 m.metadata
1039 .insert(MNEMO_META_LAST_ACTIVE.into(), Value::from(now));
1040 self.put(m)?;
1041 return Ok(true);
1042 }
1043 let mut meta = existing
1044 .as_ref()
1045 .map(|m| m.metadata.clone())
1046 .unwrap_or_default();
1047 meta.insert(MNEMO_META_AGENT.into(), Value::String(agent.clone()));
1048 for (k, v) in [
1049 (crate::memory::MNEMO_META_ROLE, role_v),
1050 (MNEMO_META_TOOL, tool_v),
1051 ] {
1052 match v {
1053 Some(v) => {
1054 meta.insert(k.into(), v);
1055 }
1056 None => {
1057 meta.remove(k);
1058 }
1059 }
1060 }
1061 meta.insert(MNEMO_META_LAST_ACTIVE.into(), Value::from(now));
1062 meta.insert(
1063 MNEMO_META_PRESENCE_LOCK.into(),
1064 Value::Bool(self.presence_held),
1065 );
1066 match existing {
1067 Some(mut m) => {
1068 m.metadata = meta;
1069 self.put(m)?;
1070 }
1071 None => {
1072 self.put_coordination_with_id(
1073 Ulid::new(),
1074 MNEMO_META_KIND_PRESENCE,
1075 format!("presence {agent}"),
1076 meta,
1077 )?;
1078 }
1079 }
1080 Ok(true)
1081 }
1082
1083 pub fn who(&mut self) -> Result<Vec<Presence>> {
1088 let claims = self.claims()?;
1089 let records = self.coordination_records(MNEMO_META_KIND_PRESENCE, None)?;
1090 let mut out: Vec<Presence> = records
1091 .iter()
1092 .map(|m| {
1093 let agent = meta_string(m, MNEMO_META_AGENT).unwrap_or_default();
1094 let locked = m
1095 .metadata
1096 .get(MNEMO_META_PRESENCE_LOCK)
1097 .and_then(Value::as_bool)
1098 .unwrap_or(false);
1099 let alive = if !locked {
1100 Alive::Unknown
1101 } else {
1102 match crate::shared::probe_presence(&self.path, &agent) {
1103 Some(true) => Alive::Yes,
1104 Some(false) => Alive::No,
1105 None => Alive::Unknown,
1106 }
1107 };
1108 Presence {
1109 claims: claims
1110 .iter()
1111 .filter(|c| c.holder == agent)
1112 .map(|c| c.topic.clone())
1113 .collect(),
1114 role: meta_string(m, crate::memory::MNEMO_META_ROLE),
1115 tool: meta_string(m, MNEMO_META_TOOL),
1116 last_active: meta_i64(m, MNEMO_META_LAST_ACTIVE).unwrap_or(0),
1117 alive,
1118 agent,
1119 }
1120 })
1121 .collect();
1122 out.sort_by(|a, b| {
1123 b.last_active
1124 .cmp(&a.last_active)
1125 .then(a.agent.cmp(&b.agent))
1126 });
1127 Ok(out)
1128 }
1129}
1130
1131use crate::memory::{
1134 task_status, MNEMO_META_AFTER, MNEMO_META_CREATOR, MNEMO_META_KIND_TASK, MNEMO_META_OWNER,
1135 MNEMO_META_PRE_APPROVED, MNEMO_META_SLUG, TASK_CLAIM_TTL, TASK_SLUG_MAX, TASK_TRANSITIONS,
1136};
1137
1138#[derive(Debug, Clone, Default, PartialEq, Eq)]
1140pub struct TaskSpec {
1141 pub title: String,
1143 pub body: String,
1145 pub role: Option<String>,
1147 pub after: Vec<String>,
1149 pub pre_approved: bool,
1151 pub slug: Option<String>,
1153 pub refs: Vec<String>,
1156}
1157
1158const TASK_REFS_MAX: usize = 32;
1160const TASK_REF_MAX: usize = 200;
1161
1162#[derive(Debug, Clone, PartialEq)]
1164pub struct Task {
1165 pub id: Ulid,
1167 pub slug: String,
1169 pub title: String,
1171 pub body: String,
1173 pub role: Option<String>,
1175 pub status: String,
1177 pub owner: Option<String>,
1179 pub creator: String,
1181 pub after: Vec<String>,
1183 pub pre_approved: bool,
1185 pub refs: Vec<String>,
1187 pub created_at: i64,
1189 pub history: Vec<Value>,
1192}
1193
1194impl Task {
1195 pub fn from_memory(m: &Memory) -> Option<Task> {
1197 if m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str) != Some(MNEMO_META_KIND_TASK) {
1198 return None;
1199 }
1200 let (title, body) = match m.content.split_once("\n\n") {
1201 Some((a, b)) => (a.to_string(), b.to_string()),
1202 None => (m.content.clone(), String::new()),
1203 };
1204 Some(Task {
1205 id: m.id,
1206 slug: meta_string(m, MNEMO_META_SLUG).unwrap_or_default(),
1207 title,
1208 body,
1209 role: meta_string(m, crate::memory::MNEMO_META_ROLE),
1210 status: meta_string(m, MNEMO_META_STATUS).unwrap_or_default(),
1211 owner: meta_string(m, MNEMO_META_OWNER),
1212 creator: meta_string(m, MNEMO_META_CREATOR).unwrap_or_default(),
1213 after: m
1214 .metadata
1215 .get(MNEMO_META_AFTER)
1216 .and_then(Value::as_array)
1217 .map(|a| {
1218 a.iter()
1219 .filter_map(|v| v.as_str().map(str::to_string))
1220 .collect()
1221 })
1222 .unwrap_or_default(),
1223 pre_approved: m
1224 .metadata
1225 .get(MNEMO_META_PRE_APPROVED)
1226 .and_then(Value::as_bool)
1227 .unwrap_or(false),
1228 refs: m
1229 .metadata
1230 .get(crate::memory::MNEMO_META_REFS)
1231 .and_then(Value::as_array)
1232 .map(|a| {
1233 a.iter()
1234 .filter_map(|v| v.as_str().map(str::to_string))
1235 .collect()
1236 })
1237 .unwrap_or_default(),
1238 created_at: m.created_at,
1239 history: m
1240 .metadata
1241 .get(MNEMO_META_STATUS_HISTORY)
1242 .and_then(Value::as_array)
1243 .cloned()
1244 .unwrap_or_default(),
1245 })
1246 }
1247
1248 fn for_role(&self, role: Option<&str>) -> bool {
1251 self.role.is_none() || self.role.as_deref() == role
1252 }
1253}
1254
1255#[derive(Debug, Clone, PartialEq)]
1257pub struct TaskTaken {
1258 pub task: Task,
1260 pub token: String,
1263 pub expires_at: i64,
1265 pub reclaimed_from: Option<String>,
1267}
1268
1269#[derive(Debug, Clone, PartialEq, Eq)]
1272pub struct TaskClaim {
1273 pub token: String,
1275 pub expires_at: i64,
1277 pub retaken: bool,
1280}
1281
1282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1284pub enum TaskLost {
1285 TakenBack,
1287 OtherToken,
1290}
1291
1292#[derive(Debug, Clone, PartialEq)]
1294pub enum TaskOutcome {
1295 Updated(Box<Task>, Option<TaskClaim>),
1299 Lost(TaskLost),
1301}
1302
1303pub fn slug_of(title: &str) -> String {
1306 let mut out = String::new();
1307 for c in title.chars() {
1308 if c.is_ascii_alphanumeric() {
1309 out.push(c.to_ascii_lowercase());
1310 } else if !out.ends_with('-') && !out.is_empty() {
1311 out.push('-');
1312 }
1313 if out.len() >= TASK_SLUG_MAX {
1314 break;
1315 }
1316 }
1317 out.trim_end_matches('-').to_string()
1318}
1319
1320fn valid_slug(s: &str) -> bool {
1321 !s.is_empty()
1322 && s.len() <= TASK_SLUG_MAX
1323 && s.bytes()
1324 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b))
1325}
1326
1327fn task_topic(slug: &str) -> String {
1328 format!("task:{slug}")
1329}
1330
1331impl Mnemo {
1332 fn task_records(&mut self, slug: Option<&str>) -> Result<Vec<Memory>> {
1333 let mut v = self.coordination_records(MNEMO_META_KIND_TASK, slug)?;
1334 v.sort_by_key(|m| m.created_at);
1335 Ok(v)
1336 }
1337
1338 fn task_record(&mut self, slug: &str) -> Result<Option<Memory>> {
1339 Ok(self.task_records(Some(slug))?.into_iter().next())
1340 }
1341
1342 pub fn task(&mut self, slug: &str) -> Result<Option<Task>> {
1344 Ok(self.task_record(slug)?.as_ref().and_then(Task::from_memory))
1345 }
1346
1347 pub fn tasks(&mut self, status: Option<&str>, role: Option<&str>) -> Result<Vec<Task>> {
1350 Ok(self
1351 .task_records(None)?
1352 .iter()
1353 .filter_map(Task::from_memory)
1354 .filter(|t| status.is_none_or(|s| t.status == s))
1355 .filter(|t| role.is_none() || t.for_role(role))
1356 .collect())
1357 }
1358
1359 pub fn ready_tasks(&mut self, role: Option<&str>) -> Result<Vec<Task>> {
1362 let all: Vec<Task> = self
1363 .task_records(None)?
1364 .iter()
1365 .filter_map(Task::from_memory)
1366 .collect();
1367 let done: std::collections::HashSet<&str> = all
1368 .iter()
1369 .filter(|t| t.status == task_status::DONE)
1370 .map(|t| t.slug.as_str())
1371 .collect();
1372 Ok(all
1373 .iter()
1374 .filter(|t| t.status == task_status::QUEUED && t.for_role(role))
1375 .filter(|t| t.after.iter().all(|a| done.contains(a.as_str())))
1376 .cloned()
1377 .collect())
1378 }
1379
1380 pub fn task_add(&mut self, spec: &TaskSpec) -> Result<(Task, WriteOutcome)> {
1386 if self.read_only {
1387 return Err(MnemoError::ReadOnly);
1388 }
1389 let title = spec.title.trim();
1390 if title.is_empty()
1391 || title.contains('\n')
1392 || title.len() > crate::memory::MESSAGE_SUBJECT_MAX
1393 {
1394 return Err(MnemoError::Invalid(format!(
1395 "a task's title is one line, not empty, at most {} bytes",
1396 crate::memory::MESSAGE_SUBJECT_MAX
1397 )));
1398 }
1399 if spec.body.len() > crate::memory::MESSAGE_BODY_MAX {
1400 return Err(MnemoError::Invalid(format!(
1401 "a task's body is at most {} bytes; put more in a fact and name it",
1402 crate::memory::MESSAGE_BODY_MAX
1403 )));
1404 }
1405 let slug = match &spec.slug {
1406 Some(s) => s.clone(),
1407 None => slug_of(title),
1408 };
1409 if !valid_slug(&slug) {
1410 return Err(MnemoError::Invalid(format!(
1411 "{slug:?} isn't a slug: 1 to {TASK_SLUG_MAX} of a-z, 0-9, '.', '_' and '-' \
1412 (give one with --slug)"
1413 )));
1414 }
1415 if let Some(r) = &spec.role {
1416 if !crate::memory::valid_agent_id(r) {
1417 return Err(MnemoError::Invalid(format!("{r:?} isn't a role")));
1418 }
1419 }
1420 if spec.refs.len() > TASK_REFS_MAX
1421 || spec
1422 .refs
1423 .iter()
1424 .any(|r| r.trim().is_empty() || r.contains('\n') || r.len() > TASK_REF_MAX)
1425 {
1426 return Err(MnemoError::Invalid(format!(
1427 "a task's refs: at most {TASK_REFS_MAX}, each one line, not empty, at most \
1428 {TASK_REF_MAX} bytes"
1429 )));
1430 }
1431 for a in &spec.after {
1432 if a == &slug {
1433 return Err(MnemoError::Invalid("a task can't wait for itself".into()));
1434 }
1435 if self.task_record(a)?.is_none() {
1436 return Err(MnemoError::Invalid(format!("after: no task {a:?}")));
1437 }
1438 }
1439 let content = if spec.body.is_empty() {
1440 title.to_string()
1441 } else {
1442 format!("{title}\n\n{}", spec.body)
1443 };
1444 let set = |meta: &mut Map<String, Value>| {
1445 match &spec.role {
1446 Some(r) => {
1447 meta.insert(
1448 crate::memory::MNEMO_META_ROLE.into(),
1449 Value::String(r.clone()),
1450 );
1451 }
1452 None => {
1453 meta.remove(crate::memory::MNEMO_META_ROLE);
1454 }
1455 }
1456 meta.insert(
1457 MNEMO_META_AFTER.into(),
1458 Value::Array(
1459 spec.after
1460 .iter()
1461 .map(|a| Value::String(a.clone()))
1462 .collect(),
1463 ),
1464 );
1465 meta.insert(
1466 MNEMO_META_PRE_APPROVED.into(),
1467 Value::Bool(spec.pre_approved),
1468 );
1469 if spec.refs.is_empty() {
1472 meta.remove(crate::memory::MNEMO_META_REFS);
1473 } else {
1474 meta.insert(
1475 crate::memory::MNEMO_META_REFS.into(),
1476 Value::Array(
1477 spec.refs
1478 .iter()
1479 .map(|r| Value::String(r.trim().to_string()))
1480 .collect(),
1481 ),
1482 );
1483 }
1484 };
1485 if let Some(mut m) = self.task_record(&slug)? {
1486 let t = Task::from_memory(&m).expect("a task");
1487 let mut meta = m.metadata.clone();
1488 set(&mut meta);
1489 if meta == m.metadata && m.content == content {
1490 return Ok((t, WriteOutcome::Unchanged));
1491 }
1492 if t.status == task_status::DONE {
1495 let mut n = 2;
1496 while self.task_record(&format!("{slug}-{n}"))?.is_some() {
1497 n += 1;
1498 }
1499 return Err(MnemoError::Invalid(format!(
1500 "{slug} is done; give a new slug ({slug}-{n}?)"
1501 )));
1502 }
1503 let caller = self.author.clone().unwrap_or_else(|| "anonymous".into());
1504 if caller != t.creator {
1505 return Err(MnemoError::Invalid(format!(
1506 "that slug is {}'s task; it wasn't changed",
1507 t.creator
1508 )));
1509 }
1510 if self.closes_cycle(&slug, &spec.after)? {
1512 return Err(MnemoError::Invalid(format!(
1513 "after: that would make {slug} wait for itself, through the tasks it waits for"
1514 )));
1515 }
1516 m.metadata = meta;
1517 m.content = content;
1518 let id = m.id;
1519 self.put(m)?;
1520 let t = Task::from_memory(&self.get(&id)?).expect("a task");
1521 return Ok((t, WriteOutcome::Updated));
1522 }
1523 let mut meta = Map::new();
1524 meta.insert(MNEMO_META_SLUG.into(), Value::String(slug));
1525 meta.insert(
1526 MNEMO_META_STATUS.into(),
1527 Value::String(task_status::QUEUED.into()),
1528 );
1529 meta.insert(
1530 MNEMO_META_CREATOR.into(),
1531 Value::String(self.author.clone().unwrap_or_else(|| "anonymous".into())),
1532 );
1533 meta.insert(
1534 MNEMO_META_DELIVERY.into(),
1535 Value::String(crate::memory::delivery::SENT.into()),
1536 );
1537 set(&mut meta);
1538 let id = self.put_coordination_with_id(Ulid::new(), MNEMO_META_KIND_TASK, content, meta)?;
1539 let t = Task::from_memory(&self.get(&id)?).expect("a task");
1540 Ok((t, WriteOutcome::Added))
1541 }
1542
1543 fn closes_cycle(&mut self, slug: &str, after: &[String]) -> Result<bool> {
1546 let all: std::collections::HashMap<String, Vec<String>> = self
1547 .task_records(None)?
1548 .iter()
1549 .filter_map(Task::from_memory)
1550 .map(|t| (t.slug, t.after))
1551 .collect();
1552 let mut stack: Vec<&str> = after.iter().map(String::as_str).collect();
1553 let mut seen = std::collections::HashSet::new();
1554 while let Some(s) = stack.pop() {
1555 if s == slug {
1556 return Ok(true);
1557 }
1558 if seen.insert(s.to_string()) {
1559 if let Some(next) = all.get(s) {
1560 stack.extend(next.iter().map(String::as_str));
1561 }
1562 }
1563 }
1564 Ok(false)
1565 }
1566
1567 pub(super) fn task_history(
1569 m: &mut Memory,
1570 from: &str,
1571 to: &str,
1572 by: &str,
1573 at: i64,
1574 extra: &[(&str, &str)],
1575 ) {
1576 let mut e = Map::new();
1577 e.insert("from".into(), Value::String(from.into()));
1578 e.insert("to".into(), Value::String(to.into()));
1579 e.insert("at".into(), Value::from(at));
1580 e.insert("by".into(), Value::String(by.into()));
1581 for (k, v) in extra {
1582 e.insert((*k).into(), Value::String((*v).into()));
1583 }
1584 let mut h = m
1585 .metadata
1586 .get(MNEMO_META_STATUS_HISTORY)
1587 .and_then(Value::as_array)
1588 .cloned()
1589 .unwrap_or_default();
1590 h.push(Value::Object(e));
1591 m.metadata
1592 .insert(MNEMO_META_STATUS_HISTORY.into(), Value::Array(h));
1593 }
1594
1595 pub fn task_next(&mut self, role: Option<&str>) -> Result<Option<TaskTaken>> {
1603 if self.read_only {
1604 return Err(MnemoError::ReadOnly);
1605 }
1606 let agent = self.claim_agent()?;
1607 let now = self.coordination_now();
1608 let ready: Vec<Ulid> = self.ready_tasks(role)?.iter().map(|t| t.id).collect();
1609 let taken: Vec<Task> = self
1614 .task_records(None)?
1615 .iter()
1616 .filter_map(Task::from_memory)
1617 .filter(|t| t.status == task_status::ACTIVE || t.status == task_status::BLOCKED)
1618 .filter(|t| t.for_role(role))
1619 .collect();
1620 let (own, others): (Vec<&Task>, Vec<&Task>) = taken
1621 .iter()
1622 .partition(|t| t.owner.as_deref() == Some(agent.as_str()));
1623 for (id, back) in own
1624 .iter()
1625 .map(|t| (t.id, true))
1626 .chain(ready.into_iter().map(|i| (i, false)))
1627 .chain(others.iter().map(|t| (t.id, true)))
1628 {
1629 let mut m = self.get(&id)?;
1630 let t = Task::from_memory(&m).expect("a task");
1631 let (token, expires_at) =
1632 match self.claim(&task_topic(&t.slug), Some(TASK_CLAIM_TTL))? {
1633 ClaimOutcome::Claimed { token, expires_at } => (token, expires_at),
1634 ClaimOutcome::HeldBy { .. } => continue,
1635 };
1636 m = self.get(&id)?;
1639 let old = t.owner.clone();
1640 let own = old.as_deref() == Some(agent.as_str());
1641 if back && own {
1642 Self::task_history(
1643 &mut m,
1644 &t.status,
1645 task_status::ACTIVE,
1646 &agent,
1647 now,
1648 &[("note", "taken again after its claim lapsed")],
1649 );
1650 } else if back {
1651 let from = old.clone().unwrap_or_default();
1652 Self::task_history(
1653 &mut m,
1654 &t.status,
1655 task_status::ACTIVE,
1656 &agent,
1657 now,
1658 &[("reclaimed_from", from.as_str())],
1659 );
1660 } else {
1661 Self::task_history(
1662 &mut m,
1663 task_status::QUEUED,
1664 task_status::ACTIVE,
1665 &agent,
1666 now,
1667 &[],
1668 );
1669 }
1670 m.metadata.insert(
1671 MNEMO_META_STATUS.into(),
1672 Value::String(task_status::ACTIVE.into()),
1673 );
1674 m.metadata
1675 .insert(MNEMO_META_OWNER.into(), Value::String(agent.clone()));
1676 self.put(m)?;
1677 let task = Task::from_memory(&self.get(&id)?).expect("a task");
1678 return Ok(Some(TaskTaken {
1679 task,
1680 token,
1681 expires_at,
1682 reclaimed_from: if back && !own { old } else { None },
1683 }));
1684 }
1685 Ok(None)
1686 }
1687
1688 pub fn task_update(
1703 &mut self,
1704 slug: &str,
1705 status: Option<&str>,
1706 note: Option<&str>,
1707 token: Option<&str>,
1708 ) -> Result<TaskOutcome> {
1709 if self.read_only {
1710 return Err(MnemoError::ReadOnly);
1711 }
1712 let agent = self.claim_agent()?;
1713 let now = self.coordination_now();
1714 let Some(m) = self.task_record(slug)? else {
1715 return Err(MnemoError::Invalid(format!("no task {slug:?}")));
1716 };
1717 let t = Task::from_memory(&m).expect("a task");
1718 let to = status.unwrap_or(&t.status).to_string();
1719 if status.is_none() && note.is_none() {
1720 return Err(MnemoError::Invalid("give a status or a note".into()));
1721 }
1722 if token.is_some() && t.owner.as_deref() != Some(agent.as_str()) {
1725 return Ok(TaskOutcome::Lost(TaskLost::TakenBack));
1726 }
1727 let changing = to != t.status;
1728 if changing && !TASK_TRANSITIONS.contains(&(t.status.as_str(), to.as_str())) {
1729 return Err(MnemoError::Invalid(format!(
1730 "a task can't go from {} to {to}",
1731 t.status
1732 )));
1733 }
1734 if changing && t.status == task_status::QUEUED {
1735 return Err(MnemoError::Invalid(
1736 "a queued task is taken with `task next`".into(),
1737 ));
1738 }
1739 let topic = task_topic(slug);
1740 let claim = self.find_claim(&topic)?;
1741 let live = claim.as_ref().filter(|c| is_live(c, now));
1742 let claim_token = claim
1743 .as_ref()
1744 .and_then(|c| meta_string(c, MNEMO_META_CLAIM_TOKEN));
1745 let held_by_owner = live.is_some_and(|c| meta_string(c, MNEMO_META_HOLDER) == t.owner);
1746 let is_owner = t.owner.as_deref() == Some(agent.as_str());
1747 let is_creator = t.creator == agent;
1748 let by_owner = if changing && t.status == task_status::READY {
1750 if !(is_creator || (is_owner && t.pre_approved)) {
1752 return Err(MnemoError::Invalid(format!(
1753 "{slug} waits for its creator ({}) to set done",
1754 t.creator
1755 )));
1756 }
1757 false
1758 } else if changing && to == task_status::QUEUED && !is_owner {
1759 if let Some(c) = live {
1761 return Err(MnemoError::Invalid(format!(
1762 "{slug} is {}'s, and its claim is live until {}; only its owner can hand \
1763 it back before then",
1764 t.owner.as_deref().unwrap_or("its owner"),
1765 crate::memory::date_time_of(effective_expiry(c, now).unwrap_or(now))
1766 )));
1767 }
1768 false
1769 } else if t.status == task_status::DONE || (!changing && t.status == task_status::READY) {
1770 if !(is_creator || is_owner) {
1772 return Err(MnemoError::Invalid(format!("{slug} isn't yours")));
1773 }
1774 false
1775 } else if !changing && is_creator && !is_owner {
1776 false } else if t.status == task_status::QUEUED {
1778 if !is_creator {
1780 return Err(MnemoError::Invalid(format!("{slug} isn't yours")));
1781 }
1782 false
1783 } else {
1784 if !is_owner {
1785 return Ok(TaskOutcome::Lost(TaskLost::TakenBack));
1786 }
1787 true
1788 };
1789 let mut renew_token = None;
1796 if by_owner {
1797 let token_ok = token.is_none_or(|tk| claim_token.as_deref() == Some(tk));
1798 if live.is_some() && !held_by_owner {
1799 return Ok(TaskOutcome::Lost(TaskLost::TakenBack));
1800 }
1801 if !token_ok {
1802 return Ok(TaskOutcome::Lost(TaskLost::OtherToken));
1803 }
1804 if held_by_owner {
1805 renew_token = claim_token.clone();
1806 }
1807 }
1808 let mut m = m;
1809 let mut extra: Vec<(&str, &str)> = Vec::new();
1810 if let Some(n) = note {
1811 extra.push(("note", n));
1812 }
1813 Self::task_history(&mut m, &t.status, &to, &agent, now, &extra);
1814 m.metadata
1815 .insert(MNEMO_META_STATUS.into(), Value::String(to.clone()));
1816 if to == task_status::QUEUED {
1817 m.metadata.remove(MNEMO_META_OWNER);
1818 }
1819 let id = m.id;
1820 self.put(m)?;
1821 let releases =
1822 [task_status::READY, task_status::DONE, task_status::QUEUED].contains(&to.as_str());
1823 let mut held: Option<TaskClaim> = None;
1824 match (releases, by_owner, renew_token) {
1825 (true, _, Some(tk)) => {
1826 self.release(&topic, &tk)?;
1827 }
1828 (true, _, None) => {
1829 if let Some(mut c) = self.find_claim(&topic)? {
1831 if is_live(&c, now)
1832 && meta_string(&c, MNEMO_META_HOLDER) == t.owner
1833 && to == task_status::DONE
1834 {
1835 c.metadata.remove(MNEMO_META_CLAIM_TOKEN);
1836 c.metadata
1837 .insert(MNEMO_META_EXPIRES_AT.into(), Value::from(now));
1838 self.put(c)?;
1839 }
1840 }
1841 }
1842 (false, true, Some(tk)) => {
1843 if let ClaimStatus::Held { expires_at } =
1844 self.renew(&topic, &tk, Some(TASK_CLAIM_TTL))?
1845 {
1846 held = Some(TaskClaim {
1847 token: tk,
1848 expires_at,
1849 retaken: false,
1850 });
1851 }
1852 }
1853 (false, true, None) => {
1854 if let ClaimOutcome::Claimed { token, expires_at } =
1857 self.claim(&topic, Some(TASK_CLAIM_TTL))?
1858 {
1859 held = Some(TaskClaim {
1860 token,
1861 expires_at,
1862 retaken: true,
1863 });
1864 }
1865 }
1866 (false, false, _) => {}
1867 }
1868 Ok(TaskOutcome::Updated(
1869 Box::new(Task::from_memory(&self.get(&id)?).expect("a task")),
1870 held,
1871 ))
1872 }
1873}
1874
1875use crate::memory::{
1878 HOP_CAP, MNEMO_META_WAKES, MNEMO_META_WAKE_PAUSED, MNEMO_META_WARNED_EXPIRY, PAIR_BURST,
1879 PAIR_BURST_SECS, TASK_CLAIM_WARN_SECS, WAKE_COOLDOWN_SECS, WAKE_PER_HOUR,
1880};
1881
1882#[derive(Debug, Clone, Default, PartialEq)]
1885pub struct NewWork {
1886 pub messages: Vec<Message>,
1888 pub tasks: Vec<Task>,
1890 pub lapsing: Vec<Claim>,
1894 pub ready_for_done: Vec<Task>,
1898 pub findings: Vec<super::Finding>,
1902 pub agent: Option<String>,
1905}
1906
1907impl NewWork {
1908 pub fn is_empty(&self) -> bool {
1910 self.messages.is_empty()
1911 && self.tasks.is_empty()
1912 && self.lapsing.is_empty()
1913 && self.ready_for_done.is_empty()
1914 && self.findings.is_empty()
1915 }
1916}
1917
1918#[derive(Debug, Clone, PartialEq, Eq)]
1920pub enum Wake {
1921 Now {
1924 tasks: usize,
1926 messages: usize,
1928 },
1929 Nothing,
1931 Held(&'static str),
1934}
1935
1936impl Mnemo {
1937 pub fn new_work(&mut self, agent: Option<&str>, role: Option<&str>) -> Result<NewWork> {
1940 let now = self.coordination_now();
1941 let unseen =
1942 |d: &str| d == crate::memory::delivery::SENT || d == crate::memory::delivery::DELIVERED;
1943 let mut messages = Vec::new();
1947 for msg in self.inbox(agent, role, true)? {
1948 let broadcast = msg.to == "all" || msg.to.starts_with("role:");
1949 let new = match (broadcast, agent) {
1950 (true, Some(a)) => !seen_by(&self.get(&msg.id)?).iter().any(|s| s == a),
1951 _ => unseen(&msg.delivery),
1952 };
1953 if new {
1954 messages.push(msg);
1955 }
1956 }
1957 let mut tasks = Vec::new();
1958 for t in self.ready_tasks(role)? {
1959 let m = self.get(&t.id)?;
1960 let new = match agent {
1961 Some(a) => !seen_by(&m).iter().any(|s| s == a),
1962 None => meta_string(&m, MNEMO_META_DELIVERY).is_none_or(|d| unseen(&d)),
1963 };
1964 if new {
1965 tasks.push(t);
1966 }
1967 }
1968 let mut ready_for_done = Vec::new();
1971 if let Some(a) = agent {
1972 for t in self.tasks(Some(crate::memory::task_status::READY), None)? {
1973 if t.creator == a && !ready_seen_by(&self.get(&t.id)?).iter().any(|s| s == a) {
1974 ready_for_done.push(t);
1975 }
1976 }
1977 }
1978 let mut findings = Vec::new();
1980 if let (Some(a), Some("planner")) = (agent, role) {
1981 let open = super::FindingFilter {
1982 status: Some(crate::memory::finding_status::OPEN.into()),
1983 ..Default::default()
1984 };
1985 for f in self.findings(&open)? {
1986 if !seen_by(&self.get(&f.record_id)?).iter().any(|s| s == a) {
1987 findings.push(f);
1988 }
1989 }
1990 }
1991 let mut lapsing = Vec::new();
1992 if let Some(a) = agent {
1993 for m in self.coordination_records(MNEMO_META_KIND_CLAIM, None)? {
1994 let topic = meta_string(&m, MNEMO_META_TOPIC).unwrap_or_default();
1995 if !topic.starts_with("task:")
1996 || meta_string(&m, MNEMO_META_HOLDER).as_deref() != Some(a)
1997 || !is_live(&m, now)
1998 {
1999 continue;
2000 }
2001 let e = effective_expiry(&m, now).unwrap_or(now);
2002 if e - now <= TASK_CLAIM_WARN_SECS
2003 && meta_i64(&m, MNEMO_META_WARNED_EXPIRY) != Some(e)
2004 {
2005 lapsing.push(Claim {
2006 topic,
2007 holder: a.to_string(),
2008 expires_at: e,
2009 lease: meta_i64(&m, MNEMO_META_LEASE).unwrap_or(CLAIM_TTL_DEFAULT),
2010 });
2011 }
2012 }
2013 }
2014 Ok(NewWork {
2015 messages,
2016 tasks,
2017 lapsing,
2018 ready_for_done,
2019 findings,
2020 agent: agent.map(str::to_string),
2021 })
2022 }
2023
2024 pub fn mark_shown(&mut self, work: &NewWork) -> Result<()> {
2029 if self.read_only {
2030 return Err(MnemoError::ReadOnly);
2031 }
2032 let ids: Vec<Ulid> = work.messages.iter().map(|m| m.id).collect();
2033 let who = work.agent.clone().or_else(|| self.author.clone());
2035 let author = std::mem::replace(&mut self.author, who.clone());
2036 let r = self.mark_seen(&ids);
2037 self.author = author;
2038 r?;
2039 for t in &work.tasks {
2040 let mut m = self.get(&t.id)?;
2041 match who.clone() {
2042 Some(a) => {
2044 if add_seen_by(&mut m, &a) {
2045 self.put(m)?;
2046 }
2047 }
2048 None => {
2049 m.metadata.insert(
2050 MNEMO_META_DELIVERY.into(),
2051 Value::String(crate::memory::delivery::SEEN.into()),
2052 );
2053 self.put(m)?;
2054 }
2055 }
2056 }
2057 if let Some(a) = &who {
2059 for f in &work.findings {
2060 let mut m = self.get(&f.record_id)?;
2061 if add_seen_by(&mut m, a) {
2062 self.put(m)?;
2063 }
2064 }
2065 }
2066 if let Some(a) = &who {
2068 for t in &work.ready_for_done {
2069 let mut m = self.get(&t.id)?;
2070 let mut v = ready_seen_by(&m);
2071 if v.iter().any(|s| s == a) {
2072 continue;
2073 }
2074 v.push(a.clone());
2075 m.metadata.insert(
2076 crate::memory::MNEMO_META_READY_SEEN_BY.into(),
2077 Value::Array(v.into_iter().map(Value::String).collect()),
2078 );
2079 self.put(m)?;
2080 }
2081 }
2082 for c in &work.lapsing {
2083 if let Some(mut m) = self.find_claim(&c.topic)? {
2084 m.metadata
2085 .insert(MNEMO_META_WARNED_EXPIRY.into(), Value::from(c.expires_at));
2086 self.put(m)?;
2087 }
2088 }
2089 Ok(())
2090 }
2091
2092 pub fn wake_paused(&mut self) -> Result<Option<(String, i64)>> {
2095 let Some(m) = self
2096 .about_in(crate::memory::VisibilitySet::ALL)?
2097 .into_iter()
2098 .find(is_manifest)
2099 else {
2100 return Ok(None);
2101 };
2102 Ok(m.metadata.get(MNEMO_META_WAKE_PAUSED).map(|v| {
2103 (
2104 v.get("by")
2105 .and_then(Value::as_str)
2106 .unwrap_or("")
2107 .to_string(),
2108 v.get("at").and_then(Value::as_i64).unwrap_or(0),
2109 )
2110 }))
2111 }
2112
2113 pub fn set_wake_paused(&mut self, paused: bool) -> Result<WriteOutcome> {
2117 if self.read_only {
2118 return Err(MnemoError::ReadOnly);
2119 }
2120 let Some(mut m) = self
2121 .about_in(crate::memory::VisibilitySet::ALL)?
2122 .into_iter()
2123 .find(is_manifest)
2124 else {
2125 return Err(MnemoError::Invalid(
2126 "this brain has no manifest to record the pause on".into(),
2127 ));
2128 };
2129 if m.metadata.contains_key(MNEMO_META_WAKE_PAUSED) == paused {
2130 return Ok(WriteOutcome::Unchanged);
2131 }
2132 if paused {
2133 let mut v = Map::new();
2134 v.insert(
2135 "by".into(),
2136 Value::String(self.author.clone().unwrap_or_else(|| "anonymous".into())),
2137 );
2138 v.insert("at".into(), Value::from(self.coordination_now()));
2139 m.metadata
2140 .insert(MNEMO_META_WAKE_PAUSED.into(), Value::Object(v));
2141 } else {
2142 m.metadata.remove(MNEMO_META_WAKE_PAUSED);
2143 }
2144 self.put(m)?;
2145 Ok(WriteOutcome::Updated)
2146 }
2147
2148 pub fn wake(&mut self, agent: &str, role: Option<&str>) -> Result<Wake> {
2163 if self.read_only {
2164 return Err(MnemoError::ReadOnly);
2165 }
2166 let now = self.coordination_now();
2167 let sent = crate::memory::delivery::SENT;
2168 let mut tasks = Vec::new();
2169 for t in self.ready_tasks(role)? {
2170 let m = self.get(&t.id)?;
2171 if t.pre_approved
2172 && meta_string(&m, MNEMO_META_DELIVERY).as_deref() == Some(sent)
2173 && !seen_by(&m).iter().any(|s| s == agent)
2174 {
2175 tasks.push(t.id);
2176 }
2177 }
2178 let all_msgs: Vec<Message> = self
2179 .messages()?
2180 .iter()
2181 .filter_map(Message::from_memory)
2182 .collect();
2183 let candidates: Vec<&Message> = all_msgs
2184 .iter()
2185 .filter(|m| m.to == agent && m.from != agent)
2186 .filter(|m| m.status == crate::memory::MESSAGE_UNREAD && m.delivery == sent)
2187 .collect();
2188 if tasks.is_empty() && candidates.is_empty() {
2189 return Ok(Wake::Nothing);
2190 }
2191 if self.wake_paused()?.is_some() {
2192 return Ok(Wake::Held("paused"));
2193 }
2194 let burst = |a: &str, b: &str| {
2195 all_msgs
2196 .iter()
2197 .filter(|m| now - m.created_at <= PAIR_BURST_SECS)
2198 .filter(|m| (m.from == a && m.to == b) || (m.from == b && m.to == a))
2199 .count()
2200 >= PAIR_BURST
2201 };
2202 let mut reason = None;
2203 let messages: Vec<Ulid> = candidates
2204 .iter()
2205 .filter(|m| {
2206 let reply = m.conversation != m.id.to_string();
2207 if reply && m.hops > HOP_CAP {
2208 reason = Some("the thread reached its hop cap");
2209 return false;
2210 }
2211 if burst(&m.from, &m.to) {
2212 reason = Some("a burst of messages between two agents");
2213 return false;
2214 }
2215 true
2216 })
2217 .map(|m| m.id)
2218 .collect();
2219 if tasks.is_empty() && messages.is_empty() {
2220 return Ok(Wake::Held(reason.unwrap_or("a guardrail")));
2221 }
2222 let presence = self
2224 .coordination_records(MNEMO_META_KIND_PRESENCE, Some(agent))?
2225 .into_iter()
2226 .next();
2227 let mut wakes: Vec<i64> = presence
2228 .as_ref()
2229 .and_then(|m| m.metadata.get(MNEMO_META_WAKES))
2230 .and_then(Value::as_array)
2231 .map(|a| a.iter().filter_map(Value::as_i64).collect())
2232 .unwrap_or_default();
2233 wakes.retain(|t| now - t < 3600 && *t <= now);
2234 if wakes.len() >= WAKE_PER_HOUR {
2235 return Ok(Wake::Held("the hourly limit of wake-ups"));
2236 }
2237 if wakes.iter().any(|t| now - t < WAKE_COOLDOWN_SECS) {
2238 return Ok(Wake::Held("the cooldown between wake-ups"));
2239 }
2240 wakes.push(now);
2241 let delivered = Value::String(crate::memory::delivery::DELIVERED.into());
2242 for id in tasks.iter().chain(messages.iter()) {
2243 let mut m = self.get(id)?;
2244 m.metadata
2245 .insert(MNEMO_META_DELIVERY.into(), delivered.clone());
2246 self.put(m)?;
2247 }
2248 let w = Value::Array(wakes.into_iter().map(Value::from).collect());
2249 match presence {
2250 Some(mut m) => {
2251 m.metadata.insert(MNEMO_META_WAKES.into(), w);
2252 self.put(m)?;
2253 }
2254 None => {
2255 let mut meta = Map::new();
2256 meta.insert(MNEMO_META_AGENT.into(), Value::String(agent.to_string()));
2257 meta.insert(MNEMO_META_LAST_ACTIVE.into(), Value::from(0));
2258 meta.insert(MNEMO_META_PRESENCE_LOCK.into(), Value::Bool(false));
2259 meta.insert(MNEMO_META_WAKES.into(), w);
2260 self.put_coordination_with_id(
2261 Ulid::new(),
2262 MNEMO_META_KIND_PRESENCE,
2263 format!("presence {agent}"),
2264 meta,
2265 )?;
2266 }
2267 }
2268 Ok(Wake::Now {
2269 tasks: tasks.len(),
2270 messages: messages.len(),
2271 })
2272 }
2273}
2274
2275#[derive(Debug, Clone, PartialEq, Eq)]
2279pub struct Stale {
2280 pub id: Ulid,
2282 pub what: String,
2286 pub since: i64,
2288 pub text: String,
2290 pub whose: Option<String>,
2292 pub visibility: String,
2294}
2295
2296impl Mnemo {
2297 pub fn stale(&mut self) -> Result<Vec<Stale>> {
2304 use super::records::{ROW_KIND_ESSENCE, ROW_REVIEW};
2305 let now = self.coordination_now();
2306 let entries: Vec<CatalogEntry> = self
2307 .catalog
2308 .iter()
2309 .filter(|e| !e.deleted)
2310 .filter(|e| {
2311 e.v9.is_none_or(|r| {
2312 r.kind == ROW_KIND_ESSENCE
2313 || r.kind == ROW_KIND_COORDINATION
2314 || r.flags & ROW_REVIEW != 0
2315 })
2316 })
2317 .cloned()
2318 .collect();
2319 let mut out = Vec::new();
2320 for e in entries {
2321 let m = self.read_memory(&e)?;
2322 let Some(since) = crate::memory::stale_since(&m, now) else {
2323 continue;
2324 };
2325 let s = |k: &str| meta_string(&m, k);
2326 let kind = s(MNEMO_META_KIND);
2327 let what = match kind.as_deref() {
2328 Some("essence") => format!(
2329 "essence {}",
2330 s(crate::memory::MNEMO_META_SECTION).unwrap_or_default()
2331 ),
2332 Some(k @ ("task" | "message")) => {
2333 format!("{k} {}", s(MNEMO_META_STATUS).unwrap_or_default())
2334 }
2335 Some(k) => k.to_string(),
2336 None => "fact".to_string(),
2337 };
2338 let whose = match kind.as_deref() {
2339 Some("task") => s(MNEMO_META_OWNER),
2340 Some("message") => s(MNEMO_META_TO),
2341 _ => s(crate::memory::MNEMO_META_AUTHOR),
2342 };
2343 out.push(Stale {
2344 id: m.id,
2345 what,
2346 since,
2347 text: m.content.lines().next().unwrap_or("").to_string(),
2348 whose,
2349 visibility: crate::memory::visibility_of(&m).to_string(),
2350 });
2351 }
2352 out.sort_by_key(|x| (x.since, x.id.0));
2353 Ok(out)
2354 }
2355}
2356
2357#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2359pub struct KindCounts {
2360 pub facts: usize,
2362 pub turns: usize,
2364 pub essence: usize,
2366 pub coordination: usize,
2368}
2369
2370impl Mnemo {
2371 pub fn kind_counts(&self) -> KindCounts {
2375 use super::records::{ROW_KIND_ESSENCE, ROW_KIND_THREAD_LINK, ROW_KIND_TURN};
2376 let mut c = KindCounts::default();
2377 for e in self.catalog.iter().filter(|e| !e.deleted) {
2378 match e.v9.map(|r| r.kind) {
2379 Some(ROW_KIND_TURN | ROW_KIND_THREAD_LINK) => c.turns += 1,
2380 Some(ROW_KIND_ESSENCE) => c.essence += 1,
2381 Some(ROW_KIND_COORDINATION) => c.coordination += 1,
2382 _ => c.facts += 1,
2383 }
2384 }
2385 c
2386 }
2387}
2388
2389#[cfg(test)]
2390mod legacy_scan_tests {
2391 use super::is_sentinel;
2392
2393 #[test]
2396 fn the_sentinel_is_told_from_an_ordinary_vector() {
2397 for dims in [4, 32, 384, 768] {
2398 let s = vec![1.0 / (dims as f32).sqrt(); dims];
2399 let (h, _) = crate::veccol::quantize(&s);
2400 assert!(is_sentinel(&h), "{dims}");
2401 let mut v = s.clone();
2402 v[dims / 2] += 0.05;
2403 assert!(!is_sentinel(&crate::veccol::quantize(&v).0), "{dims}");
2404 let flat = vec![0.5; dims];
2405 assert_eq!(
2406 is_sentinel(&crate::veccol::quantize(&flat).0),
2407 dims == 4,
2408 "{dims}"
2409 );
2410 }
2411 assert!(!is_sentinel(&[]));
2412 }
2413}