Skip to main content

agentmux_srv_core/backend/vault/
expiry.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Expiry dates and their reminders
5//! (docs/specs/SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md ยง15.2).
6//!
7//! An entry's `expires` field is a plain date (`YYYY-MM-DD`): no secret, so
8//! srv reads it on a schedule without opening anything. At 14 days, 3 days and
9//! on the day the person is notified, once each: the reminder is a line in the
10//! Vault's activity log, which is what says it was sent, across restarts. The
11//! first reminder for a date also files a task to rotate the value, for the
12//! agent that made it when an agent did.
13//!
14//! An expired entry stays usable, so a reminder never breaks a running job;
15//! each use of one is recorded with "(expired)".
16
17use std::sync::Arc;
18use std::time::Duration;
19
20use agentmux_common::time::now_ms;
21use chrono::NaiveDate;
22
23use super::{kinds, record, PERSON};
24use crate::backend::mps::Broker;
25use crate::backend::storage::store::Store;
26use crate::backend::storage::vault::VaultRow;
27use crate::backend::storage::work_board::{requested, NewCard, WorkEvent};
28use crate::backend::storage::work_queue::{work_state, WorkItem};
29
30/// The field that holds an entry's expiry date.
31pub const FIELD: &str = "expires";
32/// Who the activity log and the task name for the reminders.
33pub const ACTOR: &str = "Vault";
34pub const REMINDED: &str = "reminded";
35/// The rotation task's `kind`.
36pub const TASK_KIND: &str = "vault-rotation";
37/// In a reminder's activity line once its rotation task is filed.
38const TASK_MARK: &str = "; rotation task #";
39/// How often srv looks, besides at start.
40const EVERY: Duration = Duration::from_secs(6 * 60 * 60);
41/// The actions that make or replace an entry's value: the agent behind the
42/// latest one is asked to rotate it. A restore is the person's choice of value.
43const MADE: &[&str] = &crate::backend::storage::vault::VALUE_SETTING;
44
45/// A date as the Vault keeps it, or why it isn't one.
46pub fn parse(text: &str) -> Result<NaiveDate, String> {
47    let text = text.trim();
48    if text.len() != 10 {
49        return Err(format!("expires is a date as YYYY-MM-DD, not {:?}", clip(text)));
50    }
51    NaiveDate::parse_from_str(text, "%Y-%m-%d").map_err(|_| format!("expires is a date as YYYY-MM-DD, not {:?}", clip(text)))
52}
53
54/// A date another manager or an older backup wrote: `YYYY-MM-DD` as it is, and a
55/// month (`06/2028`, `6/2028`, `2028-06`) as its last day. None for anything else.
56pub fn normalize(text: &str) -> Option<String> {
57    let text = text.trim();
58    if let Ok(d) = parse(text) {
59        return Some(d.to_string());
60    }
61    let (y, m) = match text.split_once('/') {
62        Some((m, y)) => (y.trim(), m.trim()),
63        None => text.split_once('-')?,
64    };
65    let (y, m): (i32, u32) = (y.parse().ok().filter(|_| y.len() == 4)?, m.parse().ok()?);
66    let first_of_next = if m == 12 { NaiveDate::from_ymd_opt(y + 1, 1, 1) } else { NaiveDate::from_ymd_opt(y, m + 1, 1) };
67    first_of_next.filter(|_| (1..=12).contains(&m)).and_then(|d| d.pred_opt()).map(|d| d.to_string())
68}
69
70/// An imported entry's `expires`, made a date the Vault keeps: normalized when it
71/// can be, else moved into the entry's notes, so no entry is refused for it and
72/// no text is lost.
73pub fn settle_imported(kind: &kinds::Kind, fields: &mut std::collections::BTreeMap<String, String>) {
74    let Some(text) = fields.remove(FIELD) else { return };
75    match normalize(&text) {
76        Some(date) => {
77            fields.insert(FIELD.to_string(), date);
78        }
79        None if kind.fields.contains(&"notes") => {
80            let line = format!("Expires: {text}");
81            let notes = fields.remove("notes").filter(|n| !n.is_empty()).map(|n| format!("{n}\n{line}")).unwrap_or(line);
82            fields.insert("notes".to_string(), notes);
83        }
84        None => {}
85    }
86}
87
88fn clip(text: &str) -> String {
89    text.chars().take(40).collect()
90}
91
92pub fn today() -> NaiveDate {
93    chrono::Local::now().date_naive()
94}
95
96/// An entry's expiry date, if its kind has one and it holds a date.
97pub fn of(row: &VaultRow) -> Option<NaiveDate> {
98    if !kinds::kind(&row.kind).is_some_and(|k| k.fields.contains(&FIELD)) {
99        return None;
100    }
101    let fields: std::collections::BTreeMap<String, String> = serde_json::from_str(&row.fields).ok()?;
102    parse(fields.get(FIELD)?).ok()
103}
104
105/// Whether an entry is past its date: usable still, but its uses say so.
106pub fn expired(row: &VaultRow, today: NaiveDate) -> bool {
107    of(row).is_some_and(|d| d < today)
108}
109
110/// The three reminders.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum Stage {
113    TwoWeeks,
114    ThreeDays,
115    OnTheDay,
116}
117
118impl Stage {
119    /// The reminder due `days_left` before the date, if any: the nearest one, so
120    /// an entry saved 2 days before its date gets the 3-day reminder, not three.
121    pub fn due(days_left: i64) -> Option<Stage> {
122        match days_left {
123            d if d <= 0 => Some(Stage::OnTheDay),
124            1..=3 => Some(Stage::ThreeDays),
125            4..=14 => Some(Stage::TwoWeeks),
126            _ => None,
127        }
128    }
129
130    fn words(self) -> &'static str {
131        match self {
132            Stage::TwoWeeks => "14 days before",
133            Stage::ThreeDays => "3 days before",
134            Stage::OnTheDay => "on the day",
135        }
136    }
137}
138
139/// The activity line's target that says this reminder for this date was sent.
140/// The date is in it, so a new date starts its reminders again.
141pub fn reminder_key(date: NaiveDate, stage: Stage) -> String {
142    format!("expires {date}, {}", stage.words())
143}
144
145/// What the person reads.
146pub fn notice(date: NaiveDate, days_left: i64) -> String {
147    match days_left {
148        d if d < 0 => format!("Expired on {date}. It still works where it is used, until it's replaced."),
149        0 => format!("Expires today, {date}."),
150        1 => format!("Expires tomorrow, {date}."),
151        d => format!("Expires in {d} days, on {date}."),
152    }
153}
154
155/// A reminder to send.
156#[derive(Debug, Clone, PartialEq)]
157pub struct Due {
158    pub id: String,
159    pub label: String,
160    pub date: NaiveDate,
161    pub days_left: i64,
162    pub stage: Stage,
163    /// No rotation task was filed for this date yet: this reminder files it, so
164    /// one that couldn't be filed is tried again at the next reminder.
165    pub first: bool,
166    /// The agent that made or last replaced the value, if one did.
167    pub agent: Option<String>,
168    /// Whether a rotation task is filed: not for a card, which the person replaces with the bank.
169    pub rotates: bool,
170}
171
172/// The reminders due today that haven't been sent.
173pub fn due(store: &Store, today: NaiveDate) -> Result<Vec<Due>, String> {
174    let mut out = Vec::new();
175    for row in store.vault_list().map_err(|e| e.to_string())? {
176        let Some(date) = of(&row) else { continue };
177        let days_left = (date - today).num_days();
178        let Some(stage) = Stage::due(days_left) else { continue };
179        // By action, so a key's many uses never push these lines out. Three
180        // reminders a date: an entry's whole history of them is short.
181        let reminded = store.vault_activity_for_entry(&row.id, &[REMINDED], row.created_at, 10_000).map_err(|e| e.to_string())?;
182        let sent_for_date = format!("expires {date}, ");
183        let sent: Vec<&str> = reminded.iter().filter(|l| l.target.starts_with(&sent_for_date)).map(|l| l.target.as_str()).collect();
184        if sent.iter().any(|t| t.starts_with(&reminder_key(date, stage))) {
185            continue;
186        }
187        // The latest line that made the value.
188        let made = store.vault_activity_for_entry(&row.id, MADE, row.created_at, 1).map_err(|e| e.to_string())?;
189        let agent = made.into_iter().next().map(|l| super::history::agent_of(&l.actor).to_string()).filter(|a| a != PERSON && !a.is_empty());
190        let rotates = row.kind != super::card::KIND;
191        out.push(Due { id: row.id, label: row.label, date, days_left, stage, first: !sent.iter().any(|t| t.contains(TASK_MARK)), agent, rotates });
192    }
193    Ok(out)
194}
195
196pub fn task_title(d: &Due) -> String {
197    format!("Rotate {}: it expires on {}", d.label, d.date)
198}
199
200pub fn task_body(d: &Due) -> String {
201    format!(
202        "The Vault entry `{}` ({}) expires on {}.\n\n\
203         Make a new value where it is issued, put it where the old one is used, and save it in the entry, \
204         without seeing it: `Vault` `generate` makes one the Vault keeps, and `Terminal` `run` with `secrets`, \
205         `stdin_secret` or `secret_files` hands it to a command. Then set the entry's new expiry date.\n\n\
206         The old value keeps working until it expires, so nothing breaks before then.",
207        d.id, d.label, d.date
208    )
209}
210
211/// Files the rotation task, as `kanban.act` `create` does; returns its number.
212pub fn file_task(work: &Store, d: &Due, now: i64) -> Result<i64, String> {
213    let item = WorkItem {
214        id: uuid::Uuid::new_v4().to_string(),
215        title: task_title(d),
216        payload: task_body(d),
217        kind: TASK_KIND.to_string(),
218        target_agent: d.agent.clone().unwrap_or_default(),
219        target_group: String::new(),
220        priority: 0,
221        state: String::new(),
222        claimed_by: String::new(),
223        target_agent_uid: String::new(),
224        claimed_by_uid: String::new(),
225        claim_expires: None,
226        attempts: 0,
227        max_attempts: 3,
228        created_by: ACTOR.to_string(),
229        created_by_uid: String::new(),
230        created_at: now,
231        updated_at: now,
232        not_before: None,
233        result: String::new(),
234    };
235    work.work_queue_enqueue(&item).map_err(|e| e.to_string())?;
236    let card = NewCard {
237        review_required: false,
238        requested_by: ACTOR.to_string(),
239        requested_by_kind: requested::OTHER.to_string(),
240        filed_by: ACTOR.to_string(),
241        ..Default::default()
242    };
243    let num = work.work_card_create(&item.id, &card, now).map_err(|e| e.to_string())?;
244    let event = WorkEvent {
245        work_id: item.id.clone(),
246        at: now,
247        actor: ACTOR.to_string(),
248        actor_kind: "system".to_string(),
249        kind: "created".to_string(),
250        to_state: work_state::OPEN.to_string(),
251        ..Default::default()
252    };
253    work.work_event_add(&event).map_err(|e| e.to_string())?;
254    Ok(num)
255}
256
257/// What one look sent: the notifications to show, and whether a task was filed.
258pub struct Sent {
259    pub notices: Vec<(Due, String)>,
260    pub filed: bool,
261}
262
263/// Records each reminder due and files the rotation tasks. The notifications
264/// are the caller's to show: the record is written first, so a crash between
265/// the two never repeats a reminder.
266pub fn send(store: &Store, work: Option<&Store>, today: NaiveDate) -> Result<Sent, String> {
267    let mut sent = Sent { notices: Vec::new(), filed: false };
268    for d in due(store, today)? {
269        let mut target = reminder_key(d.date, d.stage);
270        if d.first && d.rotates {
271            if let Some(work) = work {
272                match file_task(work, &d, now_ms()) {
273                    Ok(num) => {
274                        sent.filed = true;
275                        let whom = d.agent.as_deref().map(|a| format!(" for {a}")).unwrap_or_default();
276                        target.push_str(&format!("{TASK_MARK}{num}{whom}"));
277                    }
278                    Err(e) => tracing::warn!(entry = %d.id, error = %e, "vault: couldn't file a rotation task"),
279                }
280            }
281        }
282        record(store, &d.id, &d.label, ACTOR, REMINDED, &target, "done");
283        let text = notice(d.date, d.days_left);
284        sent.notices.push((d, text));
285    }
286    Ok(sent)
287}
288
289/// The notification's key: one per entry.
290pub fn notify_key(id: &str) -> String {
291    format!("vault:{id}")
292}
293
294/// Most notifications one look shows; more entries due share one.
295pub const MAX_TOASTS: usize = 3;
296
297/// One notification to show: its key, the name its title gives, and its text.
298#[derive(Debug, PartialEq)]
299pub struct Toast {
300    pub key: String,
301    pub name: String,
302    pub body: String,
303}
304
305/// The notifications for one look's reminders: one each, or, past
306/// `MAX_TOASTS`, one for them all, so an import never floods the screen.
307pub fn toasts(notices: &[(Due, String)]) -> Vec<Toast> {
308    if notices.len() <= MAX_TOASTS {
309        return notices.iter().map(|(d, text)| Toast { key: notify_key(&d.id), name: d.label.clone(), body: text.clone() }).collect();
310    }
311    let named: Vec<&str> = notices.iter().take(MAX_TOASTS).map(|(d, _)| d.label.as_str()).collect();
312    let body = format!(
313        "{}, and {} more expire within 14 days, or have expired. The Vault's Expiring soon filter lists them.",
314        named.join(", "),
315        notices.len() - named.len()
316    );
317    vec![Toast { key: "vault:expiring".into(), name: format!("{} entries", notices.len()), body }]
318}
319
320/// Looks at start and every 6 hours. A reminder is recorded as sent, so a look
321/// waits until it can be shown: for the notification router, which starts with
322/// the first window, and past a pause or quiet hours, which would drop it.
323pub async fn run(store: Arc<Store>, work: Arc<Store>, broker: Arc<Broker>) {
324    loop {
325        match crate::backend::notify::router::get(&broker) {
326            Some(router) if !router.holds_back_attention() => {}
327            _ => {
328                tokio::time::sleep(Duration::from_secs(15 * 60)).await;
329                continue;
330            }
331        }
332        let (s, w) = (store.clone(), work.clone());
333        match tokio::task::spawn_blocking(move || send(&s, Some(&w), today())).await {
334            Ok(Ok(sent)) => {
335                if sent.filed {
336                    broker.publish_event::<crate::backend::mps_events::WorkQueueChanged>(&(), vec![], 0);
337                }
338                if !sent.notices.is_empty() {
339                    // The Activity list has new lines.
340                    let event = crate::backend::mps_events::VaultEvent {
341                        requests: super::requests::requests().list(),
342                        uses: super::uses::uses().list(),
343                        changed_ms: agentmux_common::time::now_ms_u64(),
344                    };
345                    broker.publish_event::<crate::backend::mps_events::Vault>(&event, vec![], 0);
346                }
347                for (d, _) in &sent.notices {
348                    tracing::info!(entry = %d.id, date = %d.date, "vault: expiry reminder");
349                }
350                if let Some(router) = crate::backend::notify::router::get(&broker) {
351                    for t in toasts(&sent.notices) {
352                        let router = router.clone();
353                        let _ = tokio::task::spawn_blocking(move || router.vault_expiring(&t.key, &t.name, t.body)).await;
354                    }
355                }
356            }
357            Ok(Err(e)) => tracing::warn!(error = %e, "vault: couldn't check expiry dates"),
358            Err(e) => tracing::warn!(error = %e, "vault: the expiry check stopped"),
359        }
360        tokio::time::sleep(EVERY).await;
361    }
362}
363
364#[cfg(test)]
365#[path = "expiry_tests.rs"]
366mod tests;