Skip to main content

agentmux_srv_core/backend/vault/
linked.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A linked entry: an entry that says where a key lives and who reads it, and holds no value
5//! (docs/specs/SPEC_VAULT_LINKED_ENTRIES_FLEET_VAULT_AND_BATCH_IMPORT_2026_11_15.md §2).
6//!
7//! A key that a machine role reads must stay where that role can reach it, so it never gets into the Vault. A linked
8//! entry lets the Vault say that the key exists, where it is, who reads it, when it expires and whether it changed. It
9//! is an ordinary entry of an ordinary kind, marked by the plain field `link` set to `only`, with the place in the
10//! machine copy's fields ([`super::source_link`]). Its check reads the place's description and never the key, so no
11//! value reaches srv and nothing needs the person's yes.
12
13use std::collections::BTreeMap;
14
15use agentmux_common::time::now_ms;
16use chrono::NaiveDate;
17use serde::Serialize;
18
19use super::aws_import::{self, Described, Imported, Plan, Source, Target, Via, NO_SUCH_SECRET};
20use super::source_link::{self, CheckPlan, Checked, Link, Outcome, VaultSourceCheck, AWS_SECRET, GITHUB_SECRET, OTHER};
21use super::{expiry, github_secret, history, insert_unrecorded, record_line, record_row, signins, Line, NewEntry, Parts};
22use crate::backend::storage::store::Store;
23use crate::backend::storage::vault::{VaultActivityRow, VaultRow};
24use crate::identity::aws_broker::mint::Runner;
25
26/// The field that marks a linked entry, and the one thing it may say.
27pub const LINK: &str = "link";
28pub const ONLY: &str = "only";
29/// A linked entry whose key the Vault reads from its place at each use and keeps no copy of: the secret in AWS
30/// Secrets Manager is the authority (SPEC_VAULT_SHARED_ACROSS_MACHINES_LAN_AND_CLOUD_2026_11_01.md §11.1).
31pub const BACKED: &str = "backed";
32/// Who or what reads the key, one line each: `invoice-sync (lambda): at run time`. Free text; the Vault enforces none of it.
33pub const READERS: &str = "readers";
34/// When the key was last changed, as recorded: a date. A linked entry's own, since the Vault holds no value to date.
35pub const ROTATED: &str = "rotated";
36/// Other places the same key is kept, one line each: `kind: location#key`.
37pub const COPIES: &str = "copies";
38pub const FIELDS: [&str; 4] = [LINK, READERS, ROTATED, COPIES];
39/// What is said of the key, as a KeePass export names it, so a database written from the Vault brings it back.
40pub const TITLES: [(&str, &str); 3] = [(READERS, "Read by"), (ROTATED, "Last changed"), (COPIES, "Also kept at")];
41/// The KeePass field that marks a linked entry. It holds the entry's kind: a link has no secret field to say it.
42pub const KIND_TITLE: &str = "Linked entry kind";
43pub const MAX_READERS: usize = 8;
44pub const MAX_COPIES: usize = 4;
45const MAX_LINE: usize = 200;
46
47/// The Activity action of an entry made as a link.
48pub const LINKED: &str = "linked";
49/// The Activity action of a check of one of a linked entry's other places. Its own action, so the newest `checked`
50/// line is always the entry's own place, and an agent's check counts once toward the hour's limit.
51pub const CHECKED_COPY: &str = "checked a copy";
52/// A linked entry nobody has checked for this many days is counted as unchecked.
53pub const UNCHECKED_DAYS: i64 = 30;
54const DAY_MS: i64 = 24 * 60 * 60 * 1000;
55/// Why a change that would make an entry a link, or a link an entry with a value, is refused.
56pub const SET_WHEN_MADE: &str = "whether an entry is a link (it holds no value) is set when it is made: make a new entry instead";
57const NOT_FROM_HERE: &str = "this kind of place can't be described from here: only an AWS secret and a CI secret are";
58const NOT_UNDER_AWS: &str = "an AWS copy is described under the entry's own AWS place, and this entry's place isn't in AWS";
59
60/// Whether `name` is one of a link's fields, which every kind of entry may have.
61pub fn is_field(name: &str) -> bool {
62    FIELDS.contains(&name)
63}
64
65/// Whether the entry with these fields is a link: it holds no value (a backed entry is one, its value lives in AWS).
66pub fn is_linked(fields: &BTreeMap<String, String>) -> bool {
67    fields.get(LINK).is_some_and(|v| v == ONLY || v == BACKED)
68}
69
70/// The link mark an entry's fields carry: `only`, `backed` or none. Whether an entry is a link, and which kind, is set
71/// when it is made, so a change of this value is refused (`SET_WHEN_MADE`), `only` to `backed` and back included.
72pub fn mark(fields: &BTreeMap<String, String>) -> Option<&str> {
73    fields.get(LINK).map(|v| v.trim()).filter(|v| !v.is_empty())
74}
75
76/// Whether the entry with these fields is backed: its value is read from AWS Secrets Manager each time it is used.
77pub fn is_backed(fields: &BTreeMap<String, String>) -> bool {
78    fields.get(LINK).is_some_and(|v| v == BACKED)
79}
80
81pub fn is_backed_row(row: &VaultRow) -> bool {
82    is_backed(&fields_of(row))
83}
84
85fn fields_of(row: &VaultRow) -> BTreeMap<String, String> {
86    serde_json::from_str(&row.fields).unwrap_or_default()
87}
88
89pub fn is_linked_row(row: &VaultRow) -> bool {
90    is_linked(&fields_of(row))
91}
92
93/// The lines of a field that holds one thing a line (`readers`, `copies`), trimmed, without the empty ones.
94pub fn lines(text: &str) -> Vec<&str> {
95    text.lines().map(str::trim).filter(|l| !l.is_empty()).collect()
96}
97
98/// A place as a line of `copies` writes it, and as a refusal names it: `aws-secret: staging/app#db.password`.
99pub fn place_text(link: &Link) -> String {
100    match link.key.as_str() {
101        "" => format!("{}: {}", link.kind, link.location),
102        key => format!("{}: {}#{key}", link.kind, link.location),
103    }
104}
105
106/// The place a line of `copies` names, held to what that kind of place may be.
107fn copy_of(line: &str) -> Result<Link, String> {
108    let wrong = |why: &str| format!("a line of {COPIES} is `kind: location#key`, with the kind {AWS_SECRET}, {GITHUB_SECRET} or {OTHER}; {:?} isn't one ({why})", history::one_line(line, 60));
109    let (kind, rest) = line.split_once(':').ok_or_else(|| wrong("it names no kind"))?;
110    let (location, key) = rest.rsplit_once('#').unwrap_or((rest, ""));
111    let named = [(source_link::KIND, kind), (source_link::LOCATION, location), (source_link::KEY, key)];
112    let fields: BTreeMap<String, String> = named.into_iter().map(|(k, v)| (k.to_string(), v.trim().to_string())).filter(|(_, v)| !v.is_empty()).collect();
113    source_link::validate(&fields).map_err(|why| wrong(&why))?;
114    Link::of(&fields).ok_or_else(|| wrong("it names no place"))
115}
116
117/// The other places an entry says its key is kept, in order. A line that names no place is left out: `validate`
118/// refuses one before it is saved.
119pub fn copies(fields: &BTreeMap<String, String>) -> Vec<Link> {
120    lines(fields.get(COPIES).map_or("", String::as_str)).into_iter().filter_map(|l| copy_of(l).ok()).collect()
121}
122
123/// Whether the link's fields in `fields` are ones the Vault keeps, for an entry that holds a value (`has_value`) or
124/// none. A linked entry names its place and holds nothing; who reads a key and where else it is kept may be said of
125/// any entry.
126pub fn validate(fields: &BTreeMap<String, String>, has_value: bool) -> Result<(), String> {
127    let linked = match fields.get(LINK).map(String::as_str) {
128        None => false,
129        Some(ONLY | BACKED) => true,
130        Some(_) => return Err(format!("{LINK} is \"{ONLY}\", for an entry that records where a key lives and holds no value, \"{BACKED}\", for one that reads its value from AWS Secrets Manager at each use, or is left out")),
131    };
132    if linked && Link::of(fields).is_none() {
133        return Err(format!("a linked entry says where the key lives: set {} and {}", source_link::KIND, source_link::LOCATION));
134    }
135    if is_backed(fields) && !Link::of(fields).is_some_and(|l| l.kind == AWS_SECRET) {
136        return Err(format!("a backed entry is read from an AWS secret: set {} to {AWS_SECRET}", source_link::KIND));
137    }
138    if linked && has_value {
139        return Err("a linked entry holds no value: leave the value out, or leave link out to keep the value in the Vault".into());
140    }
141    // A saved sign-in is offered by its site and filled with its password, which a link does not have.
142    if linked && fields.contains_key(signins::SITE) {
143        return Err(format!("a linked entry holds no password, so it is not a saved sign-in: leave {} out", signins::SITE));
144    }
145    if let Some(date) = fields.get(ROTATED) {
146        if !linked {
147            return Err(format!("{ROTATED} is for a linked entry: the Vault's own history says when a value it holds was changed"));
148        }
149        expiry::parse(date).map_err(|_| format!("{ROTATED} is the date the key was last changed, as YYYY-MM-DD"))?;
150    }
151    let readers = lines(fields.get(READERS).map_or("", String::as_str));
152    if readers.len() > MAX_READERS || readers.iter().any(|l| l.chars().count() > MAX_LINE) {
153        return Err(format!("{READERS} is who or what reads the key, one line each: at most {MAX_READERS} lines of {MAX_LINE} characters"));
154    }
155    let places = lines(fields.get(COPIES).map_or("", String::as_str));
156    if places.len() > MAX_COPIES {
157        return Err(format!("{COPIES} is the other places the key is kept, one line each: at most {MAX_COPIES}"));
158    }
159    places.into_iter().try_for_each(|line| copy_of(line).map(|_| ()))
160}
161
162/// Why an agent can't be given this entry's value, when the entry is a link: it has none. Nothing is asked of the
163/// person, because there is nothing to reveal.
164pub fn no_value(row: &VaultRow) -> Option<String> {
165    let fields = fields_of(row);
166    // A backed entry has a value for a use: it is read from its place then.
167    if !is_linked(&fields) || is_backed(&fields) {
168        return None;
169    }
170    let place = Link::of(&fields).map(|l| place_text(&l)).unwrap_or_default();
171    Some(format!("This entry holds no value: the key is kept at {place}. Ask the person, or use the access you already have there."))
172}
173
174/// Why `row` can't be given a value (a rotation, a capture, an import into it), when it is a link; `instead` says
175/// what to do.
176pub fn takes_no_value(row: &VaultRow, instead: &str) -> Option<String> {
177    if is_backed_row(row) {
178        return Some(format!("{} is backed by AWS Secrets Manager, which holds its value: change the secret there, not here ({instead} is for an entry that keeps its own value)", row.label));
179    }
180    is_linked_row(row).then(|| format!("{} is a linked entry, which holds no value: {instead}", row.label))
181}
182
183/// What an entry records about its key beside the place, as the person reads it before an agent changes it: who
184/// reads it, when it last changed, where else it is kept, one of them a line, so the card can show each on its own
185/// line and mark the ones a change touches. Empty when it records none of them.
186pub fn about(fields: &BTreeMap<String, String>) -> String {
187    let joined = |name: &str| lines(fields.get(name).map_or("", String::as_str)).join("; ");
188    let said = [("Read by", joined(READERS)), ("Last changed", joined(ROTATED)), ("Also kept at", joined(COPIES))];
189    said.into_iter().filter(|(_, text)| !text.is_empty()).map(|(what, text)| format!("{what}: {text}.")).collect::<Vec<_>>().join("\n")
190}
191
192/// The fields of a linked entry for the secret at `source`: the mark, the place, and what the asker says of it
193/// (`said`: readers, rotated, copies, an expiry date, the kind's own plain fields). The place is `source`, whatever
194/// `said` names.
195pub fn fields_for(source: &Source, said: &BTreeMap<String, String>) -> BTreeMap<String, String> {
196    fields_marked(ONLY, source, said)
197}
198
199/// [`fields_for`] for a backed entry: the same place, marked as one the Vault reads its value from at each use.
200pub fn fields_for_backed(source: &Source, said: &BTreeMap<String, String>) -> BTreeMap<String, String> {
201    fields_marked(BACKED, source, said)
202}
203
204fn fields_marked(mark: &str, source: &Source, said: &BTreeMap<String, String>) -> BTreeMap<String, String> {
205    let mut fields: BTreeMap<String, String> = said.iter().filter(|(k, _)| !source_link::is_field(k)).map(|(k, v)| (k.clone(), v.trim().to_string())).filter(|(_, v)| !v.is_empty()).collect();
206    let place = [
207        (LINK, Some(mark)),
208        (source_link::KIND, Some(AWS_SECRET)),
209        (source_link::LOCATION, Some(source.aws_secret_id.as_str())),
210        (source_link::KEY, source.key.as_deref()),
211        (source_link::REGION, source.region.as_deref()),
212        (source_link::PROFILE, source.profile.as_deref()),
213    ];
214    fields.extend(place.into_iter().filter_map(|(k, v)| Some((k.to_string(), v?.to_string()))));
215    fields
216}
217
218/// The record of a link a batch made, or did not make (`done`, `failed`): who, which place, why. Nothing was read.
219pub fn note(store: &Store, plan: &Plan, id: &str, label: &str, agent: &str, outcome: &str) {
220    let place = match &plan.target {
221        Target::Link { fields, .. } => Link::of(fields).map(|l| l.text()).unwrap_or_default(),
222        _ => plan.from_text(),
223    };
224    record_row(
225        store,
226        VaultActivityRow {
227            entry_id: id.into(),
228            entry_label: label.into(),
229            actor: agent.into(),
230            action: LINKED.into(),
231            target: place,
232            outcome: outcome.into(),
233            reason: plan.reason.clone(),
234            refs: history::refs_text(&plan.refs),
235            ..Default::default()
236        },
237    );
238}
239
240/// Makes the linked entry a batch's link item asked for. Nothing is read: the entry is the place and what is said of
241/// it. Its line carries the agent's reason and the batch's references.
242pub fn make(store: &Store, plan: &Plan, agent: &str) -> Result<Imported, String> {
243    let Target::Link { kind, label, fields, vault_id } = &plan.target else {
244        return Err(format!("{} is not a link", plan.label()));
245    };
246    let entry = NewEntry { kind: kind.to_string(), label: label.clone(), fields: fields.clone(), tags: Vec::new(), parts: Parts::default() };
247    let (id, label) = insert_unrecorded(store, entry, vault_id)?;
248    note(store, plan, &id, &label, agent, "done");
249    Ok(Imported { id, label, vault: plan.vault_name.clone() })
250}
251
252/// What a check found at one of a linked entry's other places.
253#[derive(Debug, Clone, PartialEq, Serialize)]
254pub struct CopyChecked {
255    /// The place, as the entry's `copies` line writes it.
256    pub place: String,
257    /// `present`, `changed since recorded`, `missing` or `could not read`.
258    pub outcome: &'static str,
259    #[serde(skip_serializing_if = "String::is_empty")]
260    pub why: String,
261    /// `not started`: the newest check of this place as the entry is now, when there is one.
262    #[serde(skip_serializing_if = "Option::is_none")]
263    pub stored: Option<VaultSourceCheck>,
264}
265
266/// What is known of one of the other places an entry names, for its "Also kept at" line. No value.
267#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
268#[ts(export, export_to = "../../../frontend/types/rpc/")]
269pub struct VaultCopyCheck {
270    /// The place, as the entry's `copies` line writes it.
271    pub place: String,
272    /// The newest check of that place as the entry is now; absent when it was never checked, or can't be.
273    #[serde(skip_serializing_if = "Option::is_none")]
274    #[ts(optional)]
275    pub checked: Option<VaultSourceCheck>,
276    /// Why no check can describe this place from here; empty when one can.
277    pub cannot: String,
278}
279
280/// Why a check can't describe `copy` from here, for an entry whose own place is of the kind `own`; `None` when it
281/// can: a CI secret is described wherever the entry's own place is, and a copy in AWS under the entry's own AWS
282/// place, whose region and login it is read with.
283fn cannot_describe(copy: &Link, own: &str) -> Option<&'static str> {
284    match (copy.kind.as_str(), own) {
285        (GITHUB_SECRET, _) | (AWS_SECRET, AWS_SECRET) => None,
286        (AWS_SECRET, _) => Some(NOT_UNDER_AWS),
287        _ => Some(NOT_FROM_HERE),
288    }
289}
290
291/// Each other place the entry names, with the newest check of it as the entry is now. A check leaves a line for a
292/// copy it can describe; for one it can't, that is said here in place of a check, so the pane shows it and not
293/// only the answer the asking agent got.
294pub fn copy_checks(store: &Store, row: &VaultRow) -> Vec<VaultCopyCheck> {
295    let fields = fields_of(row);
296    // Each line with the place it names: the pane finds a place's check by the line as the entry writes it.
297    let named: Vec<(&str, Link)> = lines(fields.get(COPIES).map_or("", String::as_str)).into_iter().filter_map(|line| Some((line, copy_of(line).ok()?))).collect();
298    if named.is_empty() {
299        return Vec::new();
300    }
301    let own = Link::of(&fields).map(|link| link.kind).unwrap_or_default();
302    let checks = copy_lines(store, row);
303    named
304        .iter()
305        .map(|(written, copy)| match cannot_describe(copy, &own) {
306            Some(why) => VaultCopyCheck { place: written.to_string(), checked: None, cannot: why.into() },
307            None => VaultCopyCheck { place: written.to_string(), checked: newest_of(&checks, copy), cannot: String::new() },
308        })
309        .collect()
310}
311
312/// The lines of the checks of the entry's other places as the entry is now, newest first. A check writes one line a
313/// copy, so this holds the last few checks of every copy.
314fn copy_lines(store: &Store, row: &VaultRow) -> Vec<VaultActivityRow> {
315    store.vault_activity_for_entry(&row.id, &[CHECKED_COPY], row.updated_at, (MAX_COPIES * 4) as i64).unwrap_or_default()
316}
317
318/// The newest check of `copy` among `checks` ([`copy_lines`]).
319fn newest_of(checks: &[VaultActivityRow], copy: &Link) -> Option<VaultSourceCheck> {
320    checks.iter().find(|line| line.target == copy.text()).map(|line| VaultSourceCheck { at: line.at, outcome: line.outcome.clone() })
321}
322
323/// What each place's description came to: the entry's own place, then its other places in order. No value is in a
324/// description. `None` is a CI secret no read was started for (`CheckPlan::no_github`).
325pub struct Found {
326    place: Option<Result<Described, String>>,
327    copies: Vec<(Link, Option<Result<Described, String>>)>,
328}
329
330/// The description of one place, or `None` for a CI secret when this asker's check may not start a read of one.
331async fn describe_place<R: Runner>(runner: &R, plan: &CheckPlan, link: &Link, via: Via<'_>) -> Option<Result<Described, String>> {
332    Some(match (link.kind.as_str(), link.aws()) {
333        (GITHUB_SECRET, _) if plan.no_github.is_some() => return None,
334        (GITHUB_SECRET, _) => github_secret::describe(runner, link).await,
335        (_, Some(source)) => aws_import::describe_secret(runner, &source, via).await,
336        (_, None) => Err(NOT_FROM_HERE.into()),
337    })
338}
339
340/// Reads the description of the entry's place and of each other place it names, with the asker's access. A copy in
341/// AWS is described as the entry's own place is, under the same region and login: when the entry's place is not in
342/// AWS there is no login to describe one under, and nothing is run for it. A CI secret is read with the GitHub CLI
343/// of this computer, wherever the entry's own place is.
344pub async fn describe<R: Runner>(runner: &R, plan: &CheckPlan, via: Via<'_>) -> Found {
345    // The places are described together: each run of a CLI has its own time limit, and a check of an entry with
346    // four copies must still answer inside the caller's wait.
347    let copies = plan.copies.iter().map(|copy| async move {
348        let described = match cannot_describe(copy, &plan.link.kind) {
349            Some(why) => Some(Err(why.into())),
350            None if copy.kind == AWS_SECRET => describe_place(runner, plan, &Link { region: plan.link.region.clone(), profile: plan.link.profile.clone(), ..copy.clone() }, via).await,
351            None => describe_place(runner, plan, copy, via).await,
352        };
353        (copy.clone(), described)
354    });
355    let (place, copies) = futures_util::future::join(describe_place(runner, plan, &plan.link, via), futures_util::future::join_all(copies)).await;
356    Found { place, copies }
357}
358
359/// What a place's description says against the date the entry records: gone, changed after that date, or there.
360fn outcome_of(described: &Result<Described, String>, recorded: Option<NaiveDate>) -> Outcome {
361    match (described, recorded) {
362        (Err(why), _) if why == NO_SUCH_SECRET || why == github_secret::NO_SUCH_SECRET => Outcome::Missing(why.clone()),
363        (Err(why), _) => Outcome::CouldNotRead(why.clone()),
364        (Ok(d), _) if d.deleted => Outcome::Missing("the secret is scheduled for deletion".into()),
365        (Ok(Described { changed: Some(changed), .. }), Some(recorded)) if *changed > recorded => Outcome::Changed(format!("the place last changed on {changed}, after the {recorded} recorded")),
366        (Ok(_), _) => Outcome::Present,
367    }
368}
369
370/// The answer for a place no read was started for: why, what to do, and the newest stored result when there is one.
371fn not_started(plan: &CheckPlan, stored: &Option<VaultSourceCheck>) -> Outcome {
372    let why = plan.no_github.as_deref().unwrap_or("no read was started");
373    let last = if stored.is_some() { "The newest stored result is in `stored`." } else { "It has not been checked yet." };
374    Outcome::NotStarted(format!("{why} {last}"))
375}
376
377/// The entry changed or went while its places were read: what was read says nothing of it. The copies that were
378/// read are still named, so the record of the reads is whole.
379fn overtaken(store: &Store, plan: &CheckPlan, found: &Found, why: String) -> Checked {
380    let outcome = Outcome::CouldNotRead(why);
381    let mut checked = if found.place.is_some() { source_link::conclude(store, plan, &outcome) } else { Checked::of(plan, &outcome) };
382    let read = found.copies.iter().filter(|(copy, described)| described.is_some() && cannot_describe(copy, &plan.link.kind).is_none());
383    checked.copies = read.map(|(copy, _)| CopyChecked { place: place_text(copy), outcome: outcome.word(), why: outcome.why().to_string(), stored: None }).collect();
384    checked
385}
386
387/// Records what the descriptions came to and answers it: a line for the entry's own place, and one for each other
388/// place that was asked. A place no read was started for gets no line, and answers with its newest stored result.
389/// Never fails: a place that can't be described is an outcome.
390pub fn finish(store: &Store, plan: &CheckPlan, found: Found) -> Checked {
391    let row = match source_link::as_planned(store, plan) {
392        Ok(row) => row,
393        Err(why) => return overtaken(store, plan, &found, why),
394    };
395    let recorded = fields_of(&row).get(ROTATED).and_then(|date| expiry::parse(date).ok());
396    let earlier = copy_lines(store, &row);
397    let mut copies = Vec::with_capacity(found.copies.len());
398    for (copy, described) in &found.copies {
399        let Some(described) = described else {
400            let stored = newest_of(&earlier, copy);
401            let outcome = not_started(plan, &stored);
402            copies.push(CopyChecked { place: place_text(copy), outcome: outcome.word(), why: outcome.why().to_string(), stored });
403            continue;
404        };
405        let outcome = outcome_of(described, recorded);
406        if cannot_describe(copy, &plan.link.kind).is_none() {
407            record_line(store, Line { entry_id: &plan.entry_id, label: &plan.label, actor: &plan.actor, action: CHECKED_COPY, target: &copy.text(), outcome: &outcome.line(), reason: &plan.reason });
408        }
409        copies.push(CopyChecked { place: place_text(copy), outcome: outcome.word(), why: outcome.why().to_string(), stored: None });
410    }
411    let mut checked = match &found.place {
412        Some(place) => source_link::conclude(store, plan, &outcome_of(place, recorded)),
413        None => {
414            let stored = source_link::last_check(store, &row, &plan.link);
415            Checked { stored: stored.clone(), ..Checked::of(plan, &not_started(plan, &stored)) }
416        }
417    };
418    if let Some(Ok(described)) = &found.place {
419        checked.last_changed = described.changed.map(|day| day.to_string());
420        checked.rotation = described.rotation;
421    }
422    checked.copies = copies;
423    checked
424}
425
426/// How a linked entry stands, by its newest check.
427#[derive(Debug, Clone, Copy, PartialEq)]
428pub enum Standing {
429    /// Checked within [`UNCHECKED_DAYS`], and the place was there and unchanged, or could not be described.
430    Checked,
431    /// The newest check found the place changed since the date recorded, or missing.
432    NeedsALook,
433    /// Never checked as it is now, or not for [`UNCHECKED_DAYS`].
434    Unchecked,
435}
436
437/// How a link stands by its newest check as it is now, and whether it has gone unchecked: that check is older than
438/// [`UNCHECKED_DAYS`], or there is none. A place found changed or missing that long ago is both.
439fn stands(checked: Option<&VaultSourceCheck>, now: i64) -> (Standing, bool) {
440    let unchecked = checked.is_none_or(|c| now - c.at > UNCHECKED_DAYS * DAY_MS);
441    let how = match checked {
442        Some(c) if c.outcome.starts_with(source_link::CHANGED) || c.outcome.starts_with(source_link::MISSING) => Standing::NeedsALook,
443        Some(_) if !unchecked => Standing::Checked,
444        _ => Standing::Unchecked,
445    };
446    (how, unchecked)
447}
448
449/// How `row` stands and whether it has gone unchecked ([`stands`]), when it is a linked entry.
450pub fn standing(store: &Store, row: &VaultRow) -> Option<(Standing, bool)> {
451    let fields = fields_of(row);
452    if !is_linked(&fields) {
453        return None;
454    }
455    let checked = Link::of(&fields).and_then(|link| source_link::last_check(store, row, &link));
456    Some(stands(checked.as_ref(), now_ms()))
457}
458
459#[cfg(test)]
460#[path = "linked_tests.rs"]
461mod tests;