Skip to main content

acdp_server/registry/
store.rs

1//! Registry persistence abstraction (feature = "server").
2//!
3//! [`RegistryStore`] is the minimal contract a registry implementation
4//! must satisfy: store an immutable [`Body`] under a registry-assigned
5//! [`CtxId`], track the parent lineage, mark predecessors superseded,
6//! and project search/lineage queries. The trait is synchronous and
7//! object-safe so a [`RegistryServer`](super::server::RegistryServer)
8//! can be parameterised over any backend (in-memory for tests, SQLite
9//! for production, etc.) without an async runtime dependency.
10//!
11//! [`InMemoryStore`] is the reference implementation used by the
12//! integration tests and intended as a drop-in for prototyping.
13
14use std::sync::Mutex;
15
16use acdp_primitives::error::AcdpError;
17use acdp_types::{
18    body::{Body, FullContext, RegistryState},
19    lifecycle::{LifecycleEvent, LifecycleEventType},
20    primitives::{AgentDid, CtxId, LineageId, Status, Visibility},
21    publish::{PublishRequest, PublishResponse},
22    search::{SearchParams, SearchResponse, SearchResult},
23};
24
25/// Abstract registry persistence backend.
26///
27/// Synchronous — the in-memory implementation is mutex-guarded; async
28/// backends should wrap blocking calls with `spawn_blocking` at the
29/// HTTP boundary.
30pub trait RegistryStore: Send + Sync {
31    /// Persist a freshly-assigned context. `body.ctx_id` and
32    /// `body.lineage_id` are already populated by the server.
33    fn put(&self, body: Body) -> Result<(), AcdpError>;
34
35    /// Retrieve a stored context by `ctx_id`.
36    fn get(&self, ctx_id: &CtxId) -> Result<Option<FullContext>, AcdpError>;
37
38    /// All contexts in a lineage, oldest first.
39    fn lineage(&self, lineage_id: &LineageId) -> Result<Vec<FullContext>, AcdpError>;
40
41    /// Returns the newest version of a lineage that is **neither
42    /// [`Status::Superseded`] nor [`Status::Retracted`]** — either
43    /// [`Status::Active`] or [`Status::Expired`] (an
44    /// expired-but-unreplaced body is still the latest version, and
45    /// callers need to see it to know it has lapsed; a retracted one is
46    /// never a head, RFC-ACDP-0013 §8.3).
47    ///
48    /// Returns `Ok(None)` when the lineage is unknown or every version is
49    /// superseded or retracted (RFC-ACDP-0004 §5.2: "if no such version
50    /// exists, returns not_found" — fixtures `ret-002` / `lc-003`).
51    /// Visibility rules are NOT applied here — filter at the server
52    /// layer via [`crate::registry::server::RegistryServer::current`].
53    fn current(&self, lineage_id: &LineageId) -> Result<Option<FullContext>, AcdpError>;
54
55    /// Mark `ctx_id`'s registry state as `superseded`. Idempotent.
56    fn mark_superseded(&self, ctx_id: &CtxId) -> Result<(), AcdpError>;
57
58    /// First-version `ctx_id` for a lineage, used to derive the
59    /// lineage_id of a supersession publish per RFC-ACDP-0001 §5.6.
60    ///
61    /// LINEAGE ANCHORING (WS-D3). Implementations SHOULD answer this
62    /// (and the supersession checks in [`Self::commit_publish`]) from
63    /// **persisted rows** — the immediate predecessor's stored
64    /// `lineage_id`/`version` and a lineage index — NOT by re-walking
65    /// the full `supersedes` chain at publish time. A registry's own
66    /// storage is trusted; anchoring removes the
67    /// `lineage_walk_failed` liveness failure where a v(N+1) publish is
68    /// rejected because some deep intermediate is unretrievable even
69    /// though the immediate predecessor exists. Reserve the full
70    /// chain walk for offline integrity audits, off the publish path.
71    /// (`InMemoryStore` implements exactly this pattern.)
72    fn first_version_ctx_id(&self, lineage_id: &LineageId) -> Result<Option<CtxId>, AcdpError>;
73
74    /// Keyword/filter search. Implementations MUST apply the RFC-ACDP-0008
75    /// §4.5 search-disclosure rules using `requester`:
76    ///
77    /// | Visibility   | Surfaces in search to                        |
78    /// |--------------|----------------------------------------------|
79    /// | `public`     | anyone                                       |
80    /// | `restricted` | producer (`agent_id`) **or** any DID in `audience` |
81    /// | `private`    | producer (`agent_id`) only — audience members must already know the ctx_id |
82    ///
83    /// `requester == None` represents an anonymous caller. Public
84    /// contexts surface only when `anonymous_public_reads` is true (the
85    /// capability flag from [`RegistryServer`](super::server::RegistryServer));
86    /// the store implements the same predicate as `RegistryServer::retrieve`
87    /// so the two endpoints stay symmetric (RFC-ACDP-0008 §4.5).
88    ///
89    /// Projection follows RFC-ACDP-0005 §2.2 `match_summary`.
90    fn search(
91        &self,
92        params: &SearchParams,
93        requester: Option<&AgentDid>,
94        anonymous_public_reads: bool,
95    ) -> Result<SearchResponse, AcdpError>;
96
97    // ── Idempotency (RFC-ACDP-0003 §6) ─────────────────────────────────
98    //
99    // Stores supporting the `idempotency_key` capability MUST implement
100    // these three methods. The default impls treat the store as
101    // non-idempotent: lookup always returns `None`, record is a no-op,
102    // evict is a no-op. A `RegistryServer` configured with
103    // `caps.supports_idempotency_key = false` MUST never call them
104    // (RFC-ACDP-0007 §3.2).
105    //
106    // ATOMICITY CONTRACT (WS-D4). Keys are scoped per `agent_id`: two
107    // different agents using the same key never interact. The
108    // idempotency record and the body persistence MUST commit
109    // atomically (single transaction / compare-and-swap / one lock —
110    // see `commit_publish`); a backend that cannot provide this (e.g.
111    // an eventually-consistent store) MUST NOT be paired with
112    // `supports_idempotency_key: true`, because concurrent identical-key
113    // publishes could mint two ctx_ids and silently defeat the
114    // guarantee the capability advertises. Durable backends should
115    // enforce a UNIQUE constraint on `(agent_id, idempotency_key)` and
116    // insert it in the same transaction as the context row.
117
118    /// Look up a prior publish record for `(agent_id, key)`.
119    ///
120    /// Returns `Some((content_hash, response))` if a record exists and
121    /// has not expired. Scoping by `agent_id` prevents a malicious
122    /// producer from poisoning another producer's key namespace
123    /// (RFC-ACDP-0003 §6 — idem-004 fixture).
124    fn idempotency_lookup(
125        &self,
126        _agent_id: &AgentDid,
127        _key: &str,
128    ) -> Result<Option<IdempotencyRecord>, AcdpError> {
129        Ok(None)
130    }
131
132    /// Record a successful publish under `(agent_id, key)` with TTL
133    /// `expires_at`. Calling on a store that does not support
134    /// idempotency is a no-op.
135    fn idempotency_record(
136        &self,
137        _agent_id: &AgentDid,
138        _key: &str,
139        _hash: &acdp_types::primitives::ContentHash,
140        _response: &acdp_types::publish::PublishResponse,
141        _expires_at: chrono::DateTime<chrono::Utc>,
142    ) -> Result<(), AcdpError> {
143        Ok(())
144    }
145
146    /// Evict records whose `expires_at` is past `now`. Implementations
147    /// may call this on a janitor schedule or lazily at lookup time.
148    fn idempotency_evict_expired(
149        &self,
150        _now: chrono::DateTime<chrono::Utc>,
151    ) -> Result<(), AcdpError> {
152        Ok(())
153    }
154
155    // ── Atomic publish commit (FEAT-01) ────────────────────────────────
156
157    /// Atomically commit a publish: idempotency lookup, supersession
158    /// validation, body insertion, predecessor supersession marking,
159    /// and idempotency record write — all under a single critical
160    /// section so two concurrent publishes targeting the same
161    /// `supersedes` (or sharing an `idempotency_key`) cannot both
162    /// succeed.
163    ///
164    /// Eliminates the TOCTOU races that the old
165    /// `put → mark_superseded → idempotency_record` sequence allowed.
166    /// Returns:
167    /// - `Inserted(response)` — the body was newly persisted.
168    /// - `IdempotentReplay(response)` — a prior record with the same
169    ///   `(agent_id, key, content_hash)` was found and its response is
170    ///   replayed verbatim (idem-002).
171    ///
172    /// On supersession contention (predecessor already marked
173    /// `Superseded`, lineage mismatch, etc.) returns
174    /// `AcdpError::SupersededTarget { reason, … }`. On idempotency-key
175    /// collision with a different `content_hash` returns
176    /// `AcdpError::DuplicatePublish` (idem-003).
177    fn commit_publish(&self, commit: PublishCommit<'_>) -> Result<PublishCommitOutcome, AcdpError>;
178
179    // ── Lifecycle events (ACDP 0.3, RFC-ACDP-0013) ─────────────────────
180
181    /// Atomically append a lifecycle event and apply its status effect
182    /// (RFC-ACDP-0013 §6 steps 4–5).
183    ///
184    /// CONTRACT — an implementation MUST, under one critical section /
185    /// transaction:
186    ///
187    /// 1. Resolve `event.ctx_id`; unknown → [`AcdpError::NotFound`]
188    ///    (visibility filtering is the server's job, before this call).
189    /// 2. **Retry idempotency** (§6): if an already-appended event has
190    ///    the same `event_id` *and identical content*, append nothing
191    ///    and return [`LifecycleCommitOutcome::IdempotentReplay`] with
192    ///    the current projected context; same `event_id` with
193    ///    *different* content → [`AcdpError::SchemaViolation`].
194    /// 3. **Strict alternation** (§6 step 4, §7.1): `retracted` is
195    ///    accepted only when the context's retraction state is *not
196    ///    retracted*; `republished` only when it *is*. A violation
197    ///    (double retract, spurious republish) →
198    ///    [`AcdpError::InvalidLifecycleTransition`], with **no state
199    ///    change**. An unregistered `event_type` →
200    ///    [`AcdpError::SchemaViolation`] (§7.3).
201    /// 4. Append the event at the END of `lifecycle_events` (append-only
202    ///    — never remove, reorder, or mutate, §4.1) atomically with the
203    ///    status effect, and return
204    ///    [`LifecycleCommitOutcome::Applied`] with the post-transition
205    ///    context (`status` reflecting the §7.2 precedence:
206    ///    `retracted` > `superseded` > `expired` > `active`).
207    ///
208    /// The default returns [`AcdpError::NotImplemented`] — deliberately
209    /// NOT a benign no-op like the idempotency defaults: silently
210    /// dropping a retraction would defeat the withdrawal the producer
211    /// signed, whereas a missing idempotency record only costs a
212    /// replay. A `RegistryServer` enabled with
213    /// [`with_lifecycle`](crate::registry::server::RegistryServer::with_lifecycle)
214    /// MUST be paired with a store that implements this method; a
215    /// registry not advertising `acdp-registry-lifecycle` never calls
216    /// it (and its wire layer maps the error to `not_implemented` /
217    /// HTTP 501, the §6 rule).
218    fn commit_lifecycle_event(
219        &self,
220        event: &LifecycleEvent,
221    ) -> Result<LifecycleCommitOutcome, AcdpError> {
222        let _ = event;
223        Err(AcdpError::NotImplemented(
224            "this RegistryStore backend does not implement lifecycle events \
225             (RFC-ACDP-0013): commit_lifecycle_event is not available"
226                .into(),
227        ))
228    }
229}
230
231/// Outcome of an atomic [`RegistryStore::commit_lifecycle_event`].
232#[derive(Debug)]
233pub enum LifecycleCommitOutcome {
234    /// The event was appended and the status effect applied; carries
235    /// the post-transition full context (RFC-ACDP-0013 §6 step 5: the
236    /// caller sees the new state in the shape it already knows).
237    Applied(FullContext),
238    /// The event's `event_id` matched an already-appended event with
239    /// identical content — nothing was appended; carries the current
240    /// state (§6 retry idempotency: a producer whose POST timed out
241    /// after the append must not receive a spurious
242    /// `invalid_lifecycle_transition`).
243    IdempotentReplay(FullContext),
244}
245
246impl LifecycleCommitOutcome {
247    /// The post-transition (or current, on replay) full context.
248    pub fn into_context(self) -> FullContext {
249        match self {
250            LifecycleCommitOutcome::Applied(ctx)
251            | LifecycleCommitOutcome::IdempotentReplay(ctx) => ctx,
252        }
253    }
254}
255
256/// Single-shot atomic publish input (FEAT-01).
257///
258/// Passed to [`RegistryStore::commit_publish`] so the predecessor
259/// lookup, supersession check, body insertion, predecessor
260/// supersession marking, and idempotency record are all done under one
261/// critical section. Eliminates TOCTOU races between two concurrent
262/// publishes that target the same `supersedes` ctx_id or share an
263/// `idempotency_key`.
264pub struct PublishCommit<'a> {
265    /// The validated, signature-verified publish request.
266    pub req: &'a PublishRequest,
267    /// The hostname the registry serves — used to mint `ctx_id`s and
268    /// stored verbatim into `body.origin_registry` (BUG-01).
269    pub authority: &'a str,
270    /// Idempotency wiring, present iff the registry advertises
271    /// `caps.supports_idempotency_key` and the request carries an
272    /// `Idempotency-Key`.
273    pub idempotency: Option<PendingIdempotencyCommit<'a>>,
274    /// Tenant this publish is scoped to, if the registry is multi-tenant.
275    /// `None` means untenanted (single-tenant / V0). A multi-tenant store
276    /// MUST persist this atomically with the context row so the tenancy is
277    /// never observable as the default bucket (and never stranded there on a
278    /// crash between insert and a separate stamping UPDATE). Stores that do
279    /// not implement tenancy ignore it.
280    pub tenant: Option<&'a str>,
281    /// Receipt minting hook (ACDP 0.2, RFC-ACDP-0010). When present,
282    /// the store MUST invoke it with the fully assigned [`Body`]
283    /// (ctx_id / lineage_id / created_at populated) **inside the same
284    /// critical section / transaction as the insert**, persist the
285    /// returned receipt with the context, and include it in the
286    /// response. A context published under the
287    /// `acdp-registry-receipts` profile must never exist without its
288    /// receipt — a crash between insert and mint must not be
289    /// observable. `None` for receipt-less (0.1.0-mode) registries.
290    #[allow(clippy::type_complexity)]
291    pub receipt_minter:
292        Option<&'a (dyn Fn(&Body) -> Result<serde_json::Value, AcdpError> + Send + Sync)>,
293}
294
295/// Idempotency parameters threaded through [`PublishCommit`].
296pub struct PendingIdempotencyCommit<'a> {
297    /// The key the producer supplied in the `Idempotency-Key` header.
298    pub key: &'a str,
299    /// TTL after which the idempotency record may be evicted (typically
300    /// `caps.limits.idempotency_key_ttl_seconds`).
301    pub ttl: chrono::Duration,
302}
303
304/// Outcome of an atomic [`RegistryStore::commit_publish`].
305#[derive(Debug)]
306pub enum PublishCommitOutcome {
307    /// Fresh publish — the body was newly persisted and the response
308    /// describes the just-assigned identifiers.
309    Inserted(PublishResponse),
310    /// `(agent_id, idempotency_key)` had a prior record with the same
311    /// `content_hash` — return the original response per idem-002.
312    IdempotentReplay(PublishResponse),
313}
314
315/// Cached publish response keyed by `(agent_id, idempotency_key)`
316/// (RFC-ACDP-0003 §6).
317#[derive(Debug, Clone)]
318pub struct IdempotencyRecord {
319    /// The original request's `content_hash`. A retry with the same key
320    /// but a different hash MUST be rejected as `duplicate_publish`.
321    pub content_hash: acdp_types::primitives::ContentHash,
322    /// The response the registry returned on the first acceptance.
323    pub response: acdp_types::publish::PublishResponse,
324    /// Eviction time (TTL window from caps.limits.idempotency_key_ttl_seconds).
325    pub expires_at: chrono::DateTime<chrono::Utc>,
326}
327
328// ── In-memory reference implementation ───────────────────────────────────────
329
330/// Minimal in-memory backend. Not durable; intended for tests and
331/// prototyping. Concurrency-safe (a single `Mutex` over the table).
332#[derive(Default)]
333pub struct InMemoryStore {
334    inner: Mutex<Inner>,
335}
336
337#[derive(Default)]
338struct Inner {
339    /// All contexts keyed by `ctx_id`. Insertion-ordered per lineage
340    /// thanks to the parallel `lineages` index.
341    by_ctx: std::collections::BTreeMap<String, FullContext>,
342    /// `lineage_id -> [ctx_id, ctx_id, ...]` in publish order.
343    lineages: std::collections::BTreeMap<String, Vec<String>>,
344    /// `(agent_did, idempotency_key) -> record` (RFC-ACDP-0003 §6).
345    idempotency: std::collections::HashMap<(String, String), IdempotencyRecord>,
346}
347
348impl InMemoryStore {
349    /// Construct an empty store.
350    pub fn new() -> Self {
351        Self::default()
352    }
353
354    fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
355        self.inner.lock().expect("InMemoryStore mutex poisoned")
356    }
357}
358
359/// RFC-ACDP-0004 §4 (as amended by RFC-ACDP-0013 §7.2) — derive the
360/// served `status` at read time from the stored state, the lifecycle
361/// event history, and the clock, so a registry that does not run a
362/// janitor still surfaces the correct lifecycle status.
363///
364/// Precedence: `retracted` > `superseded` > `expired` > `active`.
365/// Retraction state is derived from `lifecycle_events` (§7.1) and
366/// dominates everything — including a stored `Superseded` and a lapsed
367/// `expires_at`; republication removes the retraction from the
368/// derivation (not the history) and the status re-derives as though
369/// never retracted.
370pub(crate) fn project_status(
371    state: &RegistryState,
372    body: &Body,
373    now: chrono::DateTime<chrono::Utc>,
374) -> Status {
375    if state.is_retracted() {
376        return Status::Retracted;
377    }
378    match &state.status {
379        Status::Active => match body.expires_at {
380            Some(exp) if exp <= now => Status::Expired,
381            _ => Status::Active,
382        },
383        other => other.clone(),
384    }
385}
386
387/// Materialize the effective view of a stored context: applies
388/// [`project_status`] to override the stored status when retracted or
389/// expired.
390pub(crate) fn project_context(
391    mut ctx: FullContext,
392    now: chrono::DateTime<chrono::Utc>,
393) -> FullContext {
394    ctx.registry_state.status = project_status(&ctx.registry_state, &ctx.body, now);
395    ctx
396}
397
398/// RFC-ACDP-0008 §4.5 search-disclosure rule.
399///
400/// Note the asymmetry vs retrieval: a `Private` context surfaces in search
401/// **only** to its producer — audience members must already know the
402/// `ctx_id` to fetch it. `Restricted` surfaces to producer + audience.
403///
404/// `anonymous_public_reads` mirrors the capability advertisement
405/// (RFC-ACDP-0008 §4.5): a registry that does NOT permit anonymous
406/// public reads MUST suppress public contexts for unauthenticated
407/// callers in both `retrieve` and `search`. The retrieval helper
408/// already consults this flag; this function pulls it through to the
409/// store-side search path (BUG-02).
410fn can_surface_in_search(
411    body: &Body,
412    requester: Option<&AgentDid>,
413    anonymous_public_reads: bool,
414) -> bool {
415    match body.visibility {
416        Visibility::Public => anonymous_public_reads || requester.is_some(),
417        Visibility::Restricted => match requester {
418            None => false,
419            Some(r) => {
420                r == &body.agent_id
421                    || body
422                        .audience
423                        .as_deref()
424                        .is_some_and(|a| a.iter().any(|d| d == r))
425            }
426        },
427        Visibility::Private => requester == Some(&body.agent_id),
428    }
429}
430
431impl RegistryStore for InMemoryStore {
432    fn put(&self, body: Body) -> Result<(), AcdpError> {
433        let ctx_id = body.ctx_id.0.clone();
434        let lineage_id = body.lineage_id.0.clone();
435        let ctx = FullContext {
436            body,
437            registry_state: RegistryState {
438                status: Status::Active,
439                lifecycle_events: None,
440                extensions: Default::default(),
441            },
442            registry_receipt: None,
443            lineage_head_receipt: None,
444            log_inclusion: None,
445            extensions: Default::default(),
446        };
447        let mut g = self.lock();
448        if g.by_ctx.contains_key(&ctx_id) {
449            return Err(AcdpError::SchemaViolation(format!(
450                "duplicate ctx_id '{ctx_id}' in store"
451            )));
452        }
453        g.by_ctx.insert(ctx_id.clone(), ctx);
454        g.lineages.entry(lineage_id).or_default().push(ctx_id);
455        Ok(())
456    }
457
458    fn get(&self, ctx_id: &CtxId) -> Result<Option<FullContext>, AcdpError> {
459        let now = chrono::Utc::now();
460        Ok(self
461            .lock()
462            .by_ctx
463            .get(ctx_id.as_str())
464            .cloned()
465            .map(|c| project_context(c, now)))
466    }
467
468    fn lineage(&self, lineage_id: &LineageId) -> Result<Vec<FullContext>, AcdpError> {
469        let now = chrono::Utc::now();
470        let g = self.lock();
471        let Some(ids) = g.lineages.get(lineage_id.as_str()) else {
472            return Ok(Vec::new());
473        };
474        Ok(ids
475            .iter()
476            .filter_map(|id| g.by_ctx.get(id).cloned().map(|c| project_context(c, now)))
477            .collect())
478    }
479
480    fn current(&self, lineage_id: &LineageId) -> Result<Option<FullContext>, AcdpError> {
481        let now = chrono::Utc::now();
482        let g = self.lock();
483        let Some(ids) = g.lineages.get(lineage_id.as_str()) else {
484            return Ok(None);
485        };
486        // RFC-ACDP-0004 §5: "Returns the unique version that has no
487        // successor. If no such version exists, returns not_found."
488        // Walk newest-to-oldest and return the first version that is
489        // neither `Superseded` nor `Retracted`. Both `Active` and
490        // `Expired` count — an expired body that hasn't been replaced
491        // is still the latest, and the consumer needs to see it (with
492        // status=Expired) to know it has lapsed. A retracted version is
493        // NEVER a head (RFC-ACDP-0013 §8.3): it has been explicitly
494        // withdrawn from reliance, and falling back to a superseded
495        // predecessor would silently serve a replaced context — so
496        // retracting a linear lineage's head yields `None` (fixture
497        // `lc-003`).
498        //
499        // BUG-04: an earlier fallback returned the last entry even when
500        // every version was `Superseded`; that's a protocol violation.
501        // Now we return `None` instead.
502        for id in ids.iter().rev() {
503            if let Some(ctx) = g.by_ctx.get(id) {
504                let projected = project_context(ctx.clone(), now);
505                if !matches!(
506                    projected.registry_state.status,
507                    Status::Superseded | Status::Retracted
508                ) {
509                    return Ok(Some(projected));
510                }
511            }
512        }
513        Ok(None)
514    }
515
516    fn commit_lifecycle_event(
517        &self,
518        event: &LifecycleEvent,
519    ) -> Result<LifecycleCommitOutcome, AcdpError> {
520        let now = chrono::Utc::now();
521        let mut g = self.lock();
522        let ctx = g.by_ctx.get_mut(event.ctx_id.as_str()).ok_or_else(|| {
523            AcdpError::NotFound(format!(
524                "context '{}' not found in this registry",
525                event.ctx_id
526            ))
527        })?;
528        let events = ctx
529            .registry_state
530            .lifecycle_events
531            .as_deref()
532            .unwrap_or(&[]);
533
534        // §6 retry idempotency / duplicate event_id (step 2).
535        if let Some(prior) = events.iter().find(|e| e.event_id == event.event_id) {
536            if prior == event {
537                return Ok(LifecycleCommitOutcome::IdempotentReplay(project_context(
538                    ctx.clone(),
539                    now,
540                )));
541            }
542            return Err(AcdpError::SchemaViolation(format!(
543                "event_id '{}' was already appended with different content \
544                 (RFC-ACDP-0013 §4: event_id MUST be unique within lifecycle_events)",
545                event.event_id
546            )));
547        }
548
549        // §6 step 4 — strict retracted/republished alternation against
550        // the §7.1 retraction state, under the same lock as the append.
551        let currently_retracted = acdp_types::lifecycle::retraction_state(events);
552        match &event.event_type {
553            LifecycleEventType::Retracted if currently_retracted => {
554                return Err(AcdpError::InvalidLifecycleTransition(format!(
555                    "context '{}' is already retracted — double retract violates the \
556                     strict alternation rule (RFC-ACDP-0013 §6 step 4)",
557                    event.ctx_id
558                )));
559            }
560            LifecycleEventType::Republished if !currently_retracted => {
561                return Err(AcdpError::InvalidLifecycleTransition(format!(
562                    "context '{}' is not retracted — republish requires a prior \
563                     retraction (RFC-ACDP-0013 §6 step 4)",
564                    event.ctx_id
565                )));
566            }
567            LifecycleEventType::Other(other) => {
568                return Err(AcdpError::SchemaViolation(format!(
569                    "event_type '{other}' is not registered for acceptance in 0.3.0 — \
570                     only 'retracted' and 'republished' transition state \
571                     (RFC-ACDP-0013 §7.3)"
572                )));
573            }
574            LifecycleEventType::Retracted | LifecycleEventType::Republished => {}
575        }
576
577        // §6 step 5 — append atomically with the status effect. The
578        // served status is DERIVED from this same array (§7.2
579        // precedence, applied by `project_status`), so appending the
580        // event IS the status change; the stored status keeps tracking
581        // the supersession fact only.
582        ctx.registry_state
583            .lifecycle_events
584            .get_or_insert_with(Vec::new)
585            .push(event.clone());
586        Ok(LifecycleCommitOutcome::Applied(project_context(
587            ctx.clone(),
588            now,
589        )))
590    }
591
592    fn mark_superseded(&self, ctx_id: &CtxId) -> Result<(), AcdpError> {
593        let mut g = self.lock();
594        if let Some(ctx) = g.by_ctx.get_mut(ctx_id.as_str()) {
595            ctx.registry_state.status = Status::Superseded;
596        }
597        Ok(())
598    }
599
600    fn first_version_ctx_id(&self, lineage_id: &LineageId) -> Result<Option<CtxId>, AcdpError> {
601        let g = self.lock();
602        Ok(g.lineages
603            .get(lineage_id.as_str())
604            .and_then(|ids| ids.first().cloned())
605            .map(CtxId))
606    }
607
608    fn idempotency_lookup(
609        &self,
610        agent_id: &AgentDid,
611        key: &str,
612    ) -> Result<Option<IdempotencyRecord>, AcdpError> {
613        // Lazy TTL eviction at lookup time keeps the table bounded
614        // without requiring a janitor — see idempotency_evict_expired.
615        self.idempotency_evict_expired(chrono::Utc::now())?;
616        let g = self.lock();
617        Ok(g.idempotency
618            .get(&(agent_id.as_str().to_string(), key.to_string()))
619            .cloned())
620    }
621
622    fn idempotency_record(
623        &self,
624        agent_id: &AgentDid,
625        key: &str,
626        hash: &acdp_types::primitives::ContentHash,
627        response: &acdp_types::publish::PublishResponse,
628        expires_at: chrono::DateTime<chrono::Utc>,
629    ) -> Result<(), AcdpError> {
630        let mut g = self.lock();
631        g.idempotency.insert(
632            (agent_id.as_str().to_string(), key.to_string()),
633            IdempotencyRecord {
634                content_hash: hash.clone(),
635                response: response.clone(),
636                expires_at,
637            },
638        );
639        Ok(())
640    }
641
642    fn idempotency_evict_expired(
643        &self,
644        now: chrono::DateTime<chrono::Utc>,
645    ) -> Result<(), AcdpError> {
646        let mut g = self.lock();
647        g.idempotency.retain(|_, r| r.expires_at > now);
648        Ok(())
649    }
650
651    fn commit_publish(&self, commit: PublishCommit<'_>) -> Result<PublishCommitOutcome, AcdpError> {
652        use crate::registry::validator::assign_identifiers;
653
654        let PublishCommit {
655            req,
656            authority,
657            idempotency,
658            // InMemoryStore does not model tenancy (it is a single-tenant
659            // reference/test backend); the durable backends honor this.
660            tenant: _,
661            receipt_minter,
662        } = commit;
663        let now = chrono::Utc::now();
664        let mut g = self.lock();
665
666        // ── 1. Idempotency replay / collision ────────────────────────
667        if let Some(idem) = &idempotency {
668            let idem_key = (req.agent_id.as_str().to_string(), idem.key.to_string());
669            if let Some(prior) = g.idempotency.get(&idem_key) {
670                if prior.expires_at > now {
671                    return if prior.content_hash == req.content_hash {
672                        // idem-002: same key + same hash → replay.
673                        Ok(PublishCommitOutcome::IdempotentReplay(
674                            prior.response.clone(),
675                        ))
676                    } else {
677                        // idem-003: same key + different hash → duplicate_publish.
678                        Err(AcdpError::DuplicatePublish(format!(
679                            "Idempotency-Key '{}' was previously used by '{}' \
680                             with a different content_hash",
681                            idem.key, req.agent_id
682                        )))
683                    };
684                }
685                // Expired record — fall through and overwrite below.
686            }
687        }
688
689        // ── 2. Supersession lookups + coherence checks ──────────────
690        let first_v1 = if let Some(prev) = &req.supersedes {
691            let prev_full = g.by_ctx.get(prev.as_str()).cloned().ok_or_else(|| {
692                AcdpError::SupersededTarget {
693                    reason: acdp_primitives::error::SupersessionReason::NotFound,
694                    message: format!("supersedes target '{prev}' not found in this registry"),
695                }
696            })?;
697
698            // Producer-continuity: only the predecessor's producer (or a
699            // declared contributor) may publish a successor in its lineage.
700            // Signature verification only proves the *requester* signed
701            // their own request — it does not bind `supersedes` to the
702            // predecessor's owner. Without this check any signer could
703            // supersede another producer's context (`Superseded` side
704            // effect below + `current(lineage)` re-pointing), a full
705            // lineage takeover. RFC-ACDP-0001 §5.9 supersession is
706            // producer-scoped.
707            let is_owner = req.agent_id == prev_full.body.agent_id
708                || prev_full.body.contributors.contains(&req.agent_id);
709            if !is_owner {
710                // Uniform with the genuine not-found case above: a
711                // non-owner learns neither that the predecessor exists nor
712                // its version / superseded status (supersession existence
713                // oracle). Anyone who can legitimately read the
714                // predecessor learns nothing new from this shape.
715                return Err(AcdpError::SupersededTarget {
716                    reason: acdp_primitives::error::SupersessionReason::NotFound,
717                    message: format!("supersedes target '{prev}' not found in this registry"),
718                });
719            }
720
721            // Lineage coherence — when the producer self-verifies.
722            if let Some(declared) = &req.lineage_id {
723                if declared != &prev_full.body.lineage_id {
724                    return Err(AcdpError::SupersededTarget {
725                        reason: acdp_primitives::error::SupersessionReason::LineageMismatch,
726                        message: format!(
727                            "declared lineage_id '{declared}' ≠ predecessor's '{}'",
728                            prev_full.body.lineage_id
729                        ),
730                    });
731                }
732            }
733            // Version coherence: new.version MUST be predecessor.version + 1.
734            if req.version != prev_full.body.version + 1 {
735                return Err(AcdpError::SupersededTarget {
736                    reason: acdp_primitives::error::SupersessionReason::VersionMismatch,
737                    message: format!(
738                        "version {} ≠ predecessor.version + 1 ({})",
739                        req.version,
740                        prev_full.body.version + 1
741                    ),
742                });
743            }
744            // FEAT-01 atomicity: the check that previously raced with
745            // another concurrent publish. Now under the same lock as
746            // the insert below — exactly one of two contenders succeeds.
747            if matches!(prev_full.registry_state.status, Status::Superseded) {
748                return Err(AcdpError::SupersededTarget {
749                    reason: acdp_primitives::error::SupersessionReason::AlreadySuperseded,
750                    message: format!("supersedes target '{prev}' has already been superseded"),
751                });
752            }
753
754            // Derive the v1 ctx_id from the predecessor's lineage —
755            // same logic as `first_version_ctx_id`, inlined to stay
756            // under the existing lock.
757            g.lineages
758                .get(prev_full.body.lineage_id.as_str())
759                .and_then(|ids| ids.first().cloned())
760                .map(CtxId)
761        } else {
762            None
763        };
764
765        // ── 3. Identifier assignment ────────────────────────────────
766        let validated = crate::registry::validator::ValidatedPublish {
767            recomputed_hash: req.content_hash.clone(),
768        };
769        let (ctx_id, lineage_id) =
770            assign_identifiers(authority, &req.supersedes, first_v1.as_ref(), &validated)?;
771
772        // ── 4. Build the stored Body ────────────────────────────────
773        // Single materialization point (IMP-02): the constructor copies
774        // every producer field and ms-truncates `created_at`, so this
775        // backend cannot drift from the SQL backends when a producer
776        // field is added.
777        let body =
778            Body::from_publish_request(req, ctx_id.clone(), lineage_id.clone(), authority, now);
779        let created_at = body.created_at;
780
781        // ── 5. Insert (mirrors `put` but inline so we keep the lock) ─
782        let ctx_id_str = body.ctx_id.0.clone();
783        let lineage_id_str = body.lineage_id.0.clone();
784        if g.by_ctx.contains_key(&ctx_id_str) {
785            // UUID collision is astronomically unlikely but we still
786            // surface it as a SchemaViolation rather than silently
787            // overwriting.
788            return Err(AcdpError::SchemaViolation(format!(
789                "ctx_id collision: '{ctx_id_str}' already exists"
790            )));
791        }
792        // Receipt minting (RFC-ACDP-0010) — inside the critical section,
793        // before the insert becomes visible, so a context published
794        // under the receipts profile never exists without its receipt.
795        let registry_receipt = receipt_minter.map(|mint| mint(&body)).transpose()?;
796
797        let stored = FullContext {
798            body,
799            registry_state: RegistryState {
800                status: Status::Active,
801                lifecycle_events: None,
802                extensions: Default::default(),
803            },
804            registry_receipt: registry_receipt.clone(),
805            // Head receipts are ephemeral serve-time attestations —
806            // never persisted; `RegistryServer::current` mints per
807            // response (RFC-ACDP-0011 §6).
808            lineage_head_receipt: None,
809            log_inclusion: None,
810            extensions: Default::default(),
811        };
812        g.by_ctx.insert(ctx_id_str.clone(), stored);
813        g.lineages
814            .entry(lineage_id_str)
815            .or_default()
816            .push(ctx_id_str);
817
818        // ── 6. Mark predecessor superseded ──────────────────────────
819        if let Some(prev) = &req.supersedes {
820            if let Some(prev_ctx) = g.by_ctx.get_mut(prev.as_str()) {
821                prev_ctx.registry_state.status = Status::Superseded;
822            }
823        }
824
825        let response = PublishResponse {
826            ctx_id,
827            lineage_id,
828            version: req.version,
829            created_at,
830            status: Status::Active,
831            registry_receipt,
832        };
833
834        // ── 7. Idempotency record ───────────────────────────────────
835        if let Some(idem) = idempotency {
836            let expires_at = now + idem.ttl;
837            g.idempotency.insert(
838                (req.agent_id.as_str().to_string(), idem.key.to_string()),
839                IdempotencyRecord {
840                    content_hash: req.content_hash.clone(),
841                    response: response.clone(),
842                    expires_at,
843                },
844            );
845        }
846
847        Ok(PublishCommitOutcome::Inserted(response))
848    }
849
850    fn search(
851        &self,
852        params: &SearchParams,
853        requester: Option<&AgentDid>,
854        anonymous_public_reads: bool,
855    ) -> Result<SearchResponse, AcdpError> {
856        let g = self.lock();
857        let now = chrono::Utc::now();
858
859        let q_lower = params.q.as_deref().map(str::to_lowercase);
860        let domain = params.domain.as_deref();
861        let agent = params.agent_id.as_deref();
862        let context_type = params.context_type.as_deref();
863        let derived_from = params.derived_from.as_deref();
864        let schema_uri = params.schema_uri.as_deref();
865        let tags: Option<Vec<&str>> = params.tags.as_deref().map(|s| {
866            s.split(',')
867                .map(str::trim)
868                .filter(|t| !t.is_empty())
869                .collect()
870        });
871
872        // BUG-10: parse date-time filter params at the boundary so the
873        // hot loop just compares DateTime<Utc> values.
874        let created_after = parse_opt_rfc3339(&params.created_after)?;
875        let created_before = parse_opt_rfc3339(&params.created_before)?;
876        let dp_start_after = parse_opt_rfc3339(&params.data_period_start_after)?;
877        let dp_end_before = parse_opt_rfc3339(&params.data_period_end_before)?;
878        let expires_after = parse_opt_rfc3339(&params.expires_after)?;
879        let expires_before = parse_opt_rfc3339(&params.expires_before)?;
880
881        let mut matches: Vec<&FullContext> = g
882            .by_ctx
883            .values()
884            .filter(|ctx| {
885                let body = &ctx.body;
886
887                // RFC-ACDP-0008 §4.5 search-disclosure gate (note the
888                // private/restricted asymmetry: private contexts surface
889                // in search only to their producer).
890                if !can_surface_in_search(body, requester, anonymous_public_reads) {
891                    return false;
892                }
893
894                if let Some(q) = &q_lower {
895                    let haystack = format!(
896                        "{} {} {} {} {} {}",
897                        body.title,
898                        body.description.as_deref().unwrap_or(""),
899                        body.summary.as_deref().unwrap_or(""),
900                        body.domain.as_deref().unwrap_or(""),
901                        body.agent_id.as_str(),
902                        body.tags.as_ref().map(|t| t.join(" ")).unwrap_or_default(),
903                    )
904                    .to_lowercase();
905                    if !haystack.contains(q) {
906                        return false;
907                    }
908                }
909                if let Some(d) = domain {
910                    if body.domain.as_deref() != Some(d) {
911                        return false;
912                    }
913                }
914                if let Some(a) = agent {
915                    if body.agent_id.as_str() != a {
916                        return false;
917                    }
918                }
919                if let Some(t) = context_type {
920                    let body_type = serde_json::to_value(&body.context_type)
921                        .ok()
922                        .and_then(|v| v.as_str().map(str::to_string))
923                        .unwrap_or_default();
924                    if body_type != t {
925                        return false;
926                    }
927                }
928                if let Some(df) = derived_from {
929                    if !body.derived_from.iter().any(|c| c.as_str() == df) {
930                        return false;
931                    }
932                }
933                if let Some(req_tags) = &tags {
934                    let body_tags = body.tags.as_deref().unwrap_or(&[]);
935                    if !req_tags.iter().all(|t| body_tags.iter().any(|bt| bt == t)) {
936                        return false;
937                    }
938                }
939                if let Some(uri) = schema_uri {
940                    if body.schema_uri.as_deref() != Some(uri) {
941                        return false;
942                    }
943                }
944                if let Some(after) = created_after {
945                    if body.created_at < after {
946                        return false;
947                    }
948                }
949                if let Some(before) = created_before {
950                    if body.created_at > before {
951                        return false;
952                    }
953                }
954                if let Some(after) = dp_start_after {
955                    match &body.data_period {
956                        Some(p) if p.start >= after => {}
957                        _ => return false,
958                    }
959                }
960                if let Some(before) = dp_end_before {
961                    match &body.data_period {
962                        Some(p) if p.end <= before => {}
963                        _ => return false,
964                    }
965                }
966                if let Some(after) = expires_after {
967                    match body.expires_at {
968                        Some(e) if e >= after => {}
969                        _ => return false,
970                    }
971                }
972                if let Some(before) = expires_before {
973                    match body.expires_at {
974                        Some(e) if e <= before => {}
975                        _ => return false,
976                    }
977                }
978                // Status filter — registry default is `active`. Compare
979                // against PROJECTED status so a stored-Active body whose
980                // expires_at has passed is filtered out (RFC-ACDP-0004 §4)
981                // and a retracted context falls out of default searches —
982                // and out of status=superseded / status=expired even where
983                // those facts also hold (RFC-ACDP-0013 §8.2: the §7.2
984                // precedence applies to the filter).
985                let want_status = params.status.as_deref().unwrap_or("active");
986                let effective = project_status(&ctx.registry_state, body, now);
987                if effective.as_str() != want_status {
988                    return false;
989                }
990                true
991            })
992            .collect();
993
994        // Newest first; IMP-03 — fall back to ctx_id for a deterministic
995        // total order when many contexts share a millisecond.
996        matches.sort_by(|a, b| {
997            b.body
998                .created_at
999                .cmp(&a.body.created_at)
1000                .then_with(|| a.body.ctx_id.as_str().cmp(b.body.ctx_id.as_str()))
1001        });
1002
1003        // BUG-08: capture `total_estimate` BEFORE cursor filtering so
1004        // it represents the total count across all pages (RFC-ACDP-0005
1005        // §3 — clients use this for "page 1 of N" UIs). If we captured
1006        // it after `retain`, page 2 would show "80 matches" for a
1007        // 100-item search, page 3 "60", and so on.
1008        let total_estimate = Some(matches.len() as u64);
1009
1010        // BUG-10 cursor: opaque base64 of "<created_at_ms>:<ctx_id>".
1011        // ≥1h validity is implicit — cursors do not embed a timestamp,
1012        // so they remain valid until the underlying context is deleted.
1013        let cursor_anchor = params
1014            .cursor
1015            .as_deref()
1016            .map(decode_cursor)
1017            .transpose()?
1018            .flatten();
1019        if let Some((anchor_ms, anchor_id)) = &cursor_anchor {
1020            matches.retain(|c| {
1021                let ms = c.body.created_at.timestamp_millis();
1022                ms < *anchor_ms || (ms == *anchor_ms && c.body.ctx_id.as_str() > anchor_id.as_str())
1023            });
1024        }
1025
1026        // Clamp into [1, 100]: `limit` is attacker-controlled and never
1027        // lower-bounded. `limit=0` with ≥1 match would compute `limit - 1`
1028        // below → debug-build subtraction panic (request-thread DoS) /
1029        // release-build wrap to usize::MAX → broken pagination.
1030        let limit = params.limit.unwrap_or(50).clamp(1, 100) as usize;
1031        let next_cursor = if matches.len() > limit {
1032            matches.get(limit - 1).map(|c| {
1033                encode_cursor(c.body.created_at.timestamp_millis(), c.body.ctx_id.as_str())
1034            })
1035        } else {
1036            None
1037        };
1038
1039        let projected: Vec<SearchResult> = matches
1040            .iter()
1041            .take(limit)
1042            .map(|ctx| SearchResult {
1043                ctx_id: ctx.body.ctx_id.clone(),
1044                lineage_id: ctx.body.lineage_id.clone(),
1045                agent_id: ctx.body.agent_id.clone(),
1046                title: ctx.body.title.clone(),
1047                summary: ctx.body.summary.clone(),
1048                context_type: ctx.body.context_type.clone(),
1049                domain: ctx.body.domain.clone(),
1050                created_at: ctx.body.created_at,
1051                status: project_status(&ctx.registry_state, &ctx.body, now),
1052                // RFC-ACDP-0008 §4.5: only disclose visibility when the
1053                // requester is authorized for it. Public is always safe.
1054                // For restricted/private, the search filter above guarantees
1055                // the requester is producer-or-audience, so it's safe to
1056                // surface the label.
1057                visibility: Some(ctx.body.visibility.clone()),
1058            })
1059            .collect();
1060
1061        Ok(SearchResponse {
1062            matches: projected,
1063            total_estimate,
1064            next_cursor,
1065        })
1066    }
1067}
1068
1069/// Parse an optional RFC 3339 string parameter; surface a
1070/// [`AcdpError::SchemaViolation`] on malformed input.
1071fn parse_opt_rfc3339(
1072    s: &Option<String>,
1073) -> Result<Option<chrono::DateTime<chrono::Utc>>, AcdpError> {
1074    let Some(raw) = s.as_deref() else {
1075        return Ok(None);
1076    };
1077    let dt = chrono::DateTime::parse_from_rfc3339(raw)
1078        .map_err(|e| AcdpError::SchemaViolation(format!("malformed datetime '{raw}': {e}")))?;
1079    Ok(Some(dt.with_timezone(&chrono::Utc)))
1080}
1081
1082/// Cursor TTL — clients SHOULD re-fetch after this window.
1083/// RFC-ACDP-0005 §3 leaves the exact value to implementations; 1 hour
1084/// matches the common "≥1h" cursor-validity expectation.
1085const CURSOR_TTL: chrono::Duration = chrono::Duration::seconds(3600);
1086
1087/// Opaque cursor encoding — base64 of
1088/// `<mint_unix_ms>:<created_at_millis>:<ctx_id>`.
1089///
1090/// The `mint_unix_ms` prefix lets [`decode_cursor`] enforce the
1091/// `CURSOR_TTL` window and surface `AcdpError::CursorExpired` rather
1092/// than silently accepting an ancient cursor (FEAT-04). Plain
1093/// `STANDARD` engine so cursors are stable across machines.
1094fn encode_cursor(created_at_ms: i64, ctx_id: &str) -> String {
1095    use base64::{engine::general_purpose::STANDARD, Engine};
1096    let mint_ms = chrono::Utc::now().timestamp_millis();
1097    STANDARD.encode(format!("{mint_ms}:{created_at_ms}:{ctx_id}"))
1098}
1099
1100fn decode_cursor(s: &str) -> Result<Option<(i64, String)>, AcdpError> {
1101    use base64::{engine::general_purpose::STANDARD, Engine};
1102    let bytes = STANDARD
1103        .decode(s)
1104        .map_err(|_| AcdpError::InvalidCursor("cursor is not valid base64".into()))?;
1105    let decoded = String::from_utf8(bytes)
1106        .map_err(|_| AcdpError::InvalidCursor("cursor is not utf-8".into()))?;
1107    // Format: "<mint_ms>:<anchor_ms>:<ctx_id>". The mint timestamp
1108    // prefix is FEAT-04 expiry tracking.
1109    let mut parts = decoded.splitn(3, ':');
1110    let mint_str = parts
1111        .next()
1112        .ok_or_else(|| AcdpError::InvalidCursor("cursor missing mint timestamp".into()))?;
1113    let anchor_str = parts
1114        .next()
1115        .ok_or_else(|| AcdpError::InvalidCursor("cursor missing anchor timestamp".into()))?;
1116    let ctx_id = parts
1117        .next()
1118        .ok_or_else(|| AcdpError::InvalidCursor("cursor missing ctx_id".into()))?;
1119    let mint_ms: i64 = mint_str
1120        .parse()
1121        .map_err(|_| AcdpError::InvalidCursor("cursor mint millis is not an integer".into()))?;
1122    let anchor_ms: i64 = anchor_str
1123        .parse()
1124        .map_err(|_| AcdpError::InvalidCursor("cursor anchor millis is not an integer".into()))?;
1125
1126    // FEAT-04: reject cursors older than CURSOR_TTL with the
1127    // dedicated `cursor_expired` wire code so clients can distinguish
1128    // "you typo'd the cursor" (InvalidCursor) from "your cursor aged
1129    // out, restart the scan from page 1" (CursorExpired).
1130    let now = chrono::Utc::now().timestamp_millis();
1131    let age_ms = now.saturating_sub(mint_ms);
1132    if age_ms > CURSOR_TTL.num_milliseconds() {
1133        // CursorExpired is a unit variant in the wire-error mapping;
1134        // the diagnostic ("aged Xms ago") is intentionally surfaced
1135        // via Display rather than a payload so it round-trips through
1136        // `AcdpError::from_wire_error`.
1137        return Err(AcdpError::CursorExpired);
1138    }
1139    Ok(Some((anchor_ms, ctx_id.to_string())))
1140}
1141
1142#[cfg(test)]
1143mod tests {
1144    use super::*;
1145    use acdp_crypto::SigningKey;
1146    use acdp_producer::Producer;
1147    use acdp_types::body::{DataPeriod, Signature};
1148    use acdp_types::primitives::{AgentDid, ContentHash, ContextType, Visibility};
1149    use chrono::Utc;
1150
1151    fn fake_body(ctx_id: &str, lineage_id: &str, title: &str) -> Body {
1152        Body {
1153            ctx_id: CtxId(ctx_id.into()),
1154            lineage_id: LineageId(lineage_id.into()),
1155            origin_registry: "registry.example.com".into(),
1156            created_at: Utc::now(),
1157            content_hash: ContentHash("sha256:0".into()),
1158            signature: Signature {
1159                algorithm: "ed25519".into(),
1160                key_id: "did:web:agents.example.com:test#key-1".into(),
1161                value: "A".repeat(88),
1162            },
1163            version: 1,
1164            supersedes: None,
1165            agent_id: AgentDid::new("did:web:agents.example.com:test"),
1166            contributors: vec![],
1167            title: title.into(),
1168            context_type: ContextType::DataSnapshot,
1169            data_refs: vec![],
1170            derived_from: vec![],
1171            visibility: Visibility::Public,
1172            audience: None,
1173            acdp_version: None,
1174            description: None,
1175            summary: None,
1176            tags: None,
1177            domain: None,
1178            expires_at: None,
1179            data_period: None,
1180            metadata: None,
1181            schema_uri: None,
1182            extensions: Default::default(),
1183        }
1184    }
1185
1186    #[test]
1187    fn put_get_round_trip() {
1188        let s = InMemoryStore::new();
1189        let id = "acdp://r/12345678-1234-4321-8123-123456781234";
1190        let lin = "lin:sha256:1111111111111111111111111111111111111111111111111111111111111111";
1191        s.put(fake_body(id, lin, "A")).unwrap();
1192        let got = s.get(&CtxId(id.into())).unwrap().unwrap();
1193        assert_eq!(got.body.title, "A");
1194        assert!(matches!(got.registry_state.status, Status::Active));
1195    }
1196
1197    #[test]
1198    fn lineage_orders_by_publish_order() {
1199        let s = InMemoryStore::new();
1200        let lin = "lin:sha256:2222222222222222222222222222222222222222222222222222222222222222";
1201        let v1 = "acdp://r/12345678-1234-4321-8123-000000000001";
1202        let v2 = "acdp://r/12345678-1234-4321-8123-000000000002";
1203        s.put(fake_body(v1, lin, "v1")).unwrap();
1204        s.put(fake_body(v2, lin, "v2")).unwrap();
1205        let lineage = s.lineage(&LineageId(lin.into())).unwrap();
1206        assert_eq!(lineage.len(), 2);
1207        assert_eq!(lineage[0].body.title, "v1");
1208        assert_eq!(lineage[1].body.title, "v2");
1209    }
1210
1211    #[test]
1212    fn supersession_marks_predecessor() {
1213        let s = InMemoryStore::new();
1214        let lin = "lin:sha256:3333333333333333333333333333333333333333333333333333333333333333";
1215        let v1 = "acdp://r/12345678-1234-4321-8123-000000000003";
1216        s.put(fake_body(v1, lin, "v1")).unwrap();
1217        s.mark_superseded(&CtxId(v1.into())).unwrap();
1218        let got = s.get(&CtxId(v1.into())).unwrap().unwrap();
1219        assert!(matches!(got.registry_state.status, Status::Superseded));
1220    }
1221
1222    // BUG-11 — Status::Expired derived from body.expires_at at read time.
1223
1224    fn expired_body(
1225        ctx_id: &str,
1226        lineage_id: &str,
1227        title: &str,
1228        expires_at: chrono::DateTime<chrono::Utc>,
1229    ) -> Body {
1230        let mut b = fake_body(ctx_id, lineage_id, title);
1231        b.expires_at = Some(expires_at);
1232        b
1233    }
1234
1235    #[test]
1236    fn get_projects_active_to_expired_when_past_expires_at() {
1237        use chrono::Duration;
1238        let s = InMemoryStore::new();
1239        let lin = "lin:sha256:5555555555555555555555555555555555555555555555555555555555555555";
1240        let id = "acdp://r/12345678-1234-4321-8123-000000000006";
1241        s.put(expired_body(
1242            id,
1243            lin,
1244            "old",
1245            chrono::Utc::now() - Duration::hours(1),
1246        ))
1247        .unwrap();
1248        let got = s.get(&CtxId(id.into())).unwrap().unwrap();
1249        assert!(
1250            matches!(got.registry_state.status, Status::Expired),
1251            "expected Status::Expired projection, got {:?}",
1252            got.registry_state.status
1253        );
1254    }
1255
1256    #[test]
1257    fn get_keeps_active_when_expires_at_in_future() {
1258        use chrono::Duration;
1259        let s = InMemoryStore::new();
1260        let lin = "lin:sha256:6666666666666666666666666666666666666666666666666666666666666666";
1261        let id = "acdp://r/12345678-1234-4321-8123-000000000007";
1262        s.put(expired_body(
1263            id,
1264            lin,
1265            "fresh",
1266            chrono::Utc::now() + Duration::hours(1),
1267        ))
1268        .unwrap();
1269        let got = s.get(&CtxId(id.into())).unwrap().unwrap();
1270        assert!(matches!(got.registry_state.status, Status::Active));
1271    }
1272
1273    #[test]
1274    fn search_status_active_filters_out_expired() {
1275        use chrono::Duration;
1276        let s = InMemoryStore::new();
1277        let lin = "lin:sha256:7777777777777777777777777777777777777777777777777777777777777777";
1278        let id = "acdp://r/12345678-1234-4321-8123-000000000008";
1279        s.put(expired_body(
1280            id,
1281            lin,
1282            "old",
1283            chrono::Utc::now() - Duration::hours(1),
1284        ))
1285        .unwrap();
1286        let resp = s.search(&SearchParams::default(), None, true).unwrap();
1287        assert!(
1288            resp.matches.is_empty(),
1289            "expired must not surface under status=active default"
1290        );
1291        // Asking for `expired` SHOULD surface it.
1292        let resp = s
1293            .search(
1294                &SearchParams {
1295                    status: Some("expired".into()),
1296                    ..Default::default()
1297                },
1298                None,
1299                true,
1300            )
1301            .unwrap();
1302        assert_eq!(resp.matches.len(), 1);
1303    }
1304
1305    /// BUG-10 — date/time filter is honored.
1306    #[test]
1307    fn search_filters_by_created_after() {
1308        let s = InMemoryStore::new();
1309        let lin = "lin:sha256:8888888888888888888888888888888888888888888888888888888888888888";
1310        let mut body = fake_body(
1311            "acdp://r/12345678-1234-4321-8123-000000000009",
1312            lin,
1313            "match",
1314        );
1315        body.created_at = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00.000Z")
1316            .unwrap()
1317            .with_timezone(&chrono::Utc);
1318        s.put(body).unwrap();
1319        // `created_after` AFTER body.created_at → 0 matches
1320        let resp = s
1321            .search(
1322                &SearchParams {
1323                    created_after: Some("2026-02-01T00:00:00.000Z".into()),
1324                    ..Default::default()
1325                },
1326                None,
1327                true,
1328            )
1329            .unwrap();
1330        assert_eq!(resp.matches.len(), 0);
1331        // `created_after` BEFORE body.created_at → 1 match
1332        let resp = s
1333            .search(
1334                &SearchParams {
1335                    created_after: Some("2025-12-01T00:00:00.000Z".into()),
1336                    ..Default::default()
1337                },
1338                None,
1339                true,
1340            )
1341            .unwrap();
1342        assert_eq!(resp.matches.len(), 1);
1343    }
1344
1345    #[test]
1346    fn search_invalid_rfc3339_filter_rejected() {
1347        let s = InMemoryStore::new();
1348        let err = s
1349            .search(
1350                &SearchParams {
1351                    created_after: Some("not-a-date".into()),
1352                    ..Default::default()
1353                },
1354                None,
1355                true,
1356            )
1357            .unwrap_err();
1358        assert!(matches!(err, AcdpError::SchemaViolation(_)));
1359    }
1360
1361    /// BUG-10 cursor round-trips and pages correctly.
1362    #[test]
1363    fn search_cursor_pages_results() {
1364        let s = InMemoryStore::new();
1365        let lin = "lin:sha256:9999999999999999999999999999999999999999999999999999999999999999";
1366        // Insert 5 contexts with distinct created_at so order is deterministic.
1367        let base = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00.000Z")
1368            .unwrap()
1369            .with_timezone(&chrono::Utc);
1370        for i in 0..5u8 {
1371            let mut body = fake_body(
1372                &format!("acdp://r/12345678-1234-4321-8123-00000000010{i}"),
1373                lin,
1374                "match",
1375            );
1376            body.created_at = base + chrono::Duration::minutes(i as i64);
1377            s.put(body).unwrap();
1378        }
1379        let p1 = s
1380            .search(
1381                &SearchParams {
1382                    limit: Some(2),
1383                    ..Default::default()
1384                },
1385                None,
1386                true,
1387            )
1388            .unwrap();
1389        assert_eq!(p1.matches.len(), 2);
1390        let cursor = p1.next_cursor.expect("page 1 should carry a cursor");
1391        let p2 = s
1392            .search(
1393                &SearchParams {
1394                    limit: Some(2),
1395                    cursor: Some(cursor.clone()),
1396                    ..Default::default()
1397                },
1398                None,
1399                true,
1400            )
1401            .unwrap();
1402        assert_eq!(p2.matches.len(), 2);
1403        // No overlap between page 1 and page 2.
1404        for r in &p2.matches {
1405            assert!(
1406                !p1.matches.iter().any(|q| q.ctx_id == r.ctx_id),
1407                "page 2 overlapped page 1"
1408            );
1409        }
1410        // BUG-08: total_estimate MUST be stable across pages — captured
1411        // BEFORE cursor filtering. Before the fix, page 2 reported a
1412        // smaller total than page 1 (the remaining-from-cursor count).
1413        assert_eq!(
1414            p1.total_estimate, p2.total_estimate,
1415            "total_estimate MUST be stable across pages (BUG-08); \
1416             p1={:?}, p2={:?}",
1417            p1.total_estimate, p2.total_estimate
1418        );
1419        assert_eq!(
1420            p1.total_estimate,
1421            Some(5),
1422            "total_estimate MUST reflect total matches across all pages, got {:?}",
1423            p1.total_estimate
1424        );
1425    }
1426
1427    #[test]
1428    fn search_limit_zero_does_not_underflow() {
1429        // P1-1: limit=0 with ≥1 match previously computed `limit - 1`
1430        // (debug panic / release wrap). It MUST be clamped to ≥1.
1431        let s = InMemoryStore::new();
1432        let lin = "lin:sha256:8888888888888888888888888888888888888888888888888888888888888888";
1433        for i in 0..3u8 {
1434            let body = fake_body(
1435                &format!("acdp://r/12345678-1234-4321-8123-00000000020{i}"),
1436                lin,
1437                "match",
1438            );
1439            s.put(body).unwrap();
1440        }
1441        let page = s
1442            .search(
1443                &SearchParams {
1444                    limit: Some(0),
1445                    ..Default::default()
1446                },
1447                None,
1448                true,
1449            )
1450            .expect("limit=0 must not panic or error");
1451        // Clamped to 1: one result, and a cursor since more remain.
1452        assert_eq!(page.matches.len(), 1);
1453        assert!(page.next_cursor.is_some());
1454    }
1455
1456    #[test]
1457    fn search_malformed_cursor_rejected() {
1458        let s = InMemoryStore::new();
1459        let err = s
1460            .search(
1461                &SearchParams {
1462                    cursor: Some("not_base64!@#".into()),
1463                    ..Default::default()
1464                },
1465                None,
1466                true,
1467            )
1468            .unwrap_err();
1469        assert!(matches!(err, AcdpError::InvalidCursor(_)));
1470    }
1471
1472    /// FEAT-04: a cursor whose embedded mint timestamp is older than
1473    /// `CURSOR_TTL` MUST surface as `CursorExpired`, not `InvalidCursor`.
1474    /// Clients distinguish "you typo'd the cursor" from "your cursor
1475    /// aged out, restart the scan from page 1".
1476    #[test]
1477    fn search_aged_cursor_rejected_as_cursor_expired() {
1478        use base64::{engine::general_purpose::STANDARD, Engine};
1479        let s = InMemoryStore::new();
1480        // Mint a cursor 7200s in the past — twice the 3600s TTL.
1481        let stale_mint_ms = chrono::Utc::now().timestamp_millis() - 7200 * 1000;
1482        let aged = STANDARD.encode(format!(
1483            "{stale_mint_ms}:0:acdp://r/12345678-1234-4321-8123-1234567812aa"
1484        ));
1485        let err = s
1486            .search(
1487                &SearchParams {
1488                    cursor: Some(aged),
1489                    ..Default::default()
1490                },
1491                None,
1492                true,
1493            )
1494            .unwrap_err();
1495        assert!(
1496            matches!(err, AcdpError::CursorExpired),
1497            "expired cursor MUST surface CursorExpired, got {err:?}"
1498        );
1499    }
1500
1501    #[test]
1502    fn search_filters_by_status_default_active() {
1503        let s = InMemoryStore::new();
1504        let lin = "lin:sha256:4444444444444444444444444444444444444444444444444444444444444444";
1505        let v1 = "acdp://r/12345678-1234-4321-8123-000000000004";
1506        let v2 = "acdp://r/12345678-1234-4321-8123-000000000005";
1507        s.put(fake_body(v1, lin, "old")).unwrap();
1508        s.put(fake_body(v2, lin, "new")).unwrap();
1509        s.mark_superseded(&CtxId(v1.into())).unwrap();
1510        let resp = s
1511            .search(
1512                &SearchParams {
1513                    q: Some("old".into()),
1514                    ..Default::default()
1515                },
1516                None,
1517                true,
1518            )
1519            .unwrap();
1520        // Only `active` matches — superseded "old" filtered out.
1521        assert_eq!(resp.matches.len(), 0);
1522        let resp = s
1523            .search(
1524                &SearchParams {
1525                    q: Some("new".into()),
1526                    ..Default::default()
1527                },
1528                None,
1529                true,
1530            )
1531            .unwrap();
1532        assert_eq!(resp.matches.len(), 1);
1533    }
1534
1535    /// End-to-end: producer → server pipeline using the actual signing
1536    /// path. Uses a builder and the `RegistryServer` (see server.rs)
1537    /// to confirm the integration story.
1538    #[test]
1539    fn store_round_trip_from_real_publish_request() {
1540        use crate::registry::server::RegistryServer;
1541        use acdp_types::capabilities::{CapabilitiesDocument, Limits};
1542
1543        let key = SigningKey::from_bytes(&[7u8; 32]);
1544        let p = Producer::new(
1545            key,
1546            AgentDid::new("did:web:agents.example.com:test"),
1547            "did:web:agents.example.com:test#key-1",
1548        );
1549        let req = p
1550            .publish_request()
1551            .title("hello")
1552            .context_type(ContextType::DataSnapshot)
1553            .visibility(Visibility::Public)
1554            .build()
1555            .unwrap();
1556
1557        let caps = CapabilitiesDocument {
1558            acdp_version: "0.1.0".into(),
1559            registry_did: "did:web:registry.example.com".into(),
1560            supported_signature_algorithms: vec!["ed25519".into()],
1561            supported_did_methods: vec!["did:web".into()],
1562            profiles: vec!["acdp-registry-core".into()],
1563            limits: Limits {
1564                max_payload_bytes: 1_048_576,
1565                max_embedded_bytes: 65_536,
1566                idempotency_key_ttl_seconds: None,
1567                max_publish_per_minute: None,
1568            },
1569            read_authentication_methods: vec![],
1570            anonymous_public_reads: true,
1571            supports_idempotency_key: false,
1572            extensions: Default::default(),
1573        };
1574
1575        let server = RegistryServer::new(InMemoryStore::new(), caps, "registry.example.com");
1576        let resp = server.publish_unverified_for_tests(&req).unwrap();
1577        assert_eq!(resp.version, 1);
1578        let ctx = server.retrieve(&resp.ctx_id, None).unwrap().unwrap();
1579        assert_eq!(ctx.body.title, "hello");
1580
1581        // Ignore unused imports under different feature combinations
1582        let _: Option<DataPeriod> = ctx.body.data_period.clone();
1583    }
1584}