Skip to main content

agentmux_srv_core/backend/vault/
capture.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Terminal` `run`'s `capture`: a value a command prints goes straight into the
5//! Vault (docs/specs/SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md §4.2).
6//!
7//! srv holds the command's output until it ends ([`crate::backend::shell_node`]),
8//! then [`Capture::finish`] applies the rules to its standard output, stores each
9//! match as a new entry or as a new value of an existing one (the old value kept 7
10//! days, §4.4), and returns a [`Scrubber`] for the values, so the output is
11//! published with `[vault:<id>]` where each was. If a rule matches nothing, srv
12//! can't tell which line held the secret: the output is withheld whole, and kept
13//! as a note the person can open with Reveal.
14
15use std::collections::{BTreeMap, HashMap};
16
17use agentmux_common::api_types::{CaptureFrom, CaptureInto, CaptureRule};
18use agentmux_common::time::now_ms;
19use serde_json::value::RawValue;
20use zeroize::Zeroizing;
21
22use super::scrub::{self, Scrubber, MIN_LINE};
23use super::{card, insert, kinds, new_id_besides, record_line, seal, validate, versions, Line, NewEntry, Parts};
24use crate::backend::storage::store::Store;
25use crate::backend::storage::vault::VaultRow;
26use crate::backend::storage::vault_versions::CaptureWrite;
27
28/// Most rules one command may have.
29pub const MOST: usize = 8;
30/// A shorter value is refused: the output couldn't be cleaned of it reliably.
31pub const MIN_LEN: usize = 8;
32/// A card's other parts (a security code, an expiry, a ZIP) are short by nature: they are taken at any length and then
33/// checked against what the scrubber can clean (`scrub::cleanable`), so none is stored that would still show in the output.
34/// The most output held for a capture; past it the capture fails and the
35/// output kept for the person is cut here.
36pub const MAX_HELD: usize = 1024 * 1024;
37/// The longest regex, JSON path or label a rule may give.
38const MAX_RULE: usize = 500;
39/// The action an entry's activity log names a capture by.
40pub const CAPTURED: &str = "captured";
41
42/// Where one rule's value goes.
43#[derive(Debug, Clone, PartialEq)]
44pub enum Target {
45    /// `fields`: plain fields it starts with (a browser capture's origin, as its
46    /// `service` or `site`).
47    New { kind: &'static str, label: String, part: &'static str, fields: BTreeMap<String, String>, vault_id: String },
48    /// An existing entry, as it was when the command was approved: a value is
49    /// never stored into an entry deleted and made again since.
50    Existing { id: String, created_at: i64, label: String, part: &'static str, kind: String },
51}
52
53/// Where a rule finds its value in standard output.
54#[derive(Debug, Clone)]
55pub enum Source {
56    All,
57    Json(Vec<Step>),
58    Regex(regex::Regex),
59    Line(usize),
60}
61
62#[derive(Debug, Clone, PartialEq)]
63pub enum Step {
64    Key(String),
65    Index(usize),
66}
67
68#[derive(Debug, Clone)]
69pub struct Rule {
70    pub into: Target,
71    pub from: Source,
72    /// A new card's other parts, from the same output (`CaptureFrom::Parts`): the part and where it is. `from` is
73    /// then the card's number.
74    pub also: Vec<(&'static str, Source)>,
75}
76
77/// A command's capture, checked before it runs.
78#[derive(Debug, Clone)]
79pub struct Capture {
80    pub rules: Vec<Rule>,
81    /// The agent that ran the command, as its verified identity names it.
82    pub agent: String,
83    /// The command line, for the activity log and the kept output's label.
84    pub cmd: String,
85    /// The agent's reason for the capture, for the activity log.
86    pub reason: String,
87}
88
89/// A capture as the command's runner holds it: the rules, the store they write
90/// to, and a call that tells every Vault pane its entries changed.
91pub struct Job {
92    pub capture: Capture,
93    pub store: std::sync::Arc<Store>,
94    pub changed: Box<dyn Fn() + Send + Sync>,
95    /// The agent's pace this capture holds until its command has run: a job dropped before then (the person said no to
96    /// another card of the same call, or the call was cancelled) gives it back.
97    pub reservation: super::pace::Reservation,
98}
99
100/// What a capture came to, once the command ended.
101pub enum Outcome {
102    /// Every rule matched: the entries, in rule order, the values to take out of
103    /// the output, and the lines of a multi-line value too short for the scrubber
104    /// to find on their own (see [`clean_held`]).
105    Stored { ids: Vec<String>, scrubber: Scrubber, short: Vec<Zeroizing<String>> },
106    /// The output is withheld: why, and the note the person can open it in.
107    Withheld { why: String, kept_as: Option<String> },
108}
109
110fn clip(s: &str, n: usize) -> String {
111    let mut out: String = s.chars().take(n).collect();
112    if out.len() < s.len() {
113        out.push('…');
114    }
115    out
116}
117
118/// One line of held output: its stream, its text and when it was printed.
119pub type HeldLine = (&'static str, String, u64);
120
121/// The held output cleaned of every value, as the lines to publish. It is cleaned
122/// as one text, so a multi-line value is found across the lines it was printed
123/// on; lines it took up become one. If a line of such a value that is too short
124/// for the scrubber to find alone is still there (printed apart from the rest),
125/// the output can't be published: the reason is returned.
126pub fn clean_held(held: &[HeldLine], scrubber: &Scrubber, short: &[Zeroizing<String>]) -> Result<Vec<HeldLine>, String> {
127    let joined = Zeroizing::new(held.iter().map(|l| l.1.as_str()).collect::<Vec<_>>().join("\n"));
128    let clean = scrubber.scrub(&joined);
129    let lines: Vec<&str> = clean.split('\n').collect();
130    if lines.iter().any(|l| short.iter().any(|f| l.trim() == f.as_str())) {
131        return Err(format!("a line of a captured value is shorter than {MIN_LINE} characters and was printed apart from the rest, so it can't be cleaned out"));
132    }
133    if lines.len() == held.len() {
134        return Ok(held.iter().zip(lines).map(|(h, l)| (h.0, l.to_string(), h.2)).collect());
135    }
136    // A value over several lines became one mark: which stream each line came from
137    // no longer lines up, and all of it is published as standard output.
138    let ts = held.last().map(|h| h.2).unwrap_or(0);
139    Ok(lines.into_iter().map(|l| ("stdout", l.to_string(), ts)).collect())
140}
141
142/// `$.a.b[0]['c d']` as steps. `$` alone is the whole document.
143pub fn json_path(path: &str) -> Result<Vec<Step>, String> {
144    let bad = |why: &str| format!("the JSON path {:?} {why}; write it like $.AccessKey.SecretAccessKey or $.items[0].token", clip(path, 60));
145    let rest = path.trim().strip_prefix('$').ok_or_else(|| bad("doesn't start with $"))?;
146    let mut steps = Vec::new();
147    let mut chars = rest.chars().peekable();
148    while let Some(c) = chars.next() {
149        match c {
150            '.' => {
151                let mut key = String::new();
152                while let Some(&n) = chars.peek() {
153                    if n == '.' || n == '[' {
154                        break;
155                    }
156                    key.push(n);
157                    chars.next();
158                }
159                if key.is_empty() {
160                    return Err(bad("has an empty name"));
161                }
162                steps.push(Step::Key(key));
163            }
164            '[' => {
165                let quote = chars.peek().copied().filter(|q| *q == '\'' || *q == '"');
166                let mut inner = String::new();
167                if let Some(q) = quote {
168                    chars.next();
169                    loop {
170                        match chars.next() {
171                            Some(c) if c == q && chars.peek() == Some(&']') => break,
172                            Some(c) => inner.push(c),
173                            None => return Err(bad("has an unclosed quote")),
174                        }
175                    }
176                    chars.next();
177                    steps.push(Step::Key(inner));
178                } else {
179                    loop {
180                        match chars.next() {
181                            Some(']') => break,
182                            Some(c) => inner.push(c),
183                            None => return Err(bad("has an unclosed [")),
184                        }
185                    }
186                    steps.push(Step::Index(inner.trim().parse().map_err(|_| bad("has an index that isn't a number"))?));
187                }
188            }
189            _ => return Err(bad("has a step that isn't .name or [n]")),
190        }
191    }
192    Ok(steps)
193}
194
195fn rule_from(from: &CaptureFrom) -> Result<Source, String> {
196    match from {
197        CaptureFrom::Stdout(s) if s == "all" => Ok(Source::All),
198        CaptureFrom::Stdout(s) => Err(format!("\"stdout\" takes \"all\", not {:?}", clip(s, 40))),
199        CaptureFrom::Json(p) if p.len() > MAX_RULE => Err(format!("a JSON path is at most {MAX_RULE} characters")),
200        CaptureFrom::Json(p) => Ok(Source::Json(json_path(p)?)),
201        CaptureFrom::Regex(r) if r.len() > MAX_RULE => Err(format!("a regex is at most {MAX_RULE} characters")),
202        CaptureFrom::Regex(r) => {
203            let re = regex::RegexBuilder::new(r).size_limit(1 << 20).build().map_err(|e| format!("the regex doesn't compile: {e}"))?;
204            if re.captures_len() != 2 {
205                return Err(format!("the regex needs exactly one capture group, the value; it has {}", re.captures_len() - 1));
206            }
207            Ok(Source::Regex(re))
208        }
209        CaptureFrom::Line(0) => Err("lines are counted from 1".into()),
210        CaptureFrom::Line(n) => Ok(Source::Line(*n as usize)),
211        CaptureFrom::Parts(_) => Err("\"parts\" is a whole rule's, not one part's".into()),
212    }
213}
214
215/// The keys a `parts` capture takes and the card part each fills (`exp` is the older single text, read into the month
216/// and year when the card is settled).
217const CARD_KEYS: [(&str, &str); 7] = [("number", "number"), ("exp", "expiry"), ("exp_month", "exp_month"), ("exp_year", "exp_year"), ("cvc", "cvc"), ("name", "name"), ("zip", "zip")];
218
219/// A card's parts read from a page, by the keys a `parts` capture takes: the number as the main value and the rest
220/// beside it, ready for [`Capture::store`]. The page's parts are not cleaned out of an output, so they have no
221/// minimum length.
222pub fn card_found(values: BTreeMap<String, Zeroizing<String>>) -> Result<Found, String> {
223    let mut number = None;
224    let mut also = Vec::new();
225    for (key, value) in values {
226        let Some((_, part)) = CARD_KEYS.iter().find(|(k, _)| *k == key) else {
227            return Err(format!("a card has no {key:?}"));
228        };
229        if value.trim().is_empty() {
230            return Err(format!("the card's {key} is empty"));
231        }
232        let found = Found { value, printed: None, also: Vec::new() };
233        if *part == "number" {
234            number = Some(found);
235        } else {
236            also.push((*part, found));
237        }
238    }
239    let mut main = number.ok_or("a card needs its number")?;
240    main.also = also;
241    Ok(main)
242}
243
244/// A `parts` capture's sources: the card's number, and its other parts. Only a new card is made this way.
245fn card_parts(map: &BTreeMap<String, CaptureFrom>, into: &CaptureInto) -> Result<(Source, Vec<(&'static str, Source)>), String> {
246    if into.id.is_some() || into.kind.as_deref().map(str::trim) != Some("card") {
247        return Err("\"parts\" makes a new card: name it in \"as\" by kind \"card\" and a label, not by an entry's id".into());
248    }
249    if into.part.as_deref().is_some_and(|p| !p.trim().is_empty()) {
250        return Err("\"parts\" fills each part it names: leave part out".into());
251    }
252    if map.contains_key("exp") && (map.contains_key("exp_month") || map.contains_key("exp_year")) {
253        return Err("give the expiry as \"exp\", or as \"exp_month\" and \"exp_year\", not both".into());
254    }
255    let (mut number, mut also) = (None, Vec::new());
256    for (key, from) in map {
257        let Some((_, part)) = CARD_KEYS.iter().find(|(k, _)| k == key) else {
258            let names: Vec<&str> = CARD_KEYS.iter().map(|(k, _)| *k).collect();
259            return Err(format!("a card has no {key:?} to capture; its parts are {}", names.join(", ")));
260        };
261        let source = rule_from(from).map_err(|e| format!("{key}: {e}"))?;
262        if *part == "number" {
263            number = Some(source);
264        } else {
265            also.push((*part, source));
266        }
267    }
268    Ok((number.ok_or("\"parts\" needs the card's \"number\"")?, also))
269}
270
271/// Checks a command's capture before it runs: every rule readable, every entry
272/// it names there, every new one makeable.
273pub fn plan(store: &Store, rules: &[CaptureRule], agent: &str, cmd: &str) -> Result<Capture, String> {
274    if rules.is_empty() {
275        return Err("capture needs at least one rule".into());
276    }
277    if rules.len() > MOST {
278        return Err(format!("a command takes at most {MOST} capture rules"));
279    }
280    let mut out = Vec::with_capacity(rules.len());
281    for (n, r) in rules.iter().enumerate() {
282        let which = |e: String| if rules.len() > 1 { format!("capture rule {}: {e}", n + 1) } else { e };
283        let (from, also) = match &r.from {
284            CaptureFrom::Parts(map) => card_parts(map, &r.into).map_err(which)?,
285            one => (rule_from(one).map_err(which)?, Vec::new()),
286        };
287        let into = match (&r.into.id, &r.into.kind) {
288            (Some(_), Some(_)) => return Err(which("\"as\" names an entry by id, or a new one by kind and label, not both".into())),
289            (Some(id), None) => {
290                let row = store.vault_get(id.trim()).map_err(|e| e.to_string())?.ok_or_else(|| which(format!("there is no entry {id:?}")))?;
291                if !super::vaults::entry_row_usable(store, &row.vault_id, Some(agent))? {
292                    return Err(which(format!("there is no entry {id:?}")));
293                }
294                if let Some(refusal) = super::linked::takes_no_value(&row, "capture into a new entry") {
295                    return Err(which(refusal));
296                }
297                let kind = kinds::kind(&row.kind).ok_or_else(|| which(format!("entry {id} has an unknown kind")))?;
298                let part = part_of(kind, r.into.part.as_deref()).map_err(which)?;
299                if r.into.label.as_deref().is_some_and(|l| l.trim() != row.label) {
300                    return Err(which(format!("{id} is called {:?}: leave label out to keep it", row.label)));
301                }
302                Target::Existing { id: row.id, created_at: row.created_at, label: row.label, part, kind: row.kind }
303            }
304            (None, Some(kind)) => {
305                let k = kinds::kind(kind.trim()).ok_or_else(|| which(format!("unknown kind {kind:?}")))?;
306                let label = r.into.label.as_deref().map(str::trim).unwrap_or("");
307                if label.is_empty() {
308                    return Err(which("a new entry needs a label".into()));
309                }
310                if label.chars().count() > MAX_RULE {
311                    return Err(which(format!("a label is at most {MAX_RULE} characters")));
312                }
313                let part = part_of(k, r.into.part.as_deref()).map_err(which)?;
314                if part != k.parts[0] {
315                    return Err(which(format!("a new {} entry is made from its {}; capture the {part} into it once it exists", k.name, k.parts[0])));
316                }
317                // Settled now, before the command runs: a command that issues a key must not run when the value cannot be kept.
318                let vault_id = super::vaults::default_for(store, Some(agent)).map_err(which)?;
319                Target::New { kind: k.name, label: label.to_string(), part, fields: BTreeMap::new(), vault_id }
320            }
321            (None, None) => return Err(which("\"as\" needs an entry's id, or a kind and label for a new one".into())),
322        };
323        let same = |t: &Target| match (t, &into) {
324            (Target::New { kind: a, label: b, .. }, Target::New { kind: c, label: d, .. }) => a == c && b.eq_ignore_ascii_case(d),
325            (Target::Existing { id: a, .. }, Target::Existing { id: b, .. }) => a == b,
326            _ => false,
327        };
328        if out.iter().any(|r: &Rule| same(&r.into)) {
329            return Err(which("two rules write the same entry; give each its own".into()));
330        }
331        out.push(Rule { into, from, also });
332    }
333    Ok(Capture { rules: out, agent: agent.to_string(), cmd: cmd.to_string(), reason: String::new() })
334}
335
336fn part_of(kind: &kinds::Kind, part: Option<&str>) -> Result<&'static str, String> {
337    match part.map(str::trim).filter(|p| !p.is_empty()) {
338        None => Ok(kind.parts[0]),
339        Some(p) => kind.parts.iter().copied().find(|k| *k == p).ok_or_else(|| format!("a {} entry has no part {p:?}; its parts are {}", kind.name, kind.parts.join(", "))),
340    }
341}
342
343/// The JSON text at `steps`, exactly as the output printed it.
344fn walk<'a>(mut raw: &'a RawValue, steps: &[Step]) -> Option<&'a RawValue> {
345    for s in steps {
346        raw = match s {
347            Step::Key(k) => serde_json::from_str::<HashMap<String, &'a RawValue>>(raw.get()).ok()?.remove(k.as_str())?,
348            Step::Index(i) => serde_json::from_str::<Vec<&'a RawValue>>(raw.get()).ok()?.into_iter().nth(*i)?,
349        };
350    }
351    Some(raw)
352}
353
354/// A rule's value, and the text the output printed it as when that differs (a
355/// JSON string's escaped form), which is cleaned out of the output too.
356pub struct Found {
357    pub value: Zeroizing<String>,
358    pub printed: Option<Zeroizing<String>>,
359    /// A card's other parts, when the rule was a `parts` one.
360    pub also: Vec<(&'static str, Found)>,
361}
362
363/// One rule's value in `stdout`, or why there is none. Never says what it found.
364pub fn extract(from: &Source, stdout: &str) -> Result<Found, String> {
365    extract_min(from, stdout, MIN_LEN)
366}
367
368/// [`extract`], taking a value of at least `min` characters.
369pub fn extract_min(from: &Source, stdout: &str, min: usize) -> Result<Found, String> {
370    let mut printed = None;
371    let value: Zeroizing<String> = match from {
372        Source::All => Zeroizing::new(stdout.trim().to_string()),
373        Source::Line(n) => Zeroizing::new(stdout.lines().nth(n - 1).ok_or_else(|| format!("the output has fewer than {n} lines"))?.trim().to_string()),
374        Source::Regex(re) => {
375            let caps = re.captures(stdout).ok_or("the regex matched nothing")?;
376            Zeroizing::new(caps.get(1).ok_or("the regex's group matched nothing")?.as_str().trim().to_string())
377        }
378        Source::Json(steps) => {
379            let top: &RawValue = serde_json::from_str(stdout.trim()).map_err(|_| "the output isn't JSON".to_string())?;
380            let raw = walk(top, steps).ok_or("the JSON path matched nothing")?.get();
381            match raw.as_bytes().first() {
382                Some(b'"') => {
383                    let decoded = Zeroizing::new(serde_json::from_str::<String>(raw).map_err(|_| "the output isn't JSON".to_string())?);
384                    let inner = &raw[1..raw.len() - 1];
385                    if inner != decoded.as_str() {
386                        printed = Some(Zeroizing::new(inner.to_string()));
387                    }
388                    decoded
389                }
390                Some(b'-' | b'0'..=b'9') => Zeroizing::new(raw.to_string()),
391                Some(b'n') => return Err("the JSON path matched nothing".into()),
392                _ => return Err("the JSON path matched an object, a list or true/false, not a value".into()),
393            }
394        }
395    };
396    if value.is_empty() {
397        return Err("the value it matched is empty".into());
398    }
399    if value.chars().count() < min {
400        return Err(format!("the value it matched is shorter than {min} characters, too short to clean out of the output"));
401    }
402    Ok(Found { value, printed, also: Vec::new() })
403}
404
405impl Rule {
406    /// Whether the rule's main value is one of a card's short parts (a security code, an expiry or a ZIP captured into a
407    /// card that exists), not the number or another kind's value.
408    fn short_part(&self) -> Option<&'static str> {
409        match &self.into {
410            Target::Existing { kind, part, .. } if kind == card::KIND && *part != "number" => Some(part),
411            _ => None,
412        }
413    }
414}
415
416/// A card's part the output could not be cleaned of is refused, naming the part and never the value.
417fn cleanable(part: &str, f: &Found) -> Result<(), String> {
418    if scrub::cleanable(&f.value) {
419        return Ok(());
420    }
421    let hint = if part.starts_with("exp_") { ": give the expiry as one text, exp (like 03/30)" } else { "" };
422    Err(format!("the card's {part} is too short to clean out of the output (under {} characters, and not a 3-digit code){hint}", scrub::MIN_LEN))
423}
424
425/// A rule's values in `stdout`: its main one, and a card's other parts, which may be short.
426fn extract_rule(r: &Rule, stdout: &str) -> Result<Found, String> {
427    let short = r.short_part();
428    let mut found = extract_min(&r.from, stdout, if short.is_some() { 1 } else { MIN_LEN })?;
429    if let Some(part) = short {
430        cleanable(part, &found)?;
431    }
432    for (part, from) in &r.also {
433        let f = extract_min(from, stdout, 1).map_err(|e| format!("the card's {part}: {e}"))?;
434        cleanable(part, &f)?;
435        found.also.push((part, f));
436    }
437    Ok(found)
438}
439
440impl Capture {
441    /// Whether any rule replaces the value of an entry that exists: the person is
442    /// asked first.
443    pub fn replaces(&self) -> impl Iterator<Item = &Target> {
444        self.rules.iter().map(|r| &r.into).filter(|i| matches!(i, Target::Existing { .. }))
445    }
446
447    /// What this capture counts as for an agent's pace, a rule each.
448    pub fn acts(&self) -> Vec<super::pace::Act> {
449        self.rules
450            .iter()
451            .map(|r| match &r.into {
452                Target::Existing { id, .. } => super::pace::Act::Replace(id.clone()),
453                Target::New { .. } => super::pace::Act::New,
454            })
455            .collect()
456    }
457
458    /// Applies the rules to `stdout` and stores what they match. `output` is the
459    /// whole output as it would be published, kept for the person if the capture
460    /// fails; `cut` says it was longer than [`MAX_HELD`].
461    pub fn finish(&self, store: &Store, stdout: &str, output: &str, cut: bool, exit_code: i32) -> Outcome {
462        let why = if cut {
463            Err(format!("the output is over {} MB, more than a capture holds", MAX_HELD / (1024 * 1024)))
464        } else if exit_code != 0 {
465            Err(format!("the command failed (exit code {exit_code}), so nothing it printed is taken as the value"))
466        } else {
467            self.rules
468                .iter()
469                .enumerate()
470                .map(|(n, r)| extract_rule(r, stdout).map_err(|e| if self.rules.len() > 1 { format!("capture rule {}: {e}", n + 1) } else { e }))
471                .collect::<Result<Vec<_>, _>>()
472        };
473        let found = match why {
474            Ok(v) => v,
475            Err(why) => return self.withhold(store, why, output),
476        };
477        match self.store(store, &found) {
478            Ok(ids) => {
479                let mut known: Vec<(String, String)> = Vec::new();
480                let mut short = Vec::new();
481                for (id, f) in ids.iter().zip(found.iter()) {
482                    known.push((id.clone(), f.value.to_string()));
483                    if let Some(p) = &f.printed {
484                        known.push((id.clone(), p.to_string()));
485                    }
486                    for (_, x) in &f.also {
487                        known.push((id.clone(), x.value.to_string()));
488                        if let Some(p) = &x.printed {
489                            known.push((id.clone(), p.to_string()));
490                        }
491                    }
492                    if f.value.contains('\n') {
493                        short.extend(f.value.lines().map(str::trim).filter(|l| !l.is_empty() && l.len() < MIN_LINE).map(|l| Zeroizing::new(l.to_string())));
494                    }
495                }
496                Outcome::Stored { scrubber: Scrubber::new(&known), ids, short }
497            }
498            Err(why) => self.withhold(store, format!("the value couldn't be stored: {why}"), output),
499        }
500    }
501
502    /// Stores every rule's value in one transaction: all of them, or none if an
503    /// entry one replaces changed, or was deleted or made again, while the command
504    /// ran. Each old main value is kept as a version in the same transaction.
505    pub fn store(&self, store: &Store, found: &[Found]) -> Result<Vec<String>, String> {
506        let key = seal::key(store.vault_count().map_err(|e| e.to_string())? == 0)?;
507        let now = now_ms();
508        let mut writes = Vec::with_capacity(found.len());
509        let mut made: Vec<(String, String)> = Vec::with_capacity(found.len());
510        for (rule, f) in self.rules.iter().zip(found) {
511            match &rule.into {
512                Target::New { kind, label, part, fields, vault_id } => {
513                    let k = kinds::kind(kind).ok_or_else(|| format!("unknown kind {kind:?}"))?;
514                    let mut parts = Parts::default();
515                    parts.0.insert(part.to_string(), f.value.to_string());
516                    for (other, x) in &f.also {
517                        parts.0.insert(other.to_string(), x.value.to_string());
518                    }
519                    let tags = Vec::<String>::new();
520                    let mut fields: BTreeMap<String, String> = fields.iter().filter(|(_, v)| !v.trim().is_empty()).map(|(k, v)| (k.clone(), v.trim().to_string())).collect();
521                    // A card's number, expiry, brand and reminder date agree, as they do for a save by the person.
522                    card::settle(k.name, &mut fields, &mut parts)?;
523                    validate(k, label, &fields, &tags, &parts)?;
524                    let taken: Vec<String> = made.iter().map(|(id, _)| id.clone()).collect();
525                    let id = new_id_besides(store, kind, label, &taken)?;
526                    writes.push(CaptureWrite::Insert(VaultRow {
527                        id: id.clone(),
528                        kind: kind.to_string(),
529                        label: label.clone(),
530                        fields: serde_json::to_string(&fields).map_err(|e| e.to_string())?,
531                        tags: serde_json::to_string(&tags).map_err(|e| e.to_string())?,
532                        sealed: seal::seal(&key, &id, &parts)?,
533                        created_at: now,
534                        updated_at: now,
535                        last_used_at: 0,
536                        vault_id: vault_id.clone(),
537                    }));
538                    made.push((id, label.clone()));
539                }
540                Target::Existing { id, created_at, label, part, .. } => {
541                    let gone = || format!("{label} was deleted while the command ran");
542                    let row = store.vault_get(id).map_err(|e| e.to_string())?.filter(|r| r.created_at == *created_at).ok_or_else(gone)?;
543                    let mut parts = seal::open(&key, &row.id, &row.sealed)?;
544                    if let Some(mut old) = parts.0.insert(part.to_string(), f.value.to_string()) {
545                        zeroize::Zeroize::zeroize(&mut old);
546                    }
547                    // A captured expiry replaces the month and year, or the next save would put them back.
548                    if row.kind == card::KIND && *part == "expiry" {
549                        for stale in ["exp_month", "exp_year"] {
550                            if let Some(mut old) = parts.0.remove(stale) {
551                                zeroize::Zeroize::zeroize(&mut old);
552                            }
553                        }
554                    }
555                    // Only a card's plain fields follow its parts; any other kind's are left exactly as they are.
556                    let is_card = row.kind == card::KIND;
557                    let mut fields: BTreeMap<String, String> = if is_card { serde_json::from_str(&row.fields).map_err(|_| format!("{label}'s details can't be read, so nothing was changed"))? } else { BTreeMap::new() };
558                    card::settle(&row.kind, &mut fields, &mut parts)?;
559                    let fields_text = if is_card { serde_json::to_string(&fields).map_err(|e| e.to_string())? } else { row.fields.clone() };
560                    // The whole entry as it was, whichever part this replaces: the person was
561                    // told the old value is kept for 7 days.
562                    let kept = Some(versions::of(&row, &self.agent, CAPTURED));
563                    let (was, was_fields) = (row.sealed.clone(), row.fields.clone());
564                    let changed = VaultRow { sealed: seal::seal(&key, &row.id, &parts)?, fields: fields_text, updated_at: now, ..row };
565                    writes.push(CaptureWrite::Replace { row: changed, was, was_fields, kept });
566                    made.push((id.clone(), label.clone()));
567                }
568            }
569        }
570        versions::prune(store);
571        if !store.vault_capture_commit(&writes).map_err(|e| e.to_string())? {
572            return Err("an entry it replaces changed while the command ran, so nothing was stored".into());
573        }
574        let target = clip(&self.cmd, 160);
575        for (id, label) in &made {
576            record_line(store, Line { entry_id: id, label, actor: &self.agent, action: CAPTURED, target: &target, outcome: "done", reason: &self.reason });
577            // Nobody was asked, so the value is the agent's until the person has seen it (`agent_set`).
578            super::agent_set::mark(store, id, &self.agent);
579        }
580        for (rule, (id, _)) in self.rules.iter().zip(&made) {
581            // A login given a site: the place is the agent's choice or the page's, and the person has not seen it (R9).
582            if matches!(&rule.into, Target::New { kind, fields, .. } if *kind == "login" && fields.contains_key(super::signins::SITE)) {
583                super::agent_set::mark_site(store, id, &self.agent);
584            }
585        }
586        Ok(made.into_iter().map(|(id, _)| id).collect())
587    }
588
589    /// Keeps the withheld output as a note only the person opens (with Reveal), and
590    /// logs the failed capture against each entry that exists.
591    fn withhold(&self, store: &Store, why: String, output: &str) -> Outcome {
592        // Nothing was stored: a capture that failed does not use up the agent's pace.
593        super::pace::refund(&self.agent, &self.acts());
594        let mut cut = output.len().min(MAX_HELD);
595        while !output.is_char_boundary(cut) {
596            cut -= 1;
597        }
598        let kept = output[..cut].trim_end();
599        let kept_as = if kept.is_empty() {
600            None
601        } else {
602            let mut parts = Parts::default();
603            parts.0.insert("text".into(), kept.to_string());
604            let label = format!("Output withheld from {}: {}", self.agent, clip(&self.cmd, 60));
605            let entry = NewEntry { kind: "note".into(), label, fields: BTreeMap::new(), tags: vec!["capture".into()], parts };
606            match insert(store, entry, &self.agent, "output withheld", &clip(&why, 160)) {
607                Ok(id) => Some(id),
608                Err(e) => {
609                    tracing::warn!(error = %e, "vault: couldn't keep a failed capture's output");
610                    None
611                }
612            }
613        };
614        for rule in &self.rules {
615            if let Target::Existing { id, label, .. } = &rule.into {
616                record_line(store, Line { entry_id: id, label, actor: &self.agent, action: CAPTURED, target: &clip(&why, 160), outcome: "failed", reason: &self.reason });
617            }
618        }
619        Outcome::Withheld { why, kept_as }
620    }
621}
622
623#[cfg(test)]
624#[path = "capture_tests.rs"]
625mod tests;