Skip to main content

capsule_library/lifecycle/
metadata.rs

1//! User + AI metadata edits — the CRDT writes that ride a signed `metadata-update` record.
2//! The only `lifecycle` file that reaches [`capsule_core::ml`], in both directions: it reads the model
3//! registry to filter stale suggestions, and it is where [`Workspace`] implements the
4//! [`AiTagSink`] seam the inference orchestrator writes through. The orchestrator used to import
5//! `Workspace` directly, which — with this file importing `ml` — made the two modules mutually
6//! recursive; the trait inverts that edge without moving any behaviour.
7
8use capsule_core::crypto::provenance::Action;
9use capsule_core::domain::GpsDatum;
10use capsule_core::metadata::crdt::AddId;
11use capsule_core::ml::{AiTagSink, AssetSource, ModelId, Registry};
12use capsule_core::sidecar::{AiTag, Gps, GpsSource, normalize_label};
13use jiff::Timestamp;
14use uuid::Uuid;
15
16use super::album::remove_label;
17use super::{LifecycleError, Result, Workspace, now_rfc3339};
18use crate::db::DatabaseDriver;
19
20impl Workspace {
21    /// Add a user tag (OR-set) and emit a `metadata-update` provenance record.
22    ///
23    /// The tag is an asset label and follows the one label rule
24    /// ([`normalize_label`]: NFC, trimmed, 1–256 bytes); a tag the rule refuses is
25    /// [`LifecycleError::InvalidLabel`] and nothing is appended. Tags already stored are read
26    /// as they are: only new writes are normalized.
27    #[tracing::instrument(skip(self, tag), fields(asset_id = %asset_id))]
28    pub fn tag_add(&mut self, asset_id: &Uuid, tag: &str) -> Result<()> {
29        let tag = normalize_label(tag)?;
30        self.append_lifecycle(asset_id, Action::MetadataUpdate, None, move |s, add_id| {
31            s.tags_user.add(tag, add_id);
32        })
33    }
34
35    /// Remove a user tag: every add of it this device has observed (OR-set observed-remove),
36    /// as one `metadata-update` provenance record. Returns how many adds were removed; 0 means
37    /// the asset does not carry the tag, and nothing is appended.
38    ///
39    /// The tag is matched both exactly as given and after the label rule ([`normalize_label`]),
40    /// so it names the label [`tag_add`](Self::tag_add) stored and also a tag stored before the
41    /// rule existed, spelled as it is listed. A tag the rule refuses, and that the asset does
42    /// not carry verbatim, is [`LifecycleError::InvalidLabel`]. An add this device has not yet
43    /// seen (a concurrent add on another device) survives the merge, as an OR-set's add-wins
44    /// rule says.
45    #[tracing::instrument(skip(self, tag), fields(asset_id = %asset_id))]
46    pub fn tag_remove(&mut self, asset_id: &Uuid, tag: &str) -> Result<usize> {
47        let normalized = normalize_label(tag);
48        let raw = tag.to_owned();
49        let carried = self
50            .assets
51            .get(asset_id)
52            .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?
53            .sidecar
54            .tags_user
55            .entries()
56            .into_iter()
57            .filter(|(_, el)| *el == raw || normalized.as_ref().is_ok_and(|n| el == n))
58            .count();
59        if carried == 0 {
60            normalized?;
61            tracing::debug!(asset_id = %asset_id, "tag remove: the asset does not carry it");
62            return Ok(0);
63        }
64        let normalized = normalized.ok().filter(|n| *n != raw);
65        self.append_lifecycle(asset_id, Action::MetadataUpdate, None, move |s, _add_id| {
66            remove_label(&mut s.tags_user, &raw);
67            if let Some(normalized) = normalized {
68                remove_label(&mut s.tags_user, &normalized);
69            }
70        })?;
71        tracing::info!(asset_id = %asset_id, removed = carried, "user tag removed as a signed metadata-update");
72        Ok(carried)
73    }
74
75    /// Set the caption (LWW register) and emit a `metadata-update` provenance record.
76    ///
77    /// An empty `caption` clears it: the register is stamped with `""`, and the index projects
78    /// that as no caption. The index row's `caption` column is refreshed by the same
79    /// `append_lifecycle` write, so the caption reads back from the catalog without a rebuild.
80    #[tracing::instrument(skip(self, caption), fields(asset_id = %asset_id, len = caption.len()))]
81    pub fn set_caption(&mut self, asset_id: &Uuid, caption: &str) -> Result<()> {
82        let caption = caption.to_string();
83        let device = self.account.device.device_id;
84        let ts = now_rfc3339();
85        self.append_lifecycle(asset_id, Action::MetadataUpdate, None, move |s, _add_id| {
86            s.caption.set(caption, ts, device);
87        })
88    }
89
90    /// Record the user's capture time for the asset, as a new signed revision: one
91    /// `metadata-update` record, with the sidecar re-signed and its sealed blob re-sealed under a
92    /// fresh nonce, exactly as any other metadata edit lands.
93    ///
94    /// The correction is written to the `capture_timestamp_user` LWW register, stamped with this
95    /// device id and now, so concurrent corrections from two devices converge under the
96    /// `(ts, device_id)` rule. The as-imported `capture_timestamp` is **never overwritten**: it
97    /// stays what the original said, and the effective instant
98    /// ([`SidecarV1::effective_capture_timestamp`](capsule_core::sidecar::SidecarV1::effective_capture_timestamp))
99    /// is the correction.
100    ///
101    /// The **media bundle is not relocated.** The `media/{YYYY}/{YYYY-MM}` directory is the
102    /// shard fixed at import (`AssetState::capture_utc`) from the as-imported value, and the
103    /// design treats bucket-vs-timestamp drift after a correction as expected rather than as a
104    /// fault (Maintenance — Structural Validation). The index row follows the effective instant
105    /// (`asset_row_from_state`), so the timeline shows the correction immediately rather than
106    /// after a rebuild.
107    ///
108    /// Takes a [`Timestamp`] rather than raw seconds so an out-of-range instant is
109    /// unrepresentable at the call site instead of being clamped to the epoch here.
110    #[tracing::instrument(skip(self), fields(asset_id = %asset_id, capture = %capture))]
111    pub fn set_capture_timestamp(&mut self, asset_id: &Uuid, capture: Timestamp) -> Result<()> {
112        let recorded = self
113            .assets
114            .get(asset_id)
115            .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?
116            .sidecar
117            .effective_capture_timestamp()
118            .to_owned();
119        let corrected = capture.to_string();
120        let device = self.account.device.device_id;
121        let ts = now_rfc3339();
122        self.append_lifecycle(asset_id, Action::MetadataUpdate, None, move |s, _add_id| {
123            s.capture_timestamp_user.set(corrected, ts, device);
124        })?;
125        let head = self.assets[asset_id].chain.head();
126        tracing::info!(
127            asset_id = %asset_id,
128            recorded = %recorded,
129            corrected = %capture,
130            chain_head = ?head,
131            "capture timestamp corrected as a signed metadata-update"
132        );
133        Ok(())
134    }
135
136    /// Re-record the asset's **as-imported** capture time, leaving any user correction alone.
137    ///
138    /// Reserved for re-deriving what the import should have recorded from the original's own
139    /// metadata — the `capsule repair capture-time` pass, for libraries imported while the EXIF
140    /// parser could not read `DateTimeOriginal`. It is not a user edit: a user's correction goes
141    /// through [`set_capture_timestamp`](Self::set_capture_timestamp), which this never
142    /// displaces. One signed `metadata-update`; the bundle is not relocated.
143    #[tracing::instrument(skip(self), fields(asset_id = %asset_id, capture = %capture))]
144    pub fn correct_imported_capture_timestamp(
145        &mut self,
146        asset_id: &Uuid,
147        capture: Timestamp,
148    ) -> Result<()> {
149        let recorded = self
150            .assets
151            .get(asset_id)
152            .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?
153            .sidecar
154            .capture_timestamp
155            .clone();
156        let corrected = capture.to_string();
157        self.append_lifecycle(asset_id, Action::MetadataUpdate, None, move |s, _add_id| {
158            s.capture_timestamp = corrected;
159        })?;
160        tracing::info!(
161            asset_id = %asset_id,
162            recorded = %recorded,
163            corrected = %capture,
164            chain_head = ?self.assets[asset_id].chain.head(),
165            "as-imported capture timestamp re-derived as a signed metadata-update"
166        );
167        Ok(())
168    }
169
170    /// Record the user's location for the asset: a [`GpsSource::Manual`] fix in `datum`, written
171    /// to the `gps_user` LWW register as one signed `metadata-update`, stamped with this device
172    /// id and now so concurrent edits converge under the `(ts, device_id)` rule.
173    ///
174    /// The as-imported `gps` is never overwritten; the effective location
175    /// ([`SidecarV1::effective_gps`](capsule_core::sidecar::SidecarV1::effective_gps)) is this edit.
176    /// The coordinate is stored verbatim in `datum`, never converted. A latitude outside
177    /// `[-90, 90]`, a longitude outside `[-180, 180]`, or a non-finite value is
178    /// [`LifecycleError::InvalidLocation`] and nothing is appended.
179    #[tracing::instrument(skip(self), fields(asset_id = %asset_id, ?datum))]
180    pub fn set_location(
181        &mut self,
182        asset_id: &Uuid,
183        lat: f64,
184        lon: f64,
185        datum: GpsDatum,
186    ) -> Result<()> {
187        let valid = lat.is_finite()
188            && lon.is_finite()
189            && (-90.0..=90.0).contains(&lat)
190            && (-180.0..=180.0).contains(&lon);
191        if !valid {
192            tracing::debug!(asset_id = %asset_id, "location edit refused: out of range");
193            return Err(LifecycleError::InvalidLocation { lat, lon });
194        }
195        self.write_location(
196            asset_id,
197            Some(Gps {
198                lat,
199                lon,
200                source: GpsSource::Manual,
201                datum,
202            }),
203        )
204    }
205
206    /// Record that the asset has **no** location, as the user's edit: a stamped `None` in the
207    /// `gps_user` register. The as-imported `gps` stays in the sidecar, hidden from the
208    /// effective view, so a later edit can restore it.
209    #[tracing::instrument(skip(self), fields(asset_id = %asset_id))]
210    pub fn clear_location(&mut self, asset_id: &Uuid) -> Result<()> {
211        self.write_location(asset_id, None)
212    }
213
214    fn write_location(&mut self, asset_id: &Uuid, location: Option<Gps>) -> Result<()> {
215        if !self.assets.contains_key(asset_id) {
216            return Err(LifecycleError::NotFound(format!("asset {asset_id}")));
217        }
218        let set = location.is_some();
219        let device = self.account.device.device_id;
220        let ts = now_rfc3339();
221        self.append_lifecycle(asset_id, Action::MetadataUpdate, None, move |s, _add_id| {
222            s.gps_user.set(location, ts, device);
223        })?;
224        tracing::info!(
225            asset_id = %asset_id,
226            set,
227            chain_head = ?self.assets[asset_id].chain.head(),
228            "location edited as a signed metadata-update"
229        );
230        Ok(())
231    }
232
233    // ── AI metadata containment (SSoT: metadata § Tag Provenance, ai § AI Output Containment) ──
234    //
235    // AI outputs land in a namespace **structurally** separate from user-authored metadata: the
236    // `tags_ai` OR-set, never `tags_user`. An AI suggestion can therefore never overwrite a user
237    // tag — the question does not arise — and a hallucinating model can only pollute its own
238    // namespace. Population is a signed `metadata-update` through the lifecycle, mirroring
239    // [`set_cull`](Self::set_cull)'s write-through; promotion to a user tag is explicit and signed.
240
241    /// Add AI-suggested tags to the asset's `tags_ai` OR-set — a namespace **structurally**
242    /// separate from `tags_user`, so an AI suggestion can never overwrite a user tag. Emits one
243    /// `metadata-update`; each tag gets a fresh `add_id` (pre-issued from this device's monotonic
244    /// counter) so it can later be dismissed or promoted individually. A no-op (no record) if
245    /// `tags` is empty. Each [`AiTag`] carries its producing `(model_id, model_version)` so a
246    /// superseded suggestion is excluded by [`current_ai_tags`](Self::current_ai_tags).
247    pub fn add_ai_tags(&mut self, asset_id: &Uuid, tags: Vec<AiTag>) -> Result<()> {
248        if tags.is_empty() {
249            return Ok(());
250        }
251        // Pre-issue one add_id per tag so a single metadata-update can carry the whole batch, each
252        // element independently addressable (the closure receives a single add_id, not the counter).
253        let tagged: Vec<(AiTag, AddId)> = tags
254            .into_iter()
255            .map(|t| (t, self.counter.issue()))
256            .collect();
257        self.append_lifecycle(asset_id, Action::MetadataUpdate, None, move |s, _add_id| {
258            for (tag, add_id) in tagged {
259                s.tags_ai.add(tag, add_id);
260            }
261        })
262    }
263
264    /// The asset's current AI tags paired with their `add_id`s — the surface a client uses to
265    /// dismiss or promote a specific suggestion. Reads the signed sidecar OR-set (the source of
266    /// truth), not a query cache.
267    pub fn ai_tags(&self, asset_id: &Uuid) -> Result<Vec<(AddId, AiTag)>> {
268        Ok(self
269            .assets
270            .get(asset_id)
271            .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?
272            .sidecar
273            .tags_ai
274            .entries())
275    }
276
277    /// Dismiss an AI tag: an OR-set remove on `tags_ai` keyed by its `add_id`, emitting a
278    /// `metadata-update`. Rejects an `add_id` never observed locally (a fabricated remove) rather
279    /// than silently no-oping.
280    pub fn dismiss_ai_tag(&mut self, asset_id: &Uuid, add_id: AddId) -> Result<()> {
281        let observed = self
282            .assets
283            .get(asset_id)
284            .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?
285            .sidecar
286            .tags_ai
287            .observed(&add_id);
288        if !observed {
289            return Err(LifecycleError::NotFound(format!(
290                "unobserved ai-tag add_id {add_id:?}"
291            )));
292        }
293        self.append_lifecycle(asset_id, Action::MetadataUpdate, None, move |s, _add_id| {
294            s.tags_ai
295                .remove(add_id)
296                .expect("add_id observed above; remove cannot fail");
297        })
298    }
299
300    /// Promote an AI tag to a user tag: copy its text into `tags_user` with a **fresh user-scoped
301    /// `add_id`**, leaving the AI entry intact (still independently dismissable). An explicit,
302    /// signed lifecycle operation — never automatic (ai § AI Output Containment).
303    ///
304    /// The copied text becomes an asset label, so it passes through [`normalize_label`]: an AI
305    /// tag whose text the label rule refuses cannot be promoted
306    /// ([`LifecycleError::InvalidLabel`]), nothing is appended, and the AI entry is untouched.
307    #[tracing::instrument(skip(self, tag), fields(asset_id = %asset_id))]
308    pub fn promote_ai_tag(&mut self, asset_id: &Uuid, tag: &str) -> Result<()> {
309        let present = self
310            .assets
311            .get(asset_id)
312            .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?
313            .sidecar
314            .tags_ai
315            .value()
316            .iter()
317            .any(|t| t.tag == tag);
318        if !present {
319            return Err(LifecycleError::NotFound(format!("ai tag '{tag}'")));
320        }
321        let tag = normalize_label(tag)?;
322        self.append_lifecycle(asset_id, Action::MetadataUpdate, None, move |s, add_id| {
323            s.tags_user.add(tag, add_id);
324        })
325    }
326
327    /// The asset's AI tags that are **current** under `registry` — their `(model_id,
328    /// model_version)` is the canonical pair for the model's task. Stale suggestions (a superseded
329    /// model version) are excluded until regenerated, mirroring the vector-index stale rule; the
330    /// sidecar retains every AI tag regardless (it is the source of truth).
331    pub fn current_ai_tags(&self, registry: &Registry, asset_id: &Uuid) -> Result<Vec<AiTag>> {
332        let sidecar = &self
333            .assets
334            .get(asset_id)
335            .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?
336            .sidecar;
337        Ok(sidecar
338            .tags_ai
339            .value()
340            .into_iter()
341            .filter(|t| {
342                registry
343                    .row_for_id(&ModelId::from(t.model_id.as_str()))
344                    .is_some_and(|row| row.canonical_version.as_str() == t.model_version)
345            })
346            .collect())
347    }
348}
349
350/// The read half of the inference seam: the orchestrator decodes an asset's plaintext and indexes
351/// vectors through the workspace's own catalog. A thin forward to the inherent methods — the
352/// indirection exists to reverse a module edge, not to change behaviour.
353impl AssetSource for Workspace {
354    type Error = LifecycleError;
355    type Index = DatabaseDriver;
356
357    fn read_plaintext(&self, asset_id: &Uuid) -> Result<Vec<u8>> {
358        Workspace::read_plaintext(self, asset_id)
359    }
360
361    fn vector_index(&self) -> &DatabaseDriver {
362        self.db()
363    }
364}
365
366/// The write half: AI tags produced by inference land in `tags_ai` as a signed `metadata-update`,
367/// exactly as a direct [`Workspace::add_ai_tags`] call would.
368impl AiTagSink for Workspace {
369    fn add_ai_tags(&mut self, asset_id: &Uuid, tags: Vec<AiTag>) -> Result<()> {
370        Workspace::add_ai_tags(self, asset_id, tags)
371    }
372}
373
374#[cfg(test)]
375mod tests;