turbovault-plugin-api 0.1.0

Stable plugin contract and curated vault facade for TurboVault
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;

/// Provenance supplied by a writer for best-effort event correlation.
///
/// Every field is caller-supplied and therefore unverified. For trustworthy
/// loop prevention use [`VaultEventEnvelope::plugin_id`], which the host
/// stamps.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct WriteProvenance {
    /// Stable caller-selected source, such as `daily-review-agent`.
    pub source: String,
    /// Optional identifier connecting related operations.
    pub correlation_id: Option<String>,
    /// Optional human-readable reason.
    pub note: Option<String>,
}

impl WriteProvenance {
    /// Construct provenance for `source`.
    pub fn new(source: impl Into<String>) -> Self {
        Self {
            source: source.into(),
            correlation_id: None,
            note: None,
        }
    }

    /// Link this write to related operations.
    pub fn with_correlation_id(mut self, correlation_id: impl Into<String>) -> Self {
        self.correlation_id = Some(correlation_id.into());
        self
    }

    /// Explain why the write happened.
    pub fn with_note(mut self, note: impl Into<String>) -> Self {
        self.note = Some(note.into());
        self
    }
}

/// Best-effort event attribution.
///
/// This is advisory loop-prevention metadata, never an authorization or
/// security boundary.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind", content = "provenance")]
#[non_exhaustive]
pub enum EventAttribution {
    /// The host correlated the observed content with a known write.
    Attributed(WriteProvenance),
    /// No trusted correlation was available; the change may be external.
    ExternalOrUnknown,
}

/// A vault mutation observed by a hook producer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
#[non_exhaustive]
pub enum HookEvent {
    /// A note was created.
    FileCreated {
        /// Vault-relative path.
        path: String,
    },
    /// A note was modified.
    FileModified {
        /// Vault-relative path.
        path: String,
    },
    /// A note was deleted.
    FileDeleted {
        /// Vault-relative path.
        path: String,
    },
    /// A note moved between two paths.
    FileRenamed {
        /// Original vault-relative path.
        from: String,
        /// New vault-relative path.
        to: String,
    },
    /// The authoritative state must be re-read after a producer reset.
    ResyncRequired {
        /// Human-readable reason for the reset.
        reason: String,
    },
}

/// Sequenced event delivered to hook subscribers.
///
/// Sequence numbers are assigned and the envelope is enqueued inside one
/// critical section, so subscribers observe events in sequence order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct VaultEventEnvelope {
    /// Identifier of the bus run that issued [`Self::sequence`].
    ///
    /// See [`HookBus::epoch`]. Persist it alongside the sequence — an
    /// [`EventCursor`] does this — or the number means nothing after a restart.
    pub epoch: String,
    /// Sequence number, monotonic within [`Self::epoch`] and only there.
    ///
    /// It counts from zero each time the host starts.
    pub sequence: u64,
    /// Observation time as Unix epoch milliseconds.
    pub observed_at_ms: u64,
    /// Vault name.
    pub vault: String,
    /// Observed mutation.
    pub event: HookEvent,
    /// Content identity when it was available at observation time.
    pub content_hash: Option<String>,
    /// Mounted plugin namespace the host attributes this write to.
    ///
    /// Stamped by the host from the validated descriptor of the plugin whose
    /// call produced the write, and not settable by the writer — unlike
    /// [`WriteProvenance`], which is advisory caller data. `None` means the
    /// change did not come through a plugin. This is the field to use for loop
    /// prevention: a plugin skips events whose `plugin_id` is its own.
    pub plugin_id: Option<String>,
    /// Best-effort writer attribution.
    pub attribution: EventAttribution,
}

/// Current event-bus lifecycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookLifecycle {
    /// New events may be published.
    Running,
    /// No further events will be accepted.
    Closed,
}

/// Publish failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum PublishError {
    /// The bus was explicitly closed.
    #[error("hook bus is closed")]
    Closed,
}

/// Receive failure with explicit overflow semantics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum HookRecvError {
    /// No event is currently available to a non-blocking receiver.
    #[error("no hook event is currently available")]
    Empty,
    /// This subscriber fell behind the bounded ring buffer.
    ///
    /// The consumer must re-read authoritative vault state before continuing.
    #[error("hook subscriber lagged by {skipped} event(s); resync required")]
    Lagged {
        /// Number of discarded envelopes.
        skipped: u64,
    },
    /// The bus closed and all buffered events were drained.
    #[error("hook bus is closed")]
    Closed,
}

/// A consumer's durable position in the event feed.
///
/// [`VaultEventEnvelope::sequence`] restarts at zero every time the host
/// starts, so a bare sequence number persisted across a restart is worse than
/// keeping no record at all: it looks comparable to the new run's numbering and
/// is not. Pairing the sequence with the epoch that issued it turns that silent
/// mis-resume into a question a plugin can answer — [`Self::resumes_on`].
///
/// Serializable, so it stores directly through [`crate::PluginStorage`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EventCursor {
    epoch: String,
    sequence: u64,
}

