Skip to main content

lean_ctx_cloud/bus/
task_events.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `task.event` frames (C0 2.2 §10.1): Cloud tells every engine of a vault
3//! when one of its tasks changed. The engine outdates its task cache (the
4//! next `ctx_tasks` read fetches the task again) and hands the work to its
5//! own agents on the local bus, so agents orchestrate tasks themselves:
6//!
7//! - `opened`, `released`, `rejected`: the task is open (again): every agent
8//!   of the project may claim it;
9//! - `submitted`: a result waits for a second agent's check: every agent of
10//!   the project except the one that did the work (Cloud refuses a
11//!   self-verify);
12//! - everything else changes only the cache.
13//!
14//! The frame carries no task text, only its number, so nothing from it is
15//! shown as an instruction. The frame is not stored by Cloud: no replay. A
16//! frame missed while the relay was away or still subscribing is caught up
17//! after each hello (`catch_up`): the open and submitted tasks, read with
18//! `GET …/tasks?state=`, go through the same `apply`. The relay state
19//! keeps the last change applied per task ([`TasksSeen`]), so neither path
20//! announces a change twice or announces an older one after a newer.
21//!
22//! The frame types and [`notices`] are always built; `apply` and `catch_up`
23//! run only in the relay's WebSocket session (`bus::ws`, feature
24//! `http-server`), so they and what only they use are compiled with it.
25
26use std::collections::BTreeMap;
27#[cfg(feature = "http-server")]
28use std::path::Path;
29
30use serde::{Deserialize, Serialize};
31use serde_json::Value;
32
33#[cfg(feature = "http-server")]
34use super::address::Address;
35#[cfg(feature = "http-server")]
36use crate::tasks::ListFilter;
37#[cfg(feature = "http-server")]
38use crate::vault::VaultMap;
39#[cfg(feature = "http-server")]
40use lean_ctx::core::a2a::message::{MessagePriority, PrivacyLevel};
41#[cfg(feature = "http-server")]
42use lean_ctx::core::agents::AgentRegistry;
43use lean_ctx_protocol::cloud::tasks::TaskState;
44
45/// What happened to the task.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
47#[serde(rename_all = "snake_case")]
48pub enum TaskEventKind {
49    Opened,
50    Claimed,
51    Released,
52    Submitted,
53    Verified,
54    Rejected,
55    Cancelled,
56    Failed,
57    #[serde(other)]
58    Unknown,
59}
60
61/// Who acted: a worker and its engine, or Cloud itself (`system`).
62#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
63pub struct TaskEventBy {
64    #[serde(default)]
65    pub worker_id: Option<String>,
66    #[serde(default)]
67    pub instance_id: Option<String>,
68    #[serde(default)]
69    pub system: bool,
70}
71
72/// One `task.event` frame.
73#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
74pub struct TaskEvent {
75    pub vault: String,
76    pub number: u64,
77    pub event: TaskEventKind,
78    pub state: TaskState,
79    pub by: TaskEventBy,
80    pub at: u64,
81}
82
83impl TaskEvent {
84    pub fn parse(frame: &Value) -> Option<Self> {
85        serde_json::from_value(frame.clone())
86            .ok()
87            .filter(|e: &Self| e.number > 0)
88    }
89}
90
91/// Metadata key of a task notice on the local bus (additive, rc3-57): the
92/// task and what may be done with it, as JSON
93/// `{"task":7,"actions":["show","claim"]}`. The notice's text is plain
94/// language for people (the app renders the actions as buttons); an agent
95/// is shown the exact `ctx_tasks` call built from this field
96/// ([`TaskAction::call`]), never one taken from the text.
97pub const TASK_ACTION_KEY: &str = "lean_ctx.task_action";
98
99/// Who posts the notices of Cloud task events on the local bus.
100pub const SENDER: &str = "cloud";
101
102/// One thing that may be done with a task named by a notice.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(rename_all = "snake_case")]
105pub enum TaskVerb {
106    Show,
107    Claim,
108    Verify,
109    Accept,
110    Decline,
111}
112
113impl TaskVerb {
114    pub fn as_str(self) -> &'static str {
115        match self {
116            TaskVerb::Show => "show",
117            TaskVerb::Claim => "claim",
118            TaskVerb::Verify => "verify",
119            TaskVerb::Accept => "accept",
120            TaskVerb::Decline => "decline",
121        }
122    }
123}
124
125/// The structured part of a task notice ([`TASK_ACTION_KEY`]).
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127pub struct TaskAction {
128    /// The task number (of the project's vault, or its local tasks).
129    pub task: u64,
130    /// What may be done with it, `show` first.
131    pub actions: Vec<TaskVerb>,
132}
133
134impl TaskAction {
135    pub fn new(task: u64, actions: &[TaskVerb]) -> Self {
136        Self {
137            task,
138            actions: actions.to_vec(),
139        }
140    }
141
142    /// The exact `ctx_tasks` call(s) for an agent, e.g.
143    /// `ctx_tasks action=show number=7, then action=claim number=7`.
144    ///
145    /// Invariant: the call (the `next:` line `ctx_agent action=read` shows)
146    /// is built ONLY from the task number (`u64`) and the known
147    /// [`TaskVerb`]s, never from message text or any other string.
148    pub fn call(&self) -> String {
149        let n = self.task;
150        let mut out = format!("ctx_tasks action=show number={n}");
151        let next: Vec<String> = self
152            .actions
153            .iter()
154            .filter(|verb| **verb != TaskVerb::Show)
155            .map(|verb| match verb {
156                TaskVerb::Verify => format!(
157                    "action=verify number={n} verdict=accept|reject (not by the agent that did the work)"
158                ),
159                other => format!("action={} number={n}", other.as_str()),
160            })
161            .collect();
162        if !next.is_empty() {
163            out.push_str(", then ");
164            out.push_str(&next.join(" or "));
165        }
166        out
167    }
168
169    /// The action a bus entry carries, if any (an unreadable one: none).
170    /// Only the two task-notice senders ([`SENDER`] for Cloud task events,
171    /// [`crate::tasks::local::SENDER`] for local tasks) carry one: the same
172    /// metadata on any other sender's entry is ignored, so no agent can
173    /// make `read` show another agent a `next:` call.
174    pub fn of(entry: &lean_ctx::core::agents::ScratchpadEntry) -> Option<Self> {
175        if entry.from_agent != SENDER && entry.from_agent != crate::tasks::local::SENDER {
176            return None;
177        }
178        entry
179            .metadata
180            .get(TASK_ACTION_KEY)
181            .and_then(|value| serde_json::from_str(value).ok())
182    }
183
184    /// Store this action on the bus entry `id` of `registry`.
185    pub fn attach(&self, registry: &mut lean_ctx::core::agents::AgentRegistry, id: &str) {
186        let Ok(value) = serde_json::to_string(self) else {
187            return;
188        };
189        if let Some(entry) = registry.scratchpad.iter_mut().find(|e| e.id == id) {
190            entry.metadata.insert(TASK_ACTION_KEY.to_owned(), value);
191        }
192    }
193}
194
195/// One post a task change asks for.
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct Notice {
198    /// `None` = every agent of the project.
199    pub to: Option<String>,
200    /// Plain language for people: no tool syntax.
201    pub text: String,
202    /// What an agent or a person may do next, when anything.
203    pub action: Option<TaskAction>,
204}
205
206impl Notice {
207    pub fn new(to: Option<String>, text: String, action: Option<TaskAction>) -> Self {
208        Self { to, text, action }
209    }
210}
211
212/// A result to check goes to every agent of the project except `worker`,
213/// the one that did the work (no self-verify); when that agent is not on
214/// this bus, to every agent.
215pub fn to_checkers(notice: Notice, worker: &str, local: &[String]) -> Vec<Notice> {
216    if !local.iter().any(|agent| agent == worker) {
217        return vec![notice];
218    }
219    local
220        .iter()
221        .filter(|agent| agent.as_str() != worker)
222        .map(|agent| Notice {
223            to: Some(agent.clone()),
224            ..notice.clone()
225        })
226        .collect()
227}
228
229/// The local posts an event asks for. `local` are the project's active
230/// agents.
231pub fn notices(event: &TaskEvent, local: &[String]) -> Vec<Notice> {
232    let n = event.number;
233    match event.event {
234        TaskEventKind::Opened | TaskEventKind::Released | TaskEventKind::Rejected => {
235            let text = match event.event {
236                TaskEventKind::Opened => format!("Task #{n} is open and can be claimed."),
237                TaskEventKind::Released => format!("Task #{n} is open again: its claim ended."),
238                _ => format!("Task #{n} is open again: a check rejected its result."),
239            };
240            let action = TaskAction::new(n, &[TaskVerb::Show, TaskVerb::Claim]);
241            vec![Notice::new(None, text, Some(action))]
242        }
243        TaskEventKind::Submitted => {
244            let notice = Notice::new(
245                None,
246                format!("Task #{n} has a result to check."),
247                Some(TaskAction::new(n, &[TaskVerb::Show, TaskVerb::Verify])),
248            );
249            // `by.worker_id` is the agent id the claim and result named
250            // (Cloud compares the same string for self_verify).
251            let worker = event.by.worker_id.as_deref().unwrap_or_default();
252            to_checkers(notice, worker, local)
253        }
254        _ => Vec::new(),
255    }
256}
257
258/// The last change applied to one task.
259#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
260pub struct TaskSeen {
261    pub state: TaskState,
262    /// Cloud's time of the change (unix ms); a catch-up has it to the second.
263    pub at: u64,
264    /// Recorded by a catch-up, not by a frame.
265    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
266    pub caught_up: bool,
267}
268
269/// Vault address (`#ws/vault`) → task number → the last change applied.
270pub type TasksSeen = BTreeMap<String, BTreeMap<u64, TaskSeen>>;
271
272/// Tasks remembered per vault (the oldest changes drop first).
273#[cfg(any(test, feature = "http-server"))]
274const MAX_SEEN: usize = 1000;
275
276/// Where an event came from.
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub enum Origin {
279    /// A `task.event` frame.
280    Frame,
281    /// A task list read after a hello (`catch_up`).
282    CatchUp,
283}
284
285/// Record `event` in `seen`; whether its notices are due. An event older
286/// than the change already applied is dropped. A catch-up announces only a
287/// task whose state changed since; a frame repeats nothing a catch-up of
288/// the same change (same state, same second) already announced.
289#[cfg(any(test, feature = "http-server"))]
290fn admit(seen: &mut TasksSeen, event: &TaskEvent, origin: Origin) -> bool {
291    let tasks = seen.entry(event.vault.clone()).or_default();
292    let notify = match tasks.get(&event.number) {
293        None => true,
294        Some(last) if event.at < last.at => return false,
295        Some(last) => match origin {
296            Origin::Frame => {
297                !(last.caught_up && last.state == event.state && event.at < last.at + 1000)
298            }
299            Origin::CatchUp if event.at > last.at && last.state != event.state => true,
300            Origin::CatchUp => return false,
301        },
302    };
303    tasks.insert(
304        event.number,
305        TaskSeen {
306            state: event.state,
307            at: event.at,
308            caught_up: origin == Origin::CatchUp,
309        },
310    );
311    while tasks.len() > MAX_SEEN {
312        let Some(oldest) = tasks.iter().min_by_key(|(_, s)| s.at).map(|(n, _)| *n) else {
313            break;
314        };
315        tasks.remove(&oldest);
316    }
317    notify
318}
319
320/// Apply one event: outdate the vault's task cache and post its notices
321/// into the project's local bus, unless `seen` already holds this change
322/// or a newer one. An unknown vault changes nothing.
323#[cfg(feature = "http-server")]
324pub(crate) fn apply(
325    registry: &mut AgentRegistry,
326    map: &VaultMap,
327    data_dir: &Path,
328    seen: &mut TasksSeen,
329    event: &TaskEvent,
330    origin: Origin,
331) -> Result<(), String> {
332    let Ok(Address::Vault { workspace, vault }) = Address::parse(Some(&event.vault)) else {
333        return Ok(());
334    };
335    let Some(record) = map
336        .vaults
337        .values()
338        .find(|r| r.ns == workspace && r.name == vault)
339    else {
340        return Ok(());
341    };
342    crate::tasks::cache::outdate(data_dir, &record.vault_id);
343    if !admit(seen, event, origin) {
344        return Ok(());
345    }
346    let Some(root) = record.roots.iter().find(|root| Path::new(root).is_dir()) else {
347        return Ok(());
348    };
349    let local: Vec<String> = registry
350        .list_active(Some(root))
351        .into_iter()
352        .map(|a| a.agent_id.clone())
353        .collect();
354    let source = match origin {
355        Origin::Frame => "",
356        Origin::CatchUp => "caught_up:",
357    };
358    let key = format!(
359        "{}task:{}:{}:{:?}:{source}{}",
360        super::relay_v2::INBOUND_KEY_PREFIX,
361        event.vault,
362        event.number,
363        event.event,
364        event.at
365    );
366    for (i, notice) in notices(event, &local).into_iter().enumerate() {
367        let id = registry.post_message_keyed(
368            Some(root),
369            SENDER,
370            notice.to.as_deref(),
371            "status",
372            &notice.text,
373            PrivacyLevel::Team,
374            MessagePriority::Normal,
375            None,
376            Some(&format!("{key}:{i}")),
377        )?;
378        if let Some(action) = &notice.action {
379            action.attach(registry, &id);
380        }
381    }
382    Ok(())
383}
384
385/// The open and submitted tasks of the `subscribed` vaults as events, for
386/// `apply` with [`Origin::CatchUp`], and what could not be read. Blocking
387/// (HTTP); the relay runs it off its session loop after each hello.
388#[cfg(feature = "http-server")]
389pub(crate) fn catch_up(map: &VaultMap, subscribed: &[String]) -> (Vec<TaskEvent>, Vec<String>) {
390    let (mut events, mut errors) = (Vec::new(), Vec::new());
391    for record in map.vaults.values() {
392        let vault = super::relay_v2::address_of(record);
393        if !subscribed.contains(&vault) {
394            continue;
395        }
396        let Some(root) = record.roots.iter().find(|root| Path::new(root).is_dir()) else {
397            continue;
398        };
399        let root = Path::new(root);
400        for (state, kind) in [
401            (TaskState::Open, TaskEventKind::Opened),
402            (TaskState::Submitted, TaskEventKind::Submitted),
403        ] {
404            let filter = ListFilter {
405                state: Some(state),
406                ..ListFilter::default()
407            };
408            // Only a current list: tasks of a stale one (429, Cloud not
409            // reachable) may since be claimed or closed and would wake
410            // Queens as "opened" (review 5!246).
411            let list = match crate::tasks::list_read(root, &filter) {
412                Ok(read) if read.stale.is_none() => read.value,
413                Ok(read) => {
414                    let note = read.stale.map(|s| s.note()).unwrap_or_default();
415                    errors.push(format!("{vault}: {note}"));
416                    continue;
417                }
418                Err(error) => {
419                    errors.push(format!("{vault}: {error}"));
420                    continue;
421                }
422            };
423            for task in list
424                .list
425                .tasks
426                .into_iter()
427                .filter(|task| task.state == state)
428            {
429                // A result's worker gets no request to check its own work.
430                let worker_id = (kind == TaskEventKind::Submitted)
431                    .then(|| crate::tasks::show(root, task.number).ok())
432                    .flatten()
433                    .and_then(|view| view.task.result)
434                    .and_then(|result| result.by.agent);
435                events.push(TaskEvent {
436                    vault: vault.clone(),
437                    number: task.number,
438                    event: kind,
439                    state,
440                    by: TaskEventBy {
441                        worker_id,
442                        ..TaskEventBy::default()
443                    },
444                    at: unix_ms(task.updated_at.as_str()),
445                });
446            }
447        }
448    }
449    (events, errors)
450}
451
452/// `YYYY-MM-DDTHH:MM:SSZ` as unix ms; 0 (older than any change) if invalid.
453#[cfg(any(test, feature = "http-server"))]
454fn unix_ms(timestamp: &str) -> u64 {
455    lean_ctx_time::OffsetDateTime::parse_from_rfc3339(timestamp)
456        .ok()
457        .and_then(|t| u64::try_from(t.timestamp_millis()).ok())
458        .unwrap_or_default()
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464
465    const FIXTURES: &str = concat!(
466        concat!(env!("CARGO_MANIFEST_DIR"), "/../.."),
467        "/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/bus"
468    );
469
470    fn frame(name: &str) -> TaskEvent {
471        let text =
472            std::fs::read_to_string(format!("{FIXTURES}/frame.task_event.{name}.json")).unwrap();
473        let value: Value = serde_json::from_str(&text).unwrap();
474        let event = TaskEvent::parse(&value).unwrap_or_else(|| panic!("{name}"));
475        assert_eq!(
476            super::super::v2::parse_frame(&text).unwrap(),
477            super::super::v2::Inbound::TaskEvent(Box::new(event.clone())),
478            "{name}"
479        );
480        event
481    }
482
483    #[test]
484    fn the_contract_frames_parse() {
485        for (name, kind, state) in [
486            ("opened", TaskEventKind::Opened, TaskState::Open),
487            ("released", TaskEventKind::Released, TaskState::Open),
488            ("submitted", TaskEventKind::Submitted, TaskState::Submitted),
489            ("verified", TaskEventKind::Verified, TaskState::Done),
490        ] {
491            let event = frame(name);
492            assert_eq!((event.event, event.state), (kind, state), "{name}");
493            assert_eq!(event.vault, "#acme/payments");
494        }
495    }
496
497    #[test]
498    fn open_tasks_go_to_every_agent_and_results_to_the_others() {
499        let opened = frame("opened");
500        let out = notices(&opened, &["a1".to_string()]);
501        assert_eq!(out.len(), 1);
502        assert_eq!(out[0].to, None);
503        // People read plain language; the call travels in the structured field.
504        assert_eq!(out[0].text, "Task #7 is open and can be claimed.");
505        let action = out[0].action.clone().unwrap();
506        assert_eq!(
507            action,
508            TaskAction::new(7, &[TaskVerb::Show, TaskVerb::Claim])
509        );
510        assert_eq!(
511            action.call(),
512            "ctx_tasks action=show number=7, then action=claim number=7"
513        );
514        assert_eq!(
515            notices(&frame("released"), &[])[0].text,
516            "Task #7 is open again: its claim ended."
517        );
518
519        let submitted = frame("submitted");
520        let worker = submitted.by.worker_id.clone().unwrap();
521        let others = vec!["a1".to_string(), "a3".to_string()];
522        // Another agent's result: every agent here may check it.
523        assert_eq!(notices(&submitted, &others)[0].to, None);
524        // This machine's agent did the work: never that agent (no self-verify).
525        let local = vec!["a1".to_string(), worker, "a3".to_string()];
526        let to: Vec<_> = notices(&submitted, &local)
527            .into_iter()
528            .map(|notice| {
529                assert_eq!(notice.text, "Task #7 has a result to check.");
530                let call = notice.action.unwrap().call();
531                assert_eq!(
532                    call,
533                    "ctx_tasks action=show number=7, then action=verify number=7 verdict=accept|reject (not by the agent that did the work)"
534                );
535                notice.to.unwrap()
536            })
537            .collect();
538        assert_eq!(to, ["a1", "a3"]);
539
540        assert!(notices(&frame("verified"), &local).is_empty());
541    }
542
543    #[test]
544    fn notice_texts_carry_no_tool_syntax_or_product_name() {
545        let local = vec!["a1".to_string()];
546        for name in ["opened", "released", "submitted"] {
547            for notice in notices(&frame(name), &local) {
548                for banned in ["ctx_tasks", "action=", "LeanCTX Cloud"] {
549                    assert!(!notice.text.contains(banned), "{name}: {}", notice.text);
550                }
551            }
552        }
553    }
554
555    #[test]
556    fn a_task_action_round_trips_through_bus_metadata() {
557        let action = TaskAction::new(3, &[TaskVerb::Show, TaskVerb::Accept, TaskVerb::Decline]);
558        let mut entry = lean_ctx::core::agents::ScratchpadEntry {
559            id: "m1".into(),
560            from_agent: "local-tasks".into(),
561            to_agent: None,
562            task_id: None,
563            category: "status".into(),
564            priority: lean_ctx::core::a2a::message::MessagePriority::Normal,
565            privacy: lean_ctx::core::a2a::message::PrivacyLevel::Team,
566            message: "Local task #3 was proposed.".into(),
567            metadata: Default::default(),
568            project_root: None,
569            timestamp: lean_ctx_time::UtcDateTime::now(),
570            read_by: Vec::new(),
571            expires_at: None,
572        };
573        assert_eq!(TaskAction::of(&entry), None);
574        entry.metadata.insert(
575            TASK_ACTION_KEY.into(),
576            serde_json::to_string(&action).unwrap(),
577        );
578        assert_eq!(
579            entry.metadata[TASK_ACTION_KEY],
580            r#"{"task":3,"actions":["show","accept","decline"]}"#
581        );
582        assert_eq!(TaskAction::of(&entry), Some(action.clone()));
583        assert_eq!(
584            action.call(),
585            "ctx_tasks action=show number=3, then action=accept number=3 or action=decline number=3"
586        );
587        // A Cloud task-event notice carries it as well.
588        entry.from_agent = SENDER.into();
589        assert_eq!(TaskAction::of(&entry), Some(action.clone()));
590        // The same metadata from any other sender (an agent): ignored.
591        entry.from_agent = "claude-42".into();
592        assert_eq!(TaskAction::of(&entry), None);
593        entry.from_agent = crate::tasks::local::SENDER.into();
594        // An unknown verb: no action, never a guessed call.
595        entry.metadata.insert(
596            TASK_ACTION_KEY.into(),
597            r#"{"task":3,"actions":["rm"]}"#.into(),
598        );
599        assert_eq!(TaskAction::of(&entry), None);
600    }
601
602    /// Task 7 of the fixture vault in `state` at `at` (unix ms).
603    fn change(event: TaskEventKind, state: TaskState, at: u64) -> TaskEvent {
604        TaskEvent {
605            event,
606            state,
607            at,
608            ..frame("opened")
609        }
610    }
611
612    #[test]
613    fn a_task_opened_while_subscribing_is_announced_once_by_the_catch_up() {
614        let mut seen = TasksSeen::new();
615        // The frame went by before the hello: only the catch-up sees it.
616        let listed = change(TaskEventKind::Opened, TaskState::Open, 1_792_800_020_000);
617        assert!(admit(&mut seen, &listed, Origin::CatchUp));
618        // The same change as a frame (same second, ms precision): no repeat.
619        let late = change(TaskEventKind::Opened, TaskState::Open, 1_792_800_020_431);
620        assert!(!admit(&mut seen, &late, Origin::Frame));
621        // A second catch-up of the unchanged task: still nothing.
622        assert!(!admit(&mut seen, &listed, Origin::CatchUp));
623    }
624
625    #[test]
626    fn a_catch_up_never_repeats_or_rewinds_what_a_frame_announced() {
627        let mut seen = TasksSeen::new();
628        let opened = change(TaskEventKind::Opened, TaskState::Open, 1_792_800_020_431);
629        assert!(admit(&mut seen, &opened, Origin::Frame));
630        // The list read the same change (to the second): no repeat.
631        let listed = change(TaskEventKind::Opened, TaskState::Open, 1_792_800_020_000);
632        assert!(!admit(&mut seen, &listed, Origin::CatchUp));
633        // The task is done; a list read before that is stale and says nothing.
634        let done = change(TaskEventKind::Verified, TaskState::Done, 1_792_800_030_000);
635        assert!(admit(&mut seen, &done, Origin::Frame));
636        assert!(!admit(&mut seen, &listed, Origin::CatchUp));
637        assert_eq!(seen["#acme/payments"][&7].state, TaskState::Done);
638    }
639
640    #[test]
641    fn a_task_open_again_is_announced_even_when_its_claim_was_missed() {
642        let mut seen = TasksSeen::new();
643        let opened = change(TaskEventKind::Opened, TaskState::Open, 1_000);
644        assert!(admit(&mut seen, &opened, Origin::Frame));
645        // `claimed` never arrived; the release still says "open again".
646        let released = change(TaskEventKind::Released, TaskState::Open, 9_000);
647        assert!(admit(&mut seen, &released, Origin::Frame));
648        // Reopened while the relay was away: the catch-up announces it.
649        let claimed = change(TaskEventKind::Claimed, TaskState::Claimed, 10_000);
650        assert!(admit(&mut seen, &claimed, Origin::Frame));
651        let reopened = change(TaskEventKind::Opened, TaskState::Open, 20_000);
652        assert!(admit(&mut seen, &reopened, Origin::CatchUp));
653        // A frame older than what was applied is dropped.
654        assert!(!admit(&mut seen, &claimed, Origin::Frame));
655        assert_eq!(seen["#acme/payments"][&7].state, TaskState::Open);
656    }
657
658    #[test]
659    fn the_oldest_changes_drop_first() {
660        let mut seen = TasksSeen::new();
661        for number in 1..=(MAX_SEEN as u64 + 1) {
662            let event = TaskEvent {
663                number,
664                ..change(TaskEventKind::Opened, TaskState::Open, number)
665            };
666            assert!(admit(&mut seen, &event, Origin::Frame));
667        }
668        let tasks = &seen["#acme/payments"];
669        assert_eq!(tasks.len(), MAX_SEEN);
670        assert!(!tasks.contains_key(&1));
671    }
672
673    #[test]
674    fn listed_times_are_unix_ms() {
675        assert_eq!(unix_ms("2026-10-15T08:00:20Z"), 1_792_051_220_000);
676        assert_eq!(unix_ms("not a time"), 0);
677    }
678}