Skip to main content

mnemo_engine/store/
coordination.rs

1//! 13a (v0.17): coordination records, `message`, `task`, `claim` and
2//! `presence` (`docs/design/13a-coordination.md`). Step 1 is the plumbing:
3//! the kinds are stored as ordinary records in the shared scope with the
4//! sentinel vector, and kept out of recall, the keyword index, the ANN and
5//! `about` (see `is_coordination`). Each kind's API comes in its own step.
6
7use super::*;
8
9impl Mnemo {
10    /// Write a coordination record of `kind` (one of
11    /// [`crate::memory::COORDINATION_KINDS`]) holding `content` and
12    /// `metadata` (whose `_mnemo.*` keys the caller of this internal path
13    /// sets): shared scope, the sentinel vector, never embedded. The
14    /// handle's author is stamped like any new record's.
15    // The test hook's; the APIs use `put_coordination_with_id`.
16    #[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    /// [`Mnemo::put_coordination`] with the record's id chosen first (a
27    /// message's id names its conversation).
28    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/// 13a (13.1): one message between agents, as [`Mnemo::inbox`] returns it.
53#[derive(Debug, Clone, PartialEq)]
54pub struct Message {
55    /// The record's id.
56    pub id: Ulid,
57    /// An agent id, `role:<role>`, or `all`.
58    pub to: String,
59    /// The sender as it said, unproven until 13b.
60    pub from: String,
61    /// One line.
62    pub subject: String,
63    /// The body (may be empty).
64    pub body: String,
65    /// Record ids, a PR number, a ledger entry title.
66    pub refs: Vec<String>,
67    /// The conversation it belongs to.
68    pub conversation: String,
69    /// Its hop count (13.1b's hop cap).
70    pub hops: u64,
71    /// `unread` or `acked`.
72    pub status: String,
73    /// `sent`, `delivered`, `seen` or `done`.
74    pub delivery: String,
75    /// When it was posted, in unix seconds.
76    pub created_at: i64,
77    /// When it was acked, if it was.
78    pub acked_at: Option<i64>,
79}
80
81impl Message {
82    /// The message a record holds, if it's one.
83    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    /// Whether it's addressed to `agent` (by id), to `role`, or to everyone,
130    /// and isn't from `agent` itself.
131    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
141/// Whether `to` is an address: an agent id, `role:<role>`, or `all`.
142fn 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
150/// 13a (RB-012.6 item 4): the agents a broadcast message or a role's task
151/// has been shown to (`_mnemo.seen_by`).
152fn 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
164/// Add `agent` to a record's `_mnemo.seen_by`; `false` when it was there.
165fn 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    /// Every live coordination record of `kind`, in catalog order; with a
180    /// `locator` (a claim's topic, a presence record's agent), only that
181    /// one's, found through its row's hash without decrypting the rest.
182    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    /// RB-013.1: the coordination records an older build re-tagged as facts
214    /// (its `compact` writes every row again, and it computes "fact" for a
215    /// kind it doesn't know). Found once per handle: such a record keeps
216    /// its `episodic` type in the row, so only `episodic` fact rows are
217    /// decrypted. A write of one re-tags its row.
218    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    /// RB-013.1: how many coordination records are tagged as facts in their
245    /// rows (an older mnemo rewrote this brain); `mnemo compact` re-tags
246    /// them. They're found and used all the same.
247    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    /// Every live message, oldest first.
260    fn messages(&mut self) -> Result<Vec<Memory>> {
261        let mut out = self.coordination_records(crate::memory::MNEMO_META_KIND_MESSAGE, None)?;
262        // Stable: within one second (`created_at`'s grain) the catalog's
263        // order, which is the order they were written.
264        out.sort_by_key(|m| m.created_at);
265        Ok(out)
266    }
267
268    /// 13a (13.1): post a message to `to` (an agent id, `role:<role>`, or
269    /// `all`) with a one-line `subject` and an optional `body` (at most
270    /// [`crate::memory::MESSAGE_BODY_MAX`] bytes), from `from` (else the
271    /// handle's author, else `anonymous`), in `from_role` when given.
272    ///
273    /// A reply names its `conversation`, and its hop count is one more than
274    /// the conversation's highest. A new message between the same two
275    /// parties within [`crate::memory::MESSAGE_PAIR_CARRY_SECS`] starts one
276    /// above the highest count between them in that time, so agents trading
277    /// fresh messages still reach the hop cap. Its delivery is `sent` and its status `unread`.
278    // Each is a message's own field; a request struct would only rename them.
279    #[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        // The pair carry: one more than the highest count between these two,
339        // either way, in the window.
340        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    /// 13a (13.1): the messages for `agent` (by id), its `role`, or
389    /// everyone, oldest first, leaving out its own. With `unread_only`,
390    /// only those not yet acked. Reads only; [`Mnemo::mark_seen`] records
391    /// that they were shown.
392    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    /// 13a (13.5): [`Mnemo::inbox`] with the visibility levels it shows
407    /// (`inbox` itself shows public and team).
408    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    /// 13a (13.1b): mark these messages `seen` (from `sent` or `delivered`),
426    /// in place. Returns how many changed.
427    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            // RB-012.6 item 4: a message to a role or everyone is seen per
448            // agent (this handle's author).
449            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    /// 13a (13.1): ack a message, in place: `unread → acked`, its delivery
463    /// `done`, and a `status_history` entry with `by` (else the handle's
464    /// author) and the optional `note`. `Unchanged` when it's already
465    /// acked; an id that isn't a message is refused.
466    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    /// 13a (R-010.8): delete messages acked more than `older_than_secs` ago
517    /// ([`crate::memory::MESSAGE_ACKED_KEEP_SECS`] by default in the CLI).
518    /// Returns how many went. `compact` drops the same ones.
519    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
538/// Whether a message is acked and older than `keep` seconds.
539fn 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
543/// 13a (R-010.8): whether `compact` leaves this record out: a message acked
544/// more than [`crate::memory::MESSAGE_ACKED_KEEP_SECS`] ago.
545pub(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
550// --- 13a step 3: claims and presence (13.3) ---------------------------------
551
552use 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
560/// A claim's or presence record's locator: its topic or its agent.
561fn 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
575/// The hash a coordination record's v9 row carries in place of a thread
576/// hash: of its kind and topic (a claim) or agent (presence); `0` for the
577/// other kinds.
578pub(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/// 13a (13.3): what [`Mnemo::claim`] got.
589#[derive(Debug, Clone, PartialEq, Eq)]
590pub enum ClaimOutcome {
591    /// The claim is this agent's. Keep the token: `renew`, `release` and
592    /// `check_claim` need it.
593    Claimed {
594        /// The claim's token.
595        token: String,
596        /// When it lapses unless renewed, in unix seconds.
597        expires_at: i64,
598    },
599    /// Another agent (or this one, in another process or session) holds it.
600    HeldBy {
601        /// The holder.
602        agent: String,
603        /// When it lapses unless renewed.
604        expires_at: i64,
605    },
606}
607
608/// 13a (13.3): what `renew`, `release` and `check_claim` found.
609#[derive(Debug, Clone, Copy, PartialEq, Eq)]
610pub enum ClaimStatus {
611    /// The claim is still the token's, until `expires_at`.
612    Held {
613        /// When it lapses unless renewed, in unix seconds.
614        expires_at: i64,
615    },
616    /// Released.
617    Released,
618    /// The claim lapsed or another agent holds it now: whatever it guarded
619    /// may have been done by someone else. Check before an irreversible
620    /// step.
621    Lost,
622}
623
624/// 13a (13.3): a live claim, as [`Mnemo::claims`] lists it (no token).
625#[derive(Debug, Clone, PartialEq, Eq)]
626pub struct Claim {
627    /// What's claimed.
628    pub topic: String,
629    /// Who holds it.
630    pub holder: String,
631    /// When it lapses unless renewed.
632    pub expires_at: i64,
633    /// Its lease, in seconds.
634    pub lease: i64,
635}
636
637/// 13a (13.3): whether an agent's process is running, by its presence lock.
638#[derive(Debug, Clone, Copy, PartialEq, Eq)]
639pub enum Alive {
640    /// Its long-lived process holds its presence lock.
641    Yes,
642    /// It registered a lock, and the lock is free: its process is gone.
643    No,
644    /// It has no long-lived process (the CLI, a session without the MCP
645    /// server), or the probe couldn't tell.
646    Unknown,
647}
648
649/// 13a (13.3): one agent, as [`Mnemo::who`] lists it.
650#[derive(Debug, Clone, PartialEq, Eq)]
651pub struct Presence {
652    /// The agent id.
653    pub agent: String,
654    /// Its role, if it gave one.
655    pub role: Option<String>,
656    /// The tool it last wrote through (`mcp`, `cli`, ...).
657    pub tool: Option<String>,
658    /// When it last wrote, in unix seconds (updated at most once a minute).
659    pub last_active: i64,
660    /// Whether its process is running.
661    pub alive: Alive,
662    /// The topics it holds live claims on.
663    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
677/// A claim record's expiry, bounded by one lease from `now`: a clock that
678/// stepped back can't stretch a claim past its lease.
679fn 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
692/// Whether a claim record is held at `now`.
693fn 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    /// 13a: the clock claims, leases and presence run on, in unix seconds:
726    /// the wall clock (dev-hooks builds let tests shift it).
727    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    /// **Not a stable API** (dev-hooks builds only): shift this handle's
739    /// coordination clock by `secs`.
740    #[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    /// 13a (13.3): claim `topic` for this handle's author for `ttl` seconds
762    /// ([`crate::memory::CLAIM_TTL_DEFAULT`], 15 minutes, by default; 30 s
763    /// to 24 h).
764    ///
765    /// A claim is a record, not a lock, and it's advisory: nothing refuses
766    /// a write because of one. In a shared handle's write window it's a
767    /// compare-and-set: two processes can't both win. The topic is free
768    /// when nobody holds it, its claim lapsed at `expires_at`, or its
769    /// holder registered a presence lock when it claimed and has been seen
770    /// not alive twice, [`crate::memory::CLAIM_LAPSE_GRACE_SECS`] apart
771    /// (each look is recorded on the claim). A topic this agent already
772    /// holds is [`ClaimOutcome::HeldBy`] too: a token can't be recovered.
773    /// One record per topic, changed in place: a new holder gets a new
774    /// token.
775    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                    // A clock that stepped back: bring the stored expiry
813                    // within one lease.
814                    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    /// 13a (13.3): renew a claim for `ttl` seconds from now (its lease by
863    /// default). [`ClaimStatus::Lost`] when it lapsed or isn't the token's.
864    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    /// 13a (13.3): release a claim. [`ClaimStatus::Lost`] when it already
890    /// lapsed or isn't the token's (then nothing changes).
891    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    /// 13a (13.3): whether `token` still holds `topic`. Call it before an
911    /// irreversible step. Reads only.
912    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    /// 13a (13.3): the live claims, by topic. Reads only.
927    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    /// 13a (13.3): record that this handle's author is active, with its
945    /// `role` and `tool`: its presence record's `last_active`, changed in
946    /// place, at most once a minute (sooner when the role, the tool or the
947    /// presence lock changed). Call it before a write the agent makes
948    /// anyway, so it rides that commit. `false` when nothing was written
949    /// (too soon, or no author).
950    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        // RB-012.4: only a process holding the presence lock writes the
965        // lock flag and the tool; another (the CLI, beside a server that
966        // holds it) moves `last_active` alone.
967        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    /// 13a (13.3): every agent with a presence record, most recently active
1036    /// first: its role, tool, `last_active`, whether its process is alive
1037    /// (by its presence lock; [`Alive::Unknown`] for an agent with no
1038    /// long-lived process), and the topics it holds. Reads only.
1039    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
1083// --- 13a step 4: tasks (13.1) ------------------------------------------------
1084
1085use 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/// 13a (13.1): a task to add ([`Mnemo::task_add`]).
1091#[derive(Debug, Clone, Default, PartialEq, Eq)]
1092pub struct TaskSpec {
1093    /// One line, at most 200 bytes.
1094    pub title: String,
1095    /// At most 8 KB; put more in a fact and name it.
1096    pub body: String,
1097    /// The role that may take it (`worker`); `None`, any.
1098    pub role: Option<String>,
1099    /// The slugs of the tasks it waits for; each must exist.
1100    pub after: Vec<String>,
1101    /// Its owner may go from `ready` to `done` without the creator.
1102    pub pre_approved: bool,
1103    /// Its name; made from the title when left out.
1104    pub slug: Option<String>,
1105}
1106
1107/// 13a (13.1): one task.
1108#[derive(Debug, Clone, PartialEq)]
1109pub struct Task {
1110    /// The record's id.
1111    pub id: Ulid,
1112    /// Its name.
1113    pub slug: String,
1114    /// One line.
1115    pub title: String,
1116    /// The body (may be empty).
1117    pub body: String,
1118    /// The role that may take it.
1119    pub role: Option<String>,
1120    /// `queued`, `active`, `ready`, `done` or `blocked`.
1121    pub status: String,
1122    /// The agent that took it.
1123    pub owner: Option<String>,
1124    /// The agent that added it.
1125    pub creator: String,
1126    /// The slugs it waits for.
1127    pub after: Vec<String>,
1128    /// Whether its owner may set `done`.
1129    pub pre_approved: bool,
1130    /// When it was added, in unix seconds.
1131    pub created_at: i64,
1132    /// Its status changes and notes, oldest first (`from`, `to`, `at`,
1133    /// `by`, and `note` or `reclaimed_from` when there's one).
1134    pub history: Vec<Value>,
1135}
1136
1137impl Task {
1138    /// The task a record holds, if it's one.
1139    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    /// Whether an agent of `role` may take it (a task with no role is any
1182    /// role's).
1183    fn for_role(&self, role: Option<&str>) -> bool {
1184        self.role.is_none() || self.role.as_deref() == role
1185    }
1186}
1187
1188/// 13a (13.1): a task [`Mnemo::task_next`] took, with its claim's token.
1189#[derive(Debug, Clone, PartialEq)]
1190pub struct TaskTaken {
1191    /// The task, now `active` and this agent's.
1192    pub task: Task,
1193    /// The `task:<slug>` claim's token (give it to `task_update` for the
1194    /// strict check).
1195    pub token: String,
1196    /// When the claim lapses unless an update renews it.
1197    pub expires_at: i64,
1198    /// The owner whose claim lapsed, when this took an abandoned task back.
1199    pub reclaimed_from: Option<String>,
1200}
1201
1202/// 13a (13.1): the claim an owner holds after a [`Mnemo::task_update`]
1203/// (RB-012.1), so it always has the current token.
1204#[derive(Debug, Clone, PartialEq, Eq)]
1205pub struct TaskClaim {
1206    /// The `task:<slug>` claim's token.
1207    pub token: String,
1208    /// When it lapses unless an update renews it.
1209    pub expires_at: i64,
1210    /// The claim had lapsed and nobody took the task, so the owner took
1211    /// the claim again (with a new token).
1212    pub retaken: bool,
1213}
1214
1215/// 13a (13.1): why a [`Mnemo::task_update`] changed nothing.
1216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1217pub enum TaskLost {
1218    /// Another agent took the task back after the caller's claim lapsed.
1219    TakenBack,
1220    /// The token isn't the task's claim's (another session of the same
1221    /// agent may hold it).
1222    OtherToken,
1223}
1224
1225/// 13a (13.1): what [`Mnemo::task_update`] did.
1226#[derive(Debug, Clone, PartialEq)]
1227pub enum TaskOutcome {
1228    /// Changed (or a note added). For the owner, the claim it now holds:
1229    /// renewed, or taken again after a lapse; `None` when the change
1230    /// released it (`ready`, `done`, `queued`) or wasn't the owner's.
1231    Updated(Box<Task>, Option<TaskClaim>),
1232    /// Nothing changed: don't carry on with it.
1233    Lost(TaskLost),
1234}
1235
1236/// The slug a title gives: lower case, runs of anything but `a-z0-9`
1237/// as one `-`, at most [`TASK_SLUG_MAX`] bytes.
1238pub 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    /// 13a (13.1): one task by slug. Reads only.
1276    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    /// 13a (13.1): the tasks, oldest first, with `status` and for `role`
1281    /// when given (a task with no role matches any). Reads only.
1282    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    /// 13a (13.1): the `queued` tasks an agent of `role` may take now (all
1293    /// their `after` tasks `done`), oldest first. Reads only.
1294    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    /// 13a (13.1): add a task, `queued`, created by this handle's author.
1314    /// A slug that already names a task updates its title, body, role,
1315    /// `after` and `pre_approved` in place (its status, owner and history
1316    /// stay); `Unchanged` when nothing differs. `after` must name existing
1317    /// tasks, never itself.
1318    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            // RB-012.2: a finished task is never reopened by a re-add, and
1400            // only its creator changes what a task is.
1401            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            // RB-012.6 item 5: an `after` that closes a cycle.
1418            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    /// Whether `slug` waiting for `after` closes a cycle: a task in `after`
1451    /// that waits (through its own `after`, transitively) for `slug`.
1452    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    /// Append a `status_history` entry.
1475    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    /// 13a (13.1): take the next task for `role`, for this handle's author,
1503    /// all in one exclusive window in a shared handle: the oldest `queued`
1504    /// task for the role whose `after` tasks are all `done`; failing that
1505    /// (R-010.7), an `active` one whose `task:<slug>` claim has lapsed,
1506    /// taken back from its owner with a `status_history` entry naming it.
1507    /// It claims `task:<slug>` for [`crate::memory::TASK_CLAIM_TTL`] and
1508    /// sets `active` and the owner. `None` when there's nothing to take.
1509    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        // Taken tasks (`active`, or `blocked`: RB-012.3) for the role. The
1517        // caller's own come first (RB-012.1): a worker whose claim lapsed
1518        // gets its own task back before anything new. `claim()` decides
1519        // which are free.
1520        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            // The claim's write may have changed the catalog: read the task
1544            // again before changing it.
1545            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    /// 13a (13.1): change a task's status (along [`TASK_TRANSITIONS`]), or
1596    /// add a `note` with none, as this handle's author.
1597    /// - **Its owner** moves it from `active` to `ready`, `blocked` or
1598    ///   `queued` (handing it back) and from `blocked` to `active`, and may
1599    ///   add notes; each renews its `task:<slug>` claim. With a `token`,
1600    ///   the claim must be that token's. An owner whose task was taken back
1601    ///   (or whose token isn't the claim's) gets [`TaskOutcome::Lost`].
1602    /// - **`ready → done`** is its creator's, or its owner's when
1603    ///   `pre_approved`.
1604    /// - **`active → queued`** is anyone's once the owner's claim has
1605    ///   lapsed (an abandoned task).
1606    /// - `queued → active` happens only through [`Mnemo::task_next`].
1607    ///
1608    /// `ready`, `done` and `queued` release the claim.
1609    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        // A token says the caller thinks the task is its own: when it isn't
1630        // any more, that's the answer, whatever the change asked for.
1631        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        // Who may do this.
1656        let by_owner = if changing && t.status == task_status::READY {
1657            // ready -> done
1658            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            // Requeueing an abandoned task: anyone's, once its claim lapsed.
1667            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            // A note on a finished task: its creator's or owner's.
1678            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 // its creator's note, at any status
1684        } else if t.status == task_status::QUEUED {
1685            // A note on a queued task: its creator's.
1686            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        // The owner's claim (RB-012.1):
1697        // - live and its own: a given token must be the claim's;
1698        // - live and someone else's: taken back;
1699        // - lapsed: a given token must be the lapsed claim's (the record
1700        //   keeps it), else another session took it in between; then the
1701        //   owner carries on and takes the claim again.
1702        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                // A lapsed or foreign-free claim: let it lapse.
1737                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                // Lapsed, and nobody else took it: the owner takes it again,
1762                // and gets the new token.
1763                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
1782// --- 13a step 5: what's new for an agent, and the wake-up guardrails ---------
1783
1784use 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/// 13a (13.1b): what's new for an agent since it was last shown
1790/// ([`Mnemo::new_work`]), for the per-turn hook.
1791#[derive(Debug, Clone, Default, PartialEq)]
1792pub struct NewWork {
1793    /// Unread messages to it, its role or everyone, not yet `seen`.
1794    pub messages: Vec<Message>,
1795    /// Tasks ready for its role, not yet `seen`.
1796    pub tasks: Vec<Task>,
1797    /// Its own task claims lapsing within
1798    /// [`crate::memory::TASK_CLAIM_WARN_SECS`], not yet warned about at this
1799    /// expiry.
1800    pub lapsing: Vec<Claim>,
1801    /// The agent it was read for: [`Mnemo::mark_shown`] records this agent
1802    /// as having seen the broadcasts and the role's tasks.
1803    pub agent: Option<String>,
1804}
1805
1806impl NewWork {
1807    /// Whether there's nothing.
1808    pub fn is_empty(&self) -> bool {
1809        self.messages.is_empty() && self.tasks.is_empty() && self.lapsing.is_empty()
1810    }
1811}
1812
1813/// 13a (13.1b): what [`Mnemo::wake`] decided.
1814#[derive(Debug, Clone, PartialEq, Eq)]
1815pub enum Wake {
1816    /// Wake the agent for these, now marked `delivered`: how many
1817    /// pre-approved tasks and messages addressed to it by id.
1818    Now {
1819        /// Pre-approved tasks ready for its role.
1820        tasks: usize,
1821        /// Messages to it by id.
1822        messages: usize,
1823    },
1824    /// Nothing that may wake it.
1825    Nothing,
1826    /// Something waits, but a guardrail holds it (its items stay `sent`,
1827    /// and are seen at the next turn or session start).
1828    Held(&'static str),
1829}
1830
1831impl Mnemo {
1832    /// 13a (13.1b): what's new for `agent` (and `role`) since it was last
1833    /// shown. Reads only; [`Mnemo::mark_shown`] records that it was.
1834    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        // RB-012.6 item 4: a message to the agent by id is new until it's
1839        // seen; one to a role or everyone, and a role's task, until this
1840        // agent has been shown it (`_mnemo.seen_by`).
1841        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    /// 13a (13.1b): record that `work` was shown: its messages and tasks
1895    /// `seen`, its lapsing claims warned about at their expiry. In place.
1896    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        // Seen by the agent the work was read for.
1902        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                // Seen by this agent; the task stays new to the others.
1911                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    /// 13a (13.1b): whether wake-ups are paused (the kill switch): who
1936    /// paused them and when.
1937    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    /// 13a (13.1b): pause (`true`) or resume wake-ups for every session
1957    /// of this brain, on the manifest. Paused, nothing wakes anyone: items
1958    /// stay `sent`, and the per-turn hook and the brief still show them.
1959    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    /// 13a (13.1b): the wake-up guardrails, in the one place that marks an
1992    /// item `delivered`. For `agent` (and `role`), the items that may wake
1993    /// it: pre-approved tasks ready for its role, and messages addressed to
1994    /// it by id (never to its role or `all`), still `sent`. Then:
1995    /// - **paused** (the kill switch): [`Wake::Held`];
1996    /// - **an explicit reply past the hop cap** ([`crate::memory::HOP_CAP`])
1997    ///   or **a pair in a burst** ([`crate::memory::PAIR_BURST`] messages
1998    ///   either way in [`crate::memory::PAIR_BURST_SECS`]) wakes nobody;
1999    /// - **the recipient's rate** ([`crate::memory::WAKE_PER_HOUR`]) and
2000    ///   **cooldown** ([`crate::memory::WAKE_COOLDOWN_SECS`]), from its
2001    ///   presence record's `_mnemo.wakes`.
2002    ///
2003    /// On [`Wake::Now`] the items are marked `delivered` and the wake-up is
2004    /// recorded on the recipient's presence record, in place.
2005    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        // The recipient's rate and cooldown, from its presence record.
2066        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// --- 13a step 7: freshness (13.6) --------------------------------------------
2119
2120/// 13a (13.6): one stale record ([`Mnemo::stale`]).
2121#[derive(Debug, Clone, PartialEq, Eq)]
2122pub struct Stale {
2123    /// The record's id.
2124    pub id: Ulid,
2125    /// What it is: `essence state`, `essence next`, `essence open`, `task
2126    /// active`, `task blocked`, `message unread`, or `fact` (past its
2127    /// `review_by`).
2128    pub what: String,
2129    /// When it went stale, in unix seconds.
2130    pub since: i64,
2131    /// Its first line (a task's title, a message's subject).
2132    pub text: String,
2133    /// Whose it is: a task's owner, a message's recipient, else its author.
2134    pub whose: Option<String>,
2135    /// Its visibility level (`public`, `team` or `private`).
2136    pub visibility: String,
2137}
2138
2139impl Mnemo {
2140    /// 13a (13.6): every record that's stale now
2141    /// ([`crate::memory::stale_since`]), oldest first: past its `review_by`,
2142    /// or older than its kind's default (essence `state` and `next` 14
2143    /// days, `open` 30, an `active` task with no update 3, a `blocked` one
2144    /// 7, an unread message 3). Reads only the rows that can be (essence,
2145    /// coordination, and those with a `review_by`).
2146    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/// 13a (ABOUT-COUNT): the live records by what they are.
2201#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2202pub struct KindCounts {
2203    /// Facts and onboarding records (what recall and `about` read).
2204    pub facts: usize,
2205    /// Thread turns and thread links.
2206    pub turns: usize,
2207    /// Essence items.
2208    pub essence: usize,
2209    /// Messages, tasks, claims and presence records.
2210    pub coordination: usize,
2211}
2212
2213impl Mnemo {
2214    /// 13a (ABOUT-COUNT): how many live records of each kind, from the
2215    /// catalog's rows (a v8 file's records have none and count as facts).
2216    /// Superseded versions count too, as in [`Mnemo::len`].
2217    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}