impl EventCursor {
    /// The position immediately after `envelope` has been applied.
    pub fn after(envelope: &VaultEventEnvelope) -> Self {
        Self {
            epoch: envelope.epoch.clone(),
            sequence: envelope.sequence,
        }
    }

    /// The bus run that issued [`Self::sequence`].
    pub fn epoch(&self) -> &str {
        &self.epoch
    }

    /// The last applied sequence within [`Self::epoch`].
    pub fn sequence(&self) -> u64 {
        self.sequence
    }

    /// Whether this position still means something on `bus`.
    ///
    /// `false` after a host restart, which is the case worth handling: the
    /// plugin cannot know what changed while it was down, so it must reconcile
    /// from [`crate::VaultApi::list_notes_detailed`] before trusting the feed.
    ///
    /// `true` is not a promise that nothing was missed — a subscriber can still
    /// fall behind within a run, which arrives separately as
    /// [`HookRecvError::Lagged`].
    pub fn resumes_on(&self, bus: &HookBus) -> bool {
        self.epoch == bus.epoch()
    }
}

struct HookBusInner {
    sender: Mutex<Option<broadcast::Sender<VaultEventEnvelope>>>,
    epoch: String,
    sequence: AtomicU64,
    closed: AtomicBool,
    capacity: usize,
}

/// Cloneable bounded event bus shared by a host and its plugins.
///
/// Delivery is best-effort. A slow subscriber receives
/// [`HookRecvError::Lagged`] and must resynchronize from [`crate::VaultApi`].
#[derive(Clone)]
pub struct HookBus {
    inner: Arc<HookBusInner>,
}

impl std::fmt::Debug for HookBus {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("HookBus")
            .field("epoch", &self.epoch())
            .field("capacity", &self.capacity())
            .field("lifecycle", &self.lifecycle())
            .finish()
    }
}

impl HookBus {
    fn sender(&self) -> std::sync::MutexGuard<'_, Option<broadcast::Sender<VaultEventEnvelope>>> {
        self.inner
            .sender
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Create a bus with a fixed per-subscriber ring-buffer capacity.
    ///
    /// A zero capacity is promoted to one.
    pub fn new(capacity: usize) -> Self {
        let capacity = capacity.max(1);
        let (sender, _) = broadcast::channel(capacity);
        Self {
            inner: Arc::new(HookBusInner {
                sender: Mutex::new(Some(sender)),
                epoch: uuid::Uuid::new_v4().to_string(),
                sequence: AtomicU64::new(0),
                closed: AtomicBool::new(false),
                capacity,
            }),
        }
    }

    /// Return this bus run's identifier.
    ///
    /// Freshly generated per bus, so it differs on every host start. The feed
    /// is in-memory: it has no history from before this run and its sequence
    /// numbering is meaningless outside it. The epoch is what makes that
    /// detectable rather than silent — see [`EventCursor`].
    ///
    /// Opaque and unordered; compare for equality only.
    pub fn epoch(&self) -> &str {
        &self.inner.epoch
    }

    /// Return the fixed ring-buffer capacity.
    pub fn capacity(&self) -> usize {
        self.inner.capacity
    }

    /// Return whether new events are accepted.
    pub fn lifecycle(&self) -> HookLifecycle {
        if self.inner.closed.load(Ordering::Acquire) {
            HookLifecycle::Closed
        } else {
            HookLifecycle::Running
        }
    }

    /// Subscribe to future events.
    pub fn subscribe(&self) -> Result<HookSubscription, PublishError> {
        let guard = self.sender();
        let sender = guard.as_ref().ok_or(PublishError::Closed)?;
        Ok(HookSubscription {
            receiver: sender.subscribe(),
        })
    }

    /// Sequence and publish an advisory event.
    ///
    /// Success does not imply that a subscriber exists. `plugin_id` is the
    /// host's own attribution of the writer and must never be taken from
    /// caller-supplied data.
    ///
    /// The sender mutex is held across both the sequence increment and the
    /// enqueue, so two concurrent publishes cannot be delivered out of
    /// sequence order.
    pub fn publish(
        &self,
        vault: impl Into<String>,
        event: HookEvent,
        content_hash: Option<String>,
        plugin_id: Option<String>,
        attribution: EventAttribution,
    ) -> Result<VaultEventEnvelope, PublishError> {
        let guard = self.sender();
        let sender = guard.as_ref().ok_or(PublishError::Closed)?;
        let envelope = VaultEventEnvelope {
            epoch: self.inner.epoch.clone(),
            sequence: self.inner.sequence.fetch_add(1, Ordering::Relaxed) + 1,
            observed_at_ms: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis()
                .try_into()
                .unwrap_or(u64::MAX),
            vault: vault.into(),
            event,
            content_hash,
            plugin_id,
            attribution,
        };
        let _subscriber_count = sender.send(envelope.clone());
        Ok(envelope)
    }

    /// Stop accepting events and close subscribers after buffered delivery.
    ///
    /// Returns `true` only for the call that changed the lifecycle.
    pub fn close(&self) -> bool {
        let mut guard = self.sender();
        let changed = guard.take().is_some();
        self.inner.closed.store(true, Ordering::Release);
        changed
    }
}

/// A single bounded subscription to [`HookBus`].
pub struct HookSubscription {
    receiver: broadcast::Receiver<VaultEventEnvelope>,
}

impl std::fmt::Debug for HookSubscription {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("HookSubscription")
            .finish_non_exhaustive()
    }
}

impl HookSubscription {
    /// Wait for the next event or an explicit lag/close condition.
    pub async fn recv(&mut self) -> Result<VaultEventEnvelope, HookRecvError> {
        self.receiver.recv().await.map_err(|error| match error {
            broadcast::error::RecvError::Closed => HookRecvError::Closed,
            broadcast::error::RecvError::Lagged(skipped) => HookRecvError::Lagged { skipped },
        })
    }

    /// Receive immediately without waiting.
    pub fn try_recv(&mut self) -> Result<VaultEventEnvelope, HookRecvError> {
        self.receiver.try_recv().map_err(|error| match error {
            broadcast::error::TryRecvError::Closed => HookRecvError::Closed,
            broadcast::error::TryRecvError::Lagged(skipped) => HookRecvError::Lagged { skipped },
            broadcast::error::TryRecvError::Empty => HookRecvError::Empty,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn publish(bus: &HookBus, path: &str) -> VaultEventEnvelope {
        bus.publish(
            "test",
            HookEvent::FileModified {
                path: path.to_string(),
            },
            None,
            None,
            EventAttribution::ExternalOrUnknown,
        )
        .expect("publish")
    }

    #[tokio::test]
    async fn sequences_events_and_closes_after_buffered_delivery() {
        // Capacity two retains both events until this subscriber reads them.
        const CAPACITY: usize = 2;
        let bus = HookBus::new(CAPACITY);
        let mut subscription = bus.subscribe().expect("subscribe");
        assert_eq!(publish(&bus, "a.md").sequence, 1);
        assert_eq!(publish(&bus, "b.md").sequence, 2);
        assert!(bus.close());
        assert!(!bus.close());

        assert_eq!(subscription.recv().await.expect("first").sequence, 1);
        assert_eq!(subscription.recv().await.expect("second").sequence, 2);
        assert_eq!(subscription.recv().await, Err(HookRecvError::Closed));
        assert_eq!(bus.lifecycle(), HookLifecycle::Closed);
    }

    #[tokio::test]
    async fn reports_lag_and_requires_resync() {
        // Capacity one intentionally evicts the first of two unread events.
        const CAPACITY: usize = 1;
        let bus = HookBus::new(CAPACITY);
        let mut subscription = bus.subscribe().expect("subscribe");
        publish(&bus, "a.md");
        publish(&bus, "b.md");

        assert_eq!(
            subscription.recv().await,
            Err(HookRecvError::Lagged { skipped: 1 })
        );
        assert_eq!(subscription.recv().await.expect("retained").sequence, 2);
    }

    #[test]
    fn cursors_do_not_resume_across_a_restart() {
        // Two buses stand in for two runs of the host.
        let first_run = HookBus::new(4);
        let second_run = HookBus::new(4);
        assert_ne!(first_run.epoch(), second_run.epoch());

        let applied = EventCursor::after(&publish(&first_run, "a.md"));
        assert_eq!(applied.sequence(), 1);
        assert!(applied.resumes_on(&first_run));

        // The sequence number alone would compare as "already seen" against the
        // new run's first event. The epoch is what makes the mismatch visible.
        let after_restart = publish(&second_run, "b.md");
        assert_eq!(after_restart.sequence, applied.sequence());
        assert!(!applied.resumes_on(&second_run));

        // Round-trips through storage unchanged.
        let encoded = serde_json::to_vec(&applied).expect("serialize cursor");
        let decoded: EventCursor = serde_json::from_slice(&encoded).expect("deserialize cursor");
        assert_eq!(decoded, applied);
        assert!(decoded.resumes_on(&first_run));
    }

    #[test]
    fn rejects_new_work_after_close() {
        let bus = HookBus::new(0);
        assert_eq!(bus.capacity(), 1);
        assert!(bus.close());
        assert!(matches!(bus.subscribe(), Err(PublishError::Closed)));
        assert_eq!(
            bus.publish(
                "test",
                HookEvent::ResyncRequired {
                    reason: "closed".to_string()
                },
                None,
                None,
                EventAttribution::ExternalOrUnknown
            ),
            Err(PublishError::Closed)
        );
    }
}