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    /// RFC-ACDP-0014 §4 `supersedes`-row admission hook (key-revocation
294    /// lineages). `Some` iff the registry's RFC-0014 version gate is on
295    /// (`key_revocation_gate_applies`) **and** `req.supersedes` is set;
296    /// otherwise `None`.
297    ///
298    /// Stores MUST invoke it with the predecessor's stored [`Body`],
299    /// inside the same critical section / transaction as their own
300    /// supersession checks, and only **after** producer-continuity and
301    /// tenant scoping have already passed — never before. Calling it
302    /// earlier turns the check into a cross-tenant, non-owner
303    /// existence-and-type oracle: the predecessor's presence and
304    /// `context_type` would leak to a caller who does not own it and is
305    /// not scoped to its tenant. `Err` from the closure MUST abort the
306    /// commit — no insert, no supersession side effect. A store that
307    /// silently ignores a `Some` hook fails to enforce an RFC-ACDP-0014
308    /// §4 MUST.
309    #[allow(clippy::type_complexity)]
310    pub predecessor_admission: Option<&'a (dyn Fn(&Body) -> Result<(), AcdpError> + Send + Sync)>,
311}
312
313/// Idempotency parameters threaded through [`PublishCommit`].
314pub struct PendingIdempotencyCommit<'a> {
315    /// The key the producer supplied in the `Idempotency-Key` header.
316    pub key: &'a str,
317    /// TTL after which the idempotency record may be evicted (typically
318    /// `caps.limits.idempotency_key_ttl_seconds`).
319    pub ttl: chrono::Duration,
320}
321
322/// Outcome of an atomic [`RegistryStore::commit_publish`].
323#[derive(Debug)]
324pub enum PublishCommitOutcome {
325    /// Fresh publish — the body was newly persisted and the response
326    /// describes the just-assigned identifiers.
327    Inserted(PublishResponse),
328    /// `(agent_id, idempotency_key)` had a prior record with the same
329    /// `content_hash` — return the original response per idem-002.
330    IdempotentReplay(PublishResponse),
331}
332
333impl PublishCommitOutcome {
334    /// The response either way, discarding the insert/replay distinction.
335    ///
336    /// This is what every `publish_*` entry point that predates
337    /// [`crate::registry::server::RegistryServer::publish_verified_in_tenant_with_outcome`]
338    /// returns,
339    /// and the reason the distinction was invisible to callers: a registry
340    /// front-end answering `POST /contexts` needs it to choose between
341    /// `201 Created` + `Location` on a fresh publish and `200 OK` on an
342    /// idempotent replay (RFC-ACDP-0003 idem-002, which requires 200 and
343    /// explicitly NOT 201). Prefer the `*_with_outcome` entry points when
344    /// that choice is yours to make.
345    pub fn into_response(self) -> PublishResponse {
346        match self {
347            Self::Inserted(r) | Self::IdempotentReplay(r) => r,
348        }
349    }
350
351    /// Borrow the response without consuming the outcome.
352    pub fn response(&self) -> &PublishResponse {
353        match self {
354            Self::Inserted(r) | Self::IdempotentReplay(r) => r,
355        }
356    }
357
358    /// `true` when this publish was served from a prior record rather than
359    /// newly persisted — i.e. the caller must answer `200`, not `201`.
360    pub fn is_replay(&self) -> bool {
361        matches!(self, Self::IdempotentReplay(_))
362    }
363}
364
365/// Cached publish response keyed by `(agent_id, idempotency_key)`
366/// (RFC-ACDP-0003 §6).
367#[derive(Debug, Clone)]
368pub struct IdempotencyRecord {
369    /// The original request's `content_hash`. A retry with the same key
370    /// but a different hash MUST be rejected as `duplicate_publish`.
371    pub content_hash: acdp_types::primitives::ContentHash,
372    /// The response the registry returned on the first acceptance.
373    pub response: acdp_types::publish::PublishResponse,
374    /// Eviction time (TTL window from caps.limits.idempotency_key_ttl_seconds).
375    pub expires_at: chrono::DateTime<chrono::Utc>,
376}
377
378// ── In-memory reference implementation ───────────────────────────────────────
379
380/// Minimal in-memory backend. Not durable; intended for tests and
381/// prototyping. Concurrency-safe (a single `Mutex` over the table).
382#[derive(Default)]
383pub struct InMemoryStore {
384    inner: Mutex<Inner>,
385}
386
387#[derive(Default)]
388struct Inner {
389    /// All contexts keyed by `ctx_id`. Insertion-ordered per lineage
390    /// thanks to the parallel `lineages` index.
391    by_ctx: std::collections::BTreeMap<String, FullContext>,
392    /// `lineage_id -> [ctx_id, ctx_id, ...]` in publish order.
393    lineages: std::collections::BTreeMap<String, Vec<String>>,
394    /// `(agent_did, idempotency_key) -> record` (RFC-ACDP-0003 §6).
395    idempotency: std::collections::HashMap<(String, String), IdempotencyRecord>,
396}
397
398impl InMemoryStore {
399    /// Construct an empty store.
400    pub fn new() -> Self {
401        Self::default()
402    }
403
404    fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
405        self.inner.lock().expect("InMemoryStore mutex poisoned")
406    }
407}
408
409/// RFC-ACDP-0004 §4 (as amended by RFC-ACDP-0013 §7.2) — derive the
410/// served `status` at read time from the stored state, the lifecycle
411/// event history, and the clock, so a registry that does not run a
412/// janitor still surfaces the correct lifecycle status.
413///
414/// Precedence: `retracted` > `superseded` > `expired` > `active`.
415/// Retraction state is derived from `lifecycle_events` (§7.1) and
416/// dominates everything — including a stored `Superseded` and a lapsed
417/// `expires_at`; republication removes the retraction from the
418/// derivation (not the history) and the status re-derives as though
419/// never retracted.
420pub(crate) fn project_status(
421    state: &RegistryState,
422    body: &Body,
423    now: chrono::DateTime<chrono::Utc>,
424) -> Status {
425    if state.is_retracted() {
426        return Status::Retracted;
427    }
428    match &state.status {
429        Status::Active => match body.expires_at {
430            Some(exp) if exp <= now => Status::Expired,
431            _ => Status::Active,
432        },
433        other => other.clone(),
434    }
435}
436
437/// Materialize the effective view of a stored context: applies
438/// [`project_status`] to override the stored status when retracted or
439/// expired.
440pub(crate) fn project_context(
441    mut ctx: FullContext,
442    now: chrono::DateTime<chrono::Utc>,
443) -> FullContext {
444    ctx.registry_state.status = project_status(&ctx.registry_state, &ctx.body, now);
445    ctx
446}
447
448/// RFC-ACDP-0008 §4.5 search-disclosure rule.
449///
450/// Note the asymmetry vs retrieval: a `Private` context surfaces in search
451/// **only** to its producer — audience members must already know the
452/// `ctx_id` to fetch it. `Restricted` surfaces to producer + audience.
453///
454/// `anonymous_public_reads` mirrors the capability advertisement
455/// (RFC-ACDP-0008 §4.5): a registry that does NOT permit anonymous
456/// public reads MUST suppress public contexts for unauthenticated
457/// callers in both `retrieve` and `search`. The retrieval helper
458/// already consults this flag; this function pulls it through to the
459/// store-side search path (BUG-02).
460fn can_surface_in_search(
461    body: &Body,
462    requester: Option<&AgentDid>,
463    anonymous_public_reads: bool,
464) -> bool {
465    match body.visibility {
466        Visibility::Public => anonymous_public_reads || requester.is_some(),
467        Visibility::Restricted => match requester {
468            None => false,
469            Some(r) => {
470                r == &body.agent_id
471                    || body
472                        .audience
473                        .as_deref()
474                        .is_some_and(|a| a.iter().any(|d| d == r))
475            }
476        },
477        Visibility::Private => requester == Some(&body.agent_id),
478    }
479}
480
481impl RegistryStore for InMemoryStore {
482    fn put(&self, body: Body) -> Result<(), AcdpError> {
483        let ctx_id = body.ctx_id.0.clone();
484        let lineage_id = body.lineage_id.0.clone();
485        let ctx = FullContext {
486            body,
487            registry_state: RegistryState {
488                status: Status::Active,
489                lifecycle_events: None,
490                extensions: Default::default(),
491            },
492            registry_receipt: None,
493            lineage_head_receipt: None,
494            log_inclusion: None,
495            extensions: Default::default(),
496        };
497        let mut g = self.lock();
498        if g.by_ctx.contains_key(&ctx_id) {
499            return Err(AcdpError::SchemaViolation(format!(
500                "duplicate ctx_id '{ctx_id}' in store"
501            )));
502        }
503        g.by_ctx.insert(ctx_id.clone(), ctx);
504        g.lineages.entry(lineage_id).or_default().push(ctx_id);
505        Ok(())
506    }
507
508    fn get(&self, ctx_id: &CtxId) -> Result<Option<FullContext>, AcdpError> {
509        let now = chrono::Utc::now();
510        Ok(self
511            .lock()
512            .by_ctx
513            .get(ctx_id.as_str())
514            .cloned()
515            .map(|c| project_context(c, now)))
516    }
517
518    fn lineage(&self, lineage_id: &LineageId) -> Result<Vec<FullContext>, AcdpError> {
519        let now = chrono::Utc::now();
520        let g = self.lock();
521        let Some(ids) = g.lineages.get(lineage_id.as_str()) else {
522            return Ok(Vec::new());
523        };
524        Ok(ids
525            .iter()
526            .filter_map(|id| g.by_ctx.get(id).cloned().map(|c| project_context(c, now)))
527            .collect())
528    }
529
530    fn current(&self, lineage_id: &LineageId) -> Result<Option<FullContext>, AcdpError> {
531        let now = chrono::Utc::now();
532        let g = self.lock();
533        let Some(ids) = g.lineages.get(lineage_id.as_str()) else {
534            return Ok(None);
535        };
536        // RFC-ACDP-0004 §5: "Returns the unique version that has no
537        // successor. If no such version exists, returns not_found."
538        // Walk newest-to-oldest and return the first version that is
539        // neither `Superseded` nor `Retracted`. Both `Active` and
540        // `Expired` count — an expired body that hasn't been replaced
541        // is still the latest, and the consumer needs to see it (with
542        // status=Expired) to know it has lapsed. A retracted version is
543        // NEVER a head (RFC-ACDP-0013 §8.3): it has been explicitly
544        // withdrawn from reliance, and falling back to a superseded
545        // predecessor would silently serve a replaced context — so
546        // retracting a linear lineage's head yields `None` (fixture
547        // `lc-003`).
548        //
549        // BUG-04: an earlier fallback returned the last entry even when
550        // every version was `Superseded`; that's a protocol violation.
551        // Now we return `None` instead.
552        for id in ids.iter().rev() {
553            if let Some(ctx) = g.by_ctx.get(id) {
554                let projected = project_context(ctx.clone(), now);
555                if !matches!(
556                    projected.registry_state.status,
557                    Status::Superseded | Status::Retracted
558                ) {
559                    return Ok(Some(projected));
560                }
561            }
562        }
563        Ok(None)
564    }
565
566    fn commit_lifecycle_event(
567        &self,
568        event: &LifecycleEvent,
569    ) -> Result<LifecycleCommitOutcome, AcdpError> {
570        let now = chrono::Utc::now();
571        let mut g = self.lock();
572        let ctx = g.by_ctx.get_mut(event.ctx_id.as_str()).ok_or_else(|| {
573            AcdpError::NotFound(format!(
574                "context '{}' not found in this registry",
575                event.ctx_id
576            ))
577        })?;
578        let events = ctx
579            .registry_state
580            .lifecycle_events
581            .as_deref()
582            .unwrap_or(&[]);
583
584        // §6 retry idempotency / duplicate event_id (step 2).
585        if let Some(prior) = events.iter().find(|e| e.event_id == event.event_id) {
586            if prior == event {
587                return Ok(LifecycleCommitOutcome::IdempotentReplay(project_context(
588                    ctx.clone(),
589                    now,
590                )));
591            }
592            return Err(AcdpError::SchemaViolation(format!(
593                "event_id '{}' was already appended with different content \
594                 (RFC-ACDP-0013 §4: event_id MUST be unique within lifecycle_events)",
595                event.event_id
596            )));
597        }
598
599        // §6 step 4 — strict retracted/republished alternation against
600        // the §7.1 retraction state, under the same lock as the append.
601        let currently_retracted = acdp_types::lifecycle::retraction_state(events);
602        match &event.event_type {
603            LifecycleEventType::Retracted if currently_retracted => {
604                return Err(AcdpError::InvalidLifecycleTransition(format!(
605                    "context '{}' is already retracted — double retract violates the \
606                     strict alternation rule (RFC-ACDP-0013 §6 step 4)",
607                    event.ctx_id
608                )));
609            }
610            LifecycleEventType::Republished if !currently_retracted => {
611                return Err(AcdpError::InvalidLifecycleTransition(format!(
612                    "context '{}' is not retracted — republish requires a prior \
613                     retraction (RFC-ACDP-0013 §6 step 4)",
614                    event.ctx_id
615                )));
616            }
617            LifecycleEventType::Other(other) => {
618                return Err(AcdpError::SchemaViolation(format!(
619                    "event_type '{other}' is not registered for acceptance in 0.3.0 — \
620                     only 'retracted' and 'republished' transition state \
621                     (RFC-ACDP-0013 §7.3)"
622                )));
623            }
624            LifecycleEventType::Retracted | LifecycleEventType::Republished => {}
625        }
626
627        // §6 step 5 — append atomically with the status effect. The
628        // served status is DERIVED from this same array (§7.2
629        // precedence, applied by `project_status`), so appending the
630        // event IS the status change; the stored status keeps tracking
631        // the supersession fact only.
632        ctx.registry_state
633            .lifecycle_events
634            .get_or_insert_with(Vec::new)
635            .push(event.clone());
636        Ok(LifecycleCommitOutcome::Applied(project_context(
637            ctx.clone(),
638            now,
639        )))
640    }
641
642    fn mark_superseded(&self, ctx_id: &CtxId) -> Result<(), AcdpError> {
643        let mut g = self.lock();
644        if let Some(ctx) = g.by_ctx.get_mut(ctx_id.as_str()) {
645            ctx.registry_state.status = Status::Superseded;
646        }
647        Ok(())
648    }
649
650    fn first_version_ctx_id(&self, lineage_id: &LineageId) -> Result<Option<CtxId>, AcdpError> {
651        let g = self.lock();
652        Ok(g.lineages
653            .get(lineage_id.as_str())
654            .and_then(|ids| ids.first().cloned())
655            .map(CtxId))
656    }
657
658    fn idempotency_lookup(
659        &self,
660        agent_id: &AgentDid,
661        key: &str,
662    ) -> Result<Option<IdempotencyRecord>, AcdpError> {
663        // Lazy TTL eviction at lookup time keeps the table bounded
664        // without requiring a janitor — see idempotency_evict_expired.
665        self.idempotency_evict_expired(chrono::Utc::now())?;
666        let g = self.lock();
667        Ok(g.idempotency
668            .get(&(agent_id.as_str().to_string(), key.to_string()))
669            .cloned())
670    }
671
672    fn idempotency_record(
673        &self,
674        agent_id: &AgentDid,
675        key: &str,
676        hash: &acdp_types::primitives::ContentHash,
677        response: &acdp_types::publish::PublishResponse,
678        expires_at: chrono::DateTime<chrono::Utc>,
679    ) -> Result<(), AcdpError> {
680        let mut g = self.lock();
681        g.idempotency.insert(
682            (agent_id.as_str().to_string(), key.to_string()),
683            IdempotencyRecord {
684                content_hash: hash.clone(),
685                response: response.clone(),
686                expires_at,
687            },
688        );
689        Ok(())
690    }
691
692    fn idempotency_evict_expired(
693        &self,
694        now: chrono::DateTime<chrono::Utc>,
695    ) -> Result<(), AcdpError> {
696        let mut g = self.lock();
697        g.idempotency.retain(|_, r| r.expires_at > now);
698        Ok(())
699    }
700
701    fn commit_publish(&self, commit: PublishCommit<'_>) -> Result<PublishCommitOutcome, AcdpError> {
702        use crate::registry::validator::assign_identifiers;
703
704        let PublishCommit {
705            req,
706            authority,
707            idempotency,
708            // InMemoryStore does not model tenancy (it is a single-tenant
709            // reference/test backend); the durable backends honor this.
710            tenant: _,
711            receipt_minter,
712            predecessor_admission,
713        } = commit;
714        let now = chrono::Utc::now();
715        let mut g = self.lock();
716
717        // ── 1. Idempotency replay / collision ────────────────────────
718        if let Some(idem) = &idempotency {
719            let idem_key = (req.agent_id.as_str().to_string(), idem.key.to_string());
720            if let Some(prior) = g.idempotency.get(&idem_key) {
721                if prior.expires_at > now {
722                    return if prior.content_hash == req.content_hash {
723                        // idem-002: same key + same hash → replay.
724                        Ok(PublishCommitOutcome::IdempotentReplay(
725                            prior.response.clone(),
726                        ))
727                    } else {
728                        // idem-003: same key + different hash → duplicate_publish.
729                        Err(AcdpError::DuplicatePublish(format!(
730                            "Idempotency-Key '{}' was previously used by '{}' \
731                             with a different content_hash",
732                            idem.key, req.agent_id
733                        )))
734                    };
735                }
736                // Expired record — fall through and overwrite below.
737            }
738        }
739
740        // ── 2. Supersession lookups + coherence checks ──────────────
741        let first_v1 = if let Some(prev) = &req.supersedes {
742            let prev_full = g.by_ctx.get(prev.as_str()).cloned().ok_or_else(|| {
743                AcdpError::SupersededTarget {
744                    reason: acdp_primitives::error::SupersessionReason::NotFound,
745                    message: format!("supersedes target '{prev}' not found in this registry"),
746                }
747            })?;
748
749            // Producer-continuity: only the predecessor's producer (or a
750            // declared contributor) may publish a successor in its lineage.
751            // Signature verification only proves the *requester* signed
752            // their own request — it does not bind `supersedes` to the
753            // predecessor's owner. Without this check any signer could
754            // supersede another producer's context (`Superseded` side
755            // effect below + `current(lineage)` re-pointing), a full
756            // lineage takeover. RFC-ACDP-0001 §5.9 supersession is
757            // producer-scoped.
758            let is_owner = req.agent_id == prev_full.body.agent_id
759                || prev_full.body.contributors.contains(&req.agent_id);
760            if !is_owner {
761                // Uniform with the genuine not-found case above: a
762                // non-owner learns neither that the predecessor exists nor
763                // its version / superseded status (supersession existence
764                // oracle). Anyone who can legitimately read the
765                // predecessor learns nothing new from this shape.
766                return Err(AcdpError::SupersededTarget {
767                    reason: acdp_primitives::error::SupersessionReason::NotFound,
768                    message: format!("supersedes target '{prev}' not found in this registry"),
769                });
770            }
771
772            // Lineage coherence — when the producer self-verifies.
773            if let Some(declared) = &req.lineage_id {
774                if declared != &prev_full.body.lineage_id {
775                    return Err(AcdpError::SupersededTarget {
776                        reason: acdp_primitives::error::SupersessionReason::LineageMismatch,
777                        message: format!(
778                            "declared lineage_id '{declared}' ≠ predecessor's '{}'",
779                            prev_full.body.lineage_id
780                        ),
781                    });
782                }
783            }
784            // Version coherence: new.version MUST be predecessor.version + 1.
785            if req.version != prev_full.body.version + 1 {
786                return Err(AcdpError::SupersededTarget {
787                    reason: acdp_primitives::error::SupersessionReason::VersionMismatch,
788                    message: format!(
789                        "version {} ≠ predecessor.version + 1 ({})",
790                        req.version,
791                        prev_full.body.version + 1
792                    ),
793                });
794            }
795            // FEAT-01 atomicity: the check that previously raced with
796            // another concurrent publish. Now under the same lock as
797            // the insert below — exactly one of two contenders succeeds.
798            if matches!(prev_full.registry_state.status, Status::Superseded) {
799                return Err(AcdpError::SupersededTarget {
800                    reason: acdp_primitives::error::SupersessionReason::AlreadySuperseded,
801                    message: format!("supersedes target '{prev}' has already been superseded"),
802                });
803            }
804
805            // RFC-ACDP-0014 §4 `supersedes`-row enforcement. Runs AFTER
806            // producer-continuity, lineage/version coherence, and
807            // AlreadySuperseded have all passed — never earlier — so a
808            // non-owner (or wrong-tenant, on multi-tenant stores) probe
809            // is already turned away as `SupersededTarget::NotFound`
810            // above and never reaches this line. Doing this check first
811            // would make it a cross-tenant, non-owner
812            // existence-and-type oracle on the predecessor.
813            if let Some(admission) = predecessor_admission {
814                admission(&prev_full.body)?;
815            }
816
817            // Derive the v1 ctx_id from the predecessor's lineage —
818            // same logic as `first_version_ctx_id`, inlined to stay
819            // under the existing lock.
820            g.lineages
821                .get(prev_full.body.lineage_id.as_str())
822                .and_then(|ids| ids.first().cloned())
823                .map(CtxId)
824        } else {
825            None
826        };
827
828        // ── 3. Identifier assignment ────────────────────────────────
829        let validated = crate::registry::validator::ValidatedPublish {
830            recomputed_hash: req.content_hash.clone(),
831        };
832        let (ctx_id, lineage_id) =
833            assign_identifiers(authority, &req.supersedes, first_v1.as_ref(), &validated)?;
834
835        // ── 4. Build the stored Body ────────────────────────────────
836        // Single materialization point (IMP-02): the constructor copies
837        // every producer field and ms-truncates `created_at`, so this
838        // backend cannot drift from the SQL backends when a producer
839        // field is added.
840        let body =
841            Body::from_publish_request(req, ctx_id.clone(), lineage_id.clone(), authority, now);
842        let created_at = body.created_at;
843
844        // ── 5. Insert (mirrors `put` but inline so we keep the lock) ─
845        let ctx_id_str = body.ctx_id.0.clone();
846        let lineage_id_str = body.lineage_id.0.clone();
847        if g.by_ctx.contains_key(&ctx_id_str) {
848            // UUID collision is astronomically unlikely but we still
849            // surface it as a SchemaViolation rather than silently
850            // overwriting.
851            return Err(AcdpError::SchemaViolation(format!(
852                "ctx_id collision: '{ctx_id_str}' already exists"
853            )));
854        }
855        // Receipt minting (RFC-ACDP-0010) — inside the critical section,
856        // before the insert becomes visible, so a context published
857        // under the receipts profile never exists without its receipt.
858        let registry_receipt = receipt_minter.map(|mint| mint(&body)).transpose()?;
859
860        let stored = FullContext {
861            body,
862            registry_state: RegistryState {
863                status: Status::Active,
864                lifecycle_events: None,
865                extensions: Default::default(),
866            },
867            registry_receipt: registry_receipt.clone(),
868            // Head receipts are ephemeral serve-time attestations —
869            // never persisted; `RegistryServer::current` mints per
870            // response (RFC-ACDP-0011 §6).
871            lineage_head_receipt: None,
872            log_inclusion: None,
873            extensions: Default::default(),
874        };
875        g.by_ctx.insert(ctx_id_str.clone(), stored);
876        g.lineages
877            .entry(lineage_id_str)
878            .or_default()
879            .push(ctx_id_str);
880
881        // ── 6. Mark predecessor superseded ──────────────────────────
882        if let Some(prev) = &req.supersedes {
883            if let Some(prev_ctx) = g.by_ctx.get_mut(prev.as_str()) {
884                prev_ctx.registry_state.status = Status::Superseded;
885            }
886        }
887
888        let response = PublishResponse {
889            ctx_id,
890            lineage_id,
891            version: req.version,
892            created_at,
893            status: Status::Active,
894            registry_receipt,
895        };
896
897        // ── 7. Idempotency record ───────────────────────────────────
898        if let Some(idem) = idempotency {
899            let expires_at = now + idem.ttl;
900            g.idempotency.insert(
901                (req.agent_id.as_str().to_string(), idem.key.to_string()),
902                IdempotencyRecord {
903                    content_hash: req.content_hash.clone(),
904                    response: response.clone(),
905                    expires_at,
906                },
907            );
908        }
909
910        Ok(PublishCommitOutcome::Inserted(response))
911    }
912
913    fn search(
914        &self,
915        params: &SearchParams,
916        requester: Option<&AgentDid>,
917        anonymous_public_reads: bool,
918    ) -> Result<SearchResponse, AcdpError> {
919        let g = self.lock();
920        let now = chrono::Utc::now();
921
922        let q_lower = params.q.as_deref().map(str::to_lowercase);
923        let domain = params.domain.as_deref();
924        let agent = params.agent_id.as_deref();
925        let context_type = params.context_type.as_deref();
926        let derived_from = params.derived_from.as_deref();
927        let schema_uri = params.schema_uri.as_deref();
928        let tags: Option<Vec<&str>> = params.tags.as_deref().map(|s| {
929            s.split(',')
930                .map(str::trim)
931                .filter(|t| !t.is_empty())
932                .collect()
933        });
934
935        // BUG-10: parse date-time filter params at the boundary so the
936        // hot loop just compares DateTime<Utc> values.
937        let created_after = parse_opt_rfc3339(&params.created_after)?;
938        let created_before = parse_opt_rfc3339(&params.created_before)?;
939        let dp_start_after = parse_opt_rfc3339(&params.data_period_start_after)?;
940        let dp_end_before = parse_opt_rfc3339(&params.data_period_end_before)?;
941        let expires_after = parse_opt_rfc3339(&params.expires_after)?;
942        let expires_before = parse_opt_rfc3339(&params.expires_before)?;
943
944        let mut matches: Vec<&FullContext> = g
945            .by_ctx
946            .values()
947            .filter(|ctx| {
948                let body = &ctx.body;
949
950                // RFC-ACDP-0008 §4.5 search-disclosure gate (note the
951                // private/restricted asymmetry: private contexts surface
952                // in search only to their producer).
953                if !can_surface_in_search(body, requester, anonymous_public_reads) {
954                    return false;
955                }
956
957                if let Some(q) = &q_lower {
958                    let haystack = format!(
959                        "{} {} {} {} {} {}",
960                        body.title,
961                        body.description.as_deref().unwrap_or(""),
962                        body.summary.as_deref().unwrap_or(""),
963                        body.domain.as_deref().unwrap_or(""),
964                        body.agent_id.as_str(),
965                        body.tags.as_ref().map(|t| t.join(" ")).unwrap_or_default(),
966                    )
967                    .to_lowercase();
968                    if !haystack.contains(q) {
969                        return false;
970                    }
971                }
972                if let Some(d) = domain {
973                    if body.domain.as_deref() != Some(d) {
974                        return false;
975                    }
976                }
977                if let Some(a) = agent {
978                    if body.agent_id.as_str() != a {
979                        return false;
980                    }
981                }
982                if let Some(t) = context_type {
983                    let body_type = serde_json::to_value(&body.context_type)
984                        .ok()
985                        .and_then(|v| v.as_str().map(str::to_string))
986                        .unwrap_or_default();
987                    if body_type != t {
988                        return false;
989                    }
990                }
991                if let Some(df) = derived_from {
992                    if !body.derived_from.iter().any(|c| c.as_str() == df) {
993                        return false;
994                    }
995                }
996                if let Some(req_tags) = &tags {
997                    let body_tags = body.tags.as_deref().unwrap_or(&[]);
998                    if !req_tags.iter().all(|t| body_tags.iter().any(|bt| bt == t)) {
999                        return false;
1000                    }
1001                }
1002                if let Some(uri) = schema_uri {
1003                    if body.schema_uri.as_deref() != Some(uri) {
1004                        return false;
1005                    }
1006                }
1007                if let Some(after) = created_after {
1008                    if body.created_at < after {
1009                        return false;
1010                    }
1011                }
1012                if let Some(before) = created_before {
1013                    if body.created_at > before {
1014                        return false;
1015                    }
1016                }
1017                if let Some(after) = dp_start_after {
1018                    match &body.data_period {
1019                        Some(p) if p.start >= after => {}
1020                        _ => return false,
1021                    }
1022                }
1023                if let Some(before) = dp_end_before {
1024                    match &body.data_period {
1025                        Some(p) if p.end <= before => {}
1026                        _ => return false,
1027                    }
1028                }
1029                if let Some(after) = expires_after {
1030                    match body.expires_at {
1031                        Some(e) if e >= after => {}
1032                        _ => return false,
1033                    }
1034                }
1035                if let Some(before) = expires_before {
1036                    match body.expires_at {
1037                        Some(e) if e <= before => {}
1038                        _ => return false,
1039                    }
1040                }
1041                // Status filter — registry default is `active`. Compare
1042                // against PROJECTED status so a stored-Active body whose
1043                // expires_at has passed is filtered out (RFC-ACDP-0004 §4)
1044                // and a retracted context falls out of default searches —
1045                // and out of status=superseded / status=expired even where
1046                // those facts also hold (RFC-ACDP-0013 §8.2: the §7.2
1047                // precedence applies to the filter).
1048                let want_status = params.status.as_deref().unwrap_or("active");
1049                let effective = project_status(&ctx.registry_state, body, now);
1050                if effective.as_str() != want_status {
1051                    return false;
1052                }
1053                true
1054            })
1055            .collect();
1056
1057        // Newest first; IMP-03 — fall back to ctx_id for a deterministic
1058        // total order when many contexts share a millisecond.
1059        matches.sort_by(|a, b| {
1060            b.body
1061                .created_at
1062                .cmp(&a.body.created_at)
1063                .then_with(|| a.body.ctx_id.as_str().cmp(b.body.ctx_id.as_str()))
1064        });
1065
1066        // BUG-08: capture `total_estimate` BEFORE cursor filtering so
1067        // it represents the total count across all pages (RFC-ACDP-0005
1068        // §3 — clients use this for "page 1 of N" UIs). If we captured
1069        // it after `retain`, page 2 would show "80 matches" for a
1070        // 100-item search, page 3 "60", and so on.
1071        let total_estimate = Some(matches.len() as u64);
1072
1073        // BUG-10 cursor: opaque base64 of "<created_at_ms>:<ctx_id>".
1074        // ≥1h validity is implicit — cursors do not embed a timestamp,
1075        // so they remain valid until the underlying context is deleted.
1076        let cursor_anchor = params
1077            .cursor
1078            .as_deref()
1079            .map(decode_cursor)
1080            .transpose()?
1081            .flatten();
1082        if let Some((anchor_ms, anchor_id)) = &cursor_anchor {
1083            matches.retain(|c| {
1084                let ms = c.body.created_at.timestamp_millis();
1085                ms < *anchor_ms || (ms == *anchor_ms && c.body.ctx_id.as_str() > anchor_id.as_str())
1086            });
1087        }
1088
1089        // Clamp into [1, 100]: `limit` is attacker-controlled and never
1090        // lower-bounded. `limit=0` with ≥1 match would compute `limit - 1`
1091        // below → debug-build subtraction panic (request-thread DoS) /
1092        // release-build wrap to usize::MAX → broken pagination.
1093        let limit = params.limit.unwrap_or(50).clamp(1, 100) as usize;
1094        let next_cursor = if matches.len() > limit {
1095            matches.get(limit - 1).map(|c| {
1096                encode_cursor(c.body.created_at.timestamp_millis(), c.body.ctx_id.as_str())
1097            })
1098        } else {
1099            None
1100        };
1101
1102        let projected: Vec<SearchResult> = matches
1103            .iter()
1104            .take(limit)
1105            .map(|ctx| SearchResult {
1106                ctx_id: ctx.body.ctx_id.clone(),
1107                lineage_id: ctx.body.lineage_id.clone(),
1108                agent_id: ctx.body.agent_id.clone(),
1109                title: ctx.body.title.clone(),
1110                summary: ctx.body.summary.clone(),
1111                context_type: ctx.body.context_type.clone(),
1112                domain: ctx.body.domain.clone(),
1113                created_at: ctx.body.created_at,
1114                status: project_status(&ctx.registry_state, &ctx.body, now),
1115                // RFC-ACDP-0008 §4.5: only disclose visibility when the
1116                // requester is authorized for it. Public is always safe.
1117                // For restricted/private, the search filter above guarantees
1118                // the requester is producer-or-audience, so it's safe to
1119                // surface the label.
1120                visibility: Some(ctx.body.visibility.clone()),
1121            })
1122            .collect();
1123
1124        Ok(SearchResponse {
1125            matches: projected,
1126            total_estimate,
1127            next_cursor,
1128        })
1129    }
1130}
1131
1132/// Parse an optional RFC 3339 string parameter; surface a
1133/// [`AcdpError::SchemaViolation`] on malformed input.
1134fn parse_opt_rfc3339(
1135    s: &Option<String>,
1136) -> Result<Option<chrono::DateTime<chrono::Utc>>, AcdpError> {
1137    let Some(raw) = s.as_deref() else {
1138        return Ok(None);
1139    };
1140    let dt = chrono::DateTime::parse_from_rfc3339(raw)
1141        .map_err(|e| AcdpError::SchemaViolation(format!("malformed datetime '{raw}': {e}")))?;
1142    Ok(Some(dt.with_timezone(&chrono::Utc)))
1143}
1144
1145/// Cursor TTL — clients SHOULD re-fetch after this window.
1146/// RFC-ACDP-0005 §3 leaves the exact value to implementations; 1 hour
1147/// matches the common "≥1h" cursor-validity expectation.
1148const CURSOR_TTL: chrono::Duration = chrono::Duration::seconds(3600);
1149
1150/// Opaque cursor encoding — base64 of
1151/// `<mint_unix_ms>:<created_at_millis>:<ctx_id>`.
1152///
1153/// The `mint_unix_ms` prefix lets [`decode_cursor`] enforce the
1154/// `CURSOR_TTL` window and surface `AcdpError::CursorExpired` rather
1155/// than silently accepting an ancient cursor (FEAT-04). Plain
1156/// `STANDARD` engine so cursors are stable across machines.
1157fn encode_cursor(created_at_ms: i64, ctx_id: &str) -> String {
1158    use base64::{engine::general_purpose::STANDARD, Engine};
1159    let mint_ms = chrono::Utc::now().timestamp_millis();
1160    STANDARD.encode(format!("{mint_ms}:{created_at_ms}:{ctx_id}"))
1161}
1162
1163fn decode_cursor(s: &str) -> Result<Option<(i64, String)>, AcdpError> {
1164    use base64::{engine::general_purpose::STANDARD, Engine};
1165    let bytes = STANDARD
1166        .decode(s)
1167        .map_err(|_| AcdpError::InvalidCursor("cursor is not valid base64".into()))?;
1168    let decoded = String::from_utf8(bytes)
1169        .map_err(|_| AcdpError::InvalidCursor("cursor is not utf-8".into()))?;
1170    // Format: "<mint_ms>:<anchor_ms>:<ctx_id>". The mint timestamp
1171    // prefix is FEAT-04 expiry tracking.
1172    let mut parts = decoded.splitn(3, ':');
1173    let mint_str = parts
1174        .next()
1175        .ok_or_else(|| AcdpError::InvalidCursor("cursor missing mint timestamp".into()))?;
1176    let anchor_str = parts
1177        .next()
1178        .ok_or_else(|| AcdpError::InvalidCursor("cursor missing anchor timestamp".into()))?;
1179    let ctx_id = parts
1180        .next()
1181        .ok_or_else(|| AcdpError::InvalidCursor("cursor missing ctx_id".into()))?;
1182    let mint_ms: i64 = mint_str
1183        .parse()
1184        .map_err(|_| AcdpError::InvalidCursor("cursor mint millis is not an integer".into()))?;
1185    let anchor_ms: i64 = anchor_str
1186        .parse()
1187        .map_err(|_| AcdpError::InvalidCursor("cursor anchor millis is not an integer".into()))?;
1188
1189    // FEAT-04: reject cursors older than CURSOR_TTL with the
1190    // dedicated `cursor_expired` wire code so clients can distinguish
1191    // "you typo'd the cursor" (InvalidCursor) from "your cursor aged
1192    // out, restart the scan from page 1" (CursorExpired).
1193    let now = chrono::Utc::now().timestamp_millis();
1194    let age_ms = now.saturating_sub(mint_ms);
1195    if age_ms > CURSOR_TTL.num_milliseconds() {
1196        // CursorExpired is a unit variant in the wire-error mapping;
1197        // the diagnostic ("aged Xms ago") is intentionally surfaced
1198        // via Display rather than a payload so it round-trips through
1199        // `AcdpError::from_wire_error`.
1200        return Err(AcdpError::CursorExpired);
1201    }
1202    Ok(Some((anchor_ms, ctx_id.to_string())))
1203}
1204
1205#[cfg(test)]
1206mod tests {
1207    use super::*;
1208    use acdp_crypto::SigningKey;
1209    use acdp_producer::Producer;
1210    use acdp_types::body::{DataPeriod, Signature};
1211    use acdp_types::primitives::{AgentDid, ContentHash, ContextType, Visibility};
1212    use chrono::Utc;
1213
1214    fn fake_body(ctx_id: &str, lineage_id: &str, title: &str) -> Body {
1215        Body {
1216            ctx_id: CtxId(ctx_id.into()),
1217            lineage_id: LineageId(lineage_id.into()),
1218            origin_registry: "registry.example.com".into(),
1219            created_at: Utc::now(),
1220            content_hash: ContentHash("sha256:0".into()),
1221            signature: Signature {
1222                algorithm: "ed25519".into(),
1223                key_id: "did:web:agents.example.com:test#key-1".into(),
1224                value: "A".repeat(88),
1225            },
1226            version: 1,
1227            supersedes: None,
1228            agent_id: AgentDid::new("did:web:agents.example.com:test"),
1229            contributors: vec![],
1230            title: title.into(),
1231            context_type: ContextType::DataSnapshot,
1232            data_refs: vec![],
1233            derived_from: vec![],
1234            visibility: Visibility::Public,
1235            audience: None,
1236            acdp_version: None,
1237            description: None,
1238            summary: None,
1239            tags: None,
1240            domain: None,
1241            expires_at: None,
1242            data_period: None,
1243            metadata: None,
1244            schema_uri: None,
1245            anchors: None,
1246            extensions: Default::default(),
1247        }
1248    }
1249
1250    #[test]
1251    fn put_get_round_trip() {
1252        let s = InMemoryStore::new();
1253        let id = "acdp://r/12345678-1234-4321-8123-123456781234";
1254        let lin = "lin:sha256:1111111111111111111111111111111111111111111111111111111111111111";
1255        s.put(fake_body(id, lin, "A")).unwrap();
1256        let got = s.get(&CtxId(id.into())).unwrap().unwrap();
1257        assert_eq!(got.body.title, "A");
1258        assert!(matches!(got.registry_state.status, Status::Active));
1259    }
1260
1261    #[test]
1262    fn lineage_orders_by_publish_order() {
1263        let s = InMemoryStore::new();
1264        let lin = "lin:sha256:2222222222222222222222222222222222222222222222222222222222222222";
1265        let v1 = "acdp://r/12345678-1234-4321-8123-000000000001";
1266        let v2 = "acdp://r/12345678-1234-4321-8123-000000000002";
1267        s.put(fake_body(v1, lin, "v1")).unwrap();
1268        s.put(fake_body(v2, lin, "v2")).unwrap();
1269        let lineage = s.lineage(&LineageId(lin.into())).unwrap();
1270        assert_eq!(lineage.len(), 2);
1271        assert_eq!(lineage[0].body.title, "v1");
1272        assert_eq!(lineage[1].body.title, "v2");
1273    }
1274
1275    #[test]
1276    fn supersession_marks_predecessor() {
1277        let s = InMemoryStore::new();
1278        let lin = "lin:sha256:3333333333333333333333333333333333333333333333333333333333333333";
1279        let v1 = "acdp://r/12345678-1234-4321-8123-000000000003";
1280        s.put(fake_body(v1, lin, "v1")).unwrap();
1281        s.mark_superseded(&CtxId(v1.into())).unwrap();
1282        let got = s.get(&CtxId(v1.into())).unwrap().unwrap();
1283        assert!(matches!(got.registry_state.status, Status::Superseded));
1284    }
1285
1286    // BUG-11 — Status::Expired derived from body.expires_at at read time.
1287
1288    fn expired_body(
1289        ctx_id: &str,
1290        lineage_id: &str,
1291        title: &str,
1292        expires_at: chrono::DateTime<chrono::Utc>,
1293    ) -> Body {
1294        let mut b = fake_body(ctx_id, lineage_id, title);
1295        b.expires_at = Some(expires_at);
1296        b
1297    }
1298
1299    #[test]
1300    fn get_projects_active_to_expired_when_past_expires_at() {
1301        use chrono::Duration;
1302        let s = InMemoryStore::new();
1303        let lin = "lin:sha256:5555555555555555555555555555555555555555555555555555555555555555";
1304        let id = "acdp://r/12345678-1234-4321-8123-000000000006";
1305        s.put(expired_body(
1306            id,
1307            lin,
1308            "old",
1309            chrono::Utc::now() - Duration::hours(1),
1310        ))
1311        .unwrap();
1312        let got = s.get(&CtxId(id.into())).unwrap().unwrap();
1313        assert!(
1314            matches!(got.registry_state.status, Status::Expired),
1315            "expected Status::Expired projection, got {:?}",
1316            got.registry_state.status
1317        );
1318    }
1319
1320    #[test]
1321    fn get_keeps_active_when_expires_at_in_future() {
1322        use chrono::Duration;
1323        let s = InMemoryStore::new();
1324        let lin = "lin:sha256:6666666666666666666666666666666666666666666666666666666666666666";
1325        let id = "acdp://r/12345678-1234-4321-8123-000000000007";
1326        s.put(expired_body(
1327            id,
1328            lin,
1329            "fresh",
1330            chrono::Utc::now() + Duration::hours(1),
1331        ))
1332        .unwrap();
1333        let got = s.get(&CtxId(id.into())).unwrap().unwrap();
1334        assert!(matches!(got.registry_state.status, Status::Active));
1335    }
1336
1337    #[test]
1338    fn search_status_active_filters_out_expired() {
1339        use chrono::Duration;
1340        let s = InMemoryStore::new();
1341        let lin = "lin:sha256:7777777777777777777777777777777777777777777777777777777777777777";
1342        let id = "acdp://r/12345678-1234-4321-8123-000000000008";
1343        s.put(expired_body(
1344            id,
1345            lin,
1346            "old",
1347            chrono::Utc::now() - Duration::hours(1),
1348        ))
1349        .unwrap();
1350        let resp = s.search(&SearchParams::default(), None, true).unwrap();
1351        assert!(
1352            resp.matches.is_empty(),
1353            "expired must not surface under status=active default"
1354        );
1355        // Asking for `expired` SHOULD surface it.
1356        let resp = s
1357            .search(
1358                &SearchParams {
1359                    status: Some("expired".into()),
1360                    ..Default::default()
1361                },
1362                None,
1363                true,
1364            )
1365            .unwrap();
1366        assert_eq!(resp.matches.len(), 1);
1367    }
1368
1369    /// BUG-10 — date/time filter is honored.
1370    #[test]
1371    fn search_filters_by_created_after() {
1372        let s = InMemoryStore::new();
1373        let lin = "lin:sha256:8888888888888888888888888888888888888888888888888888888888888888";
1374        let mut body = fake_body(
1375            "acdp://r/12345678-1234-4321-8123-000000000009",
1376            lin,
1377            "match",
1378        );
1379        body.created_at = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00.000Z")
1380            .unwrap()
1381            .with_timezone(&chrono::Utc);
1382        s.put(body).unwrap();
1383        // `created_after` AFTER body.created_at → 0 matches
1384        let resp = s
1385            .search(
1386                &SearchParams {
1387                    created_after: Some("2026-02-01T00:00:00.000Z".into()),
1388                    ..Default::default()
1389                },
1390                None,
1391                true,
1392            )
1393            .unwrap();
1394        assert_eq!(resp.matches.len(), 0);
1395        // `created_after` BEFORE body.created_at → 1 match
1396        let resp = s
1397            .search(
1398                &SearchParams {
1399                    created_after: Some("2025-12-01T00:00:00.000Z".into()),
1400                    ..Default::default()
1401                },
1402                None,
1403                true,
1404            )
1405            .unwrap();
1406        assert_eq!(resp.matches.len(), 1);
1407    }
1408
1409    #[test]
1410    fn search_invalid_rfc3339_filter_rejected() {
1411        let s = InMemoryStore::new();
1412        let err = s
1413            .search(
1414                &SearchParams {
1415                    created_after: Some("not-a-date".into()),
1416                    ..Default::default()
1417                },
1418                None,
1419                true,
1420            )
1421            .unwrap_err();
1422        assert!(matches!(err, AcdpError::SchemaViolation(_)));
1423    }
1424
1425    /// BUG-10 cursor round-trips and pages correctly.
1426    #[test]
1427    fn search_cursor_pages_results() {
1428        let s = InMemoryStore::new();
1429        let lin = "lin:sha256:9999999999999999999999999999999999999999999999999999999999999999";
1430        // Insert 5 contexts with distinct created_at so order is deterministic.
1431        let base = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00.000Z")
1432            .unwrap()
1433            .with_timezone(&chrono::Utc);
1434        for i in 0..5u8 {
1435            let mut body = fake_body(
1436                &format!("acdp://r/12345678-1234-4321-8123-00000000010{i}"),
1437                lin,
1438                "match",
1439            );
1440            body.created_at = base + chrono::Duration::minutes(i as i64);
1441            s.put(body).unwrap();
1442        }
1443        let p1 = s
1444            .search(
1445                &SearchParams {
1446                    limit: Some(2),
1447                    ..Default::default()
1448                },
1449                None,
1450                true,
1451            )
1452            .unwrap();
1453        assert_eq!(p1.matches.len(), 2);
1454        let cursor = p1.next_cursor.expect("page 1 should carry a cursor");
1455        let p2 = s
1456            .search(
1457                &SearchParams {
1458                    limit: Some(2),
1459                    cursor: Some(cursor.clone()),
1460                    ..Default::default()
1461                },
1462                None,
1463                true,
1464            )
1465            .unwrap();
1466        assert_eq!(p2.matches.len(), 2);
1467        // No overlap between page 1 and page 2.
1468        for r in &p2.matches {
1469            assert!(
1470                !p1.matches.iter().any(|q| q.ctx_id == r.ctx_id),
1471                "page 2 overlapped page 1"
1472            );
1473        }
1474        // BUG-08: total_estimate MUST be stable across pages — captured
1475        // BEFORE cursor filtering. Before the fix, page 2 reported a
1476        // smaller total than page 1 (the remaining-from-cursor count).
1477        assert_eq!(
1478            p1.total_estimate, p2.total_estimate,
1479            "total_estimate MUST be stable across pages (BUG-08); \
1480             p1={:?}, p2={:?}",
1481            p1.total_estimate, p2.total_estimate
1482        );
1483        assert_eq!(
1484            p1.total_estimate,
1485            Some(5),
1486            "total_estimate MUST reflect total matches across all pages, got {:?}",
1487            p1.total_estimate
1488        );
1489    }
1490
1491    #[test]
1492    fn search_limit_zero_does_not_underflow() {
1493        // P1-1: limit=0 with ≥1 match previously computed `limit - 1`
1494        // (debug panic / release wrap). It MUST be clamped to ≥1.
1495        let s = InMemoryStore::new();
1496        let lin = "lin:sha256:8888888888888888888888888888888888888888888888888888888888888888";
1497        for i in 0..3u8 {
1498            let body = fake_body(
1499                &format!("acdp://r/12345678-1234-4321-8123-00000000020{i}"),
1500                lin,
1501                "match",
1502            );
1503            s.put(body).unwrap();
1504        }
1505        let page = s
1506            .search(
1507                &SearchParams {
1508                    limit: Some(0),
1509                    ..Default::default()
1510                },
1511                None,
1512                true,
1513            )
1514            .expect("limit=0 must not panic or error");
1515        // Clamped to 1: one result, and a cursor since more remain.
1516        assert_eq!(page.matches.len(), 1);
1517        assert!(page.next_cursor.is_some());
1518    }
1519
1520    #[test]
1521    fn search_malformed_cursor_rejected() {
1522        let s = InMemoryStore::new();
1523        let err = s
1524            .search(
1525                &SearchParams {
1526                    cursor: Some("not_base64!@#".into()),
1527                    ..Default::default()
1528                },
1529                None,
1530                true,
1531            )
1532            .unwrap_err();
1533        assert!(matches!(err, AcdpError::InvalidCursor(_)));
1534    }
1535
1536    /// FEAT-04: a cursor whose embedded mint timestamp is older than
1537    /// `CURSOR_TTL` MUST surface as `CursorExpired`, not `InvalidCursor`.
1538    /// Clients distinguish "you typo'd the cursor" from "your cursor
1539    /// aged out, restart the scan from page 1".
1540    #[test]
1541    fn search_aged_cursor_rejected_as_cursor_expired() {
1542        use base64::{engine::general_purpose::STANDARD, Engine};
1543        let s = InMemoryStore::new();
1544        // Mint a cursor 7200s in the past — twice the 3600s TTL.
1545        let stale_mint_ms = chrono::Utc::now().timestamp_millis() - 7200 * 1000;
1546        let aged = STANDARD.encode(format!(
1547            "{stale_mint_ms}:0:acdp://r/12345678-1234-4321-8123-1234567812aa"
1548        ));
1549        let err = s
1550            .search(
1551                &SearchParams {
1552                    cursor: Some(aged),
1553                    ..Default::default()
1554                },
1555                None,
1556                true,
1557            )
1558            .unwrap_err();
1559        assert!(
1560            matches!(err, AcdpError::CursorExpired),
1561            "expired cursor MUST surface CursorExpired, got {err:?}"
1562        );
1563    }
1564
1565    #[test]
1566    fn search_filters_by_status_default_active() {
1567        let s = InMemoryStore::new();
1568        let lin = "lin:sha256:4444444444444444444444444444444444444444444444444444444444444444";
1569        let v1 = "acdp://r/12345678-1234-4321-8123-000000000004";
1570        let v2 = "acdp://r/12345678-1234-4321-8123-000000000005";
1571        s.put(fake_body(v1, lin, "old")).unwrap();
1572        s.put(fake_body(v2, lin, "new")).unwrap();
1573        s.mark_superseded(&CtxId(v1.into())).unwrap();
1574        let resp = s
1575            .search(
1576                &SearchParams {
1577                    q: Some("old".into()),
1578                    ..Default::default()
1579                },
1580                None,
1581                true,
1582            )
1583            .unwrap();
1584        // Only `active` matches — superseded "old" filtered out.
1585        assert_eq!(resp.matches.len(), 0);
1586        let resp = s
1587            .search(
1588                &SearchParams {
1589                    q: Some("new".into()),
1590                    ..Default::default()
1591                },
1592                None,
1593                true,
1594            )
1595            .unwrap();
1596        assert_eq!(resp.matches.len(), 1);
1597    }
1598
1599    /// End-to-end: producer → server pipeline using the actual signing
1600    /// path. Uses a builder and the `RegistryServer` (see server.rs)
1601    /// to confirm the integration story.
1602    #[test]
1603    fn store_round_trip_from_real_publish_request() {
1604        use crate::registry::server::RegistryServer;
1605        use acdp_types::capabilities::{CapabilitiesDocument, Limits};
1606
1607        let key = SigningKey::from_bytes(&[7u8; 32]);
1608        let p = Producer::new(
1609            key,
1610            AgentDid::new("did:web:agents.example.com:test"),
1611            "did:web:agents.example.com:test#key-1",
1612        );
1613        let req = p
1614            .publish_request()
1615            .title("hello")
1616            .context_type(ContextType::DataSnapshot)
1617            .visibility(Visibility::Public)
1618            .build()
1619            .unwrap();
1620
1621        let caps = CapabilitiesDocument {
1622            acdp_version: "0.1.0".into(),
1623            registry_did: "did:web:registry.example.com".into(),
1624            supported_signature_algorithms: vec!["ed25519".into()],
1625            supported_did_methods: vec!["did:web".into()],
1626            profiles: vec!["acdp-registry-core".into()],
1627            limits: Limits {
1628                max_payload_bytes: 1_048_576,
1629                max_embedded_bytes: 65_536,
1630                idempotency_key_ttl_seconds: None,
1631                max_publish_per_minute: None,
1632            },
1633            read_authentication_methods: vec![],
1634            anonymous_public_reads: true,
1635            supports_idempotency_key: false,
1636            extensions: Default::default(),
1637        };
1638
1639        let server = RegistryServer::new(InMemoryStore::new(), caps, "registry.example.com");
1640        let resp = server.publish_unverified_for_tests(&req).unwrap();
1641        assert_eq!(resp.version, 1);
1642        let ctx = server.retrieve(&resp.ctx_id, None).unwrap().unwrap();
1643        assert_eq!(ctx.body.title, "hello");
1644
1645        // Ignore unused imports under different feature combinations
1646        let _: Option<DataPeriod> = ctx.body.data_period.clone();
1647    }
1648}
1649
1650#[cfg(test)]
1651mod publish_commit_outcome_tests {
1652    use super::*;
1653    use acdp_types::publish::PublishResponse;
1654    use acdp_types::Status;
1655
1656    fn response(version: u32) -> PublishResponse {
1657        PublishResponse {
1658            registry_receipt: None,
1659            ctx_id: acdp_types::CtxId(
1660                "acdp://registry.example.com/12345678-1234-4321-8123-000000000099".into(),
1661            ),
1662            lineage_id: acdp_types::LineageId(
1663                "lin:sha256:9999999999999999999999999999999999999999999999999999999999999999"
1664                    .into(),
1665            ),
1666            version,
1667            created_at: chrono::Utc::now(),
1668            status: Status::Active,
1669        }
1670    }
1671
1672    /// `is_replay` is the whole point of this type surviving past
1673    /// `commit_via_store`, so it is asserted on BOTH variants rather than
1674    /// only on the interesting one: a `matches!` that had been written
1675    /// against the wrong variant passes a one-sided test.
1676    #[test]
1677    fn is_replay_discriminates_both_ways() {
1678        assert!(
1679            !PublishCommitOutcome::Inserted(response(1)).is_replay(),
1680            "a fresh insert must not report as a replay — a registry reading \
1681             this answers 200 instead of 201 Created"
1682        );
1683        assert!(
1684            PublishCommitOutcome::IdempotentReplay(response(1)).is_replay(),
1685            "a replay must report as one — a registry reading this answers \
1686             201 Created to a retry, which idem-002 forbids explicitly"
1687        );
1688    }
1689
1690    /// Both variants must yield their OWN response, not a fixed arm. An
1691    /// `into_response` mistakenly written as `Self::Inserted(r) => r, _ =>
1692    /// <the other one>` is caught by varying `version` per variant rather
1693    /// than reusing one value — the field is read, so the assertion cannot
1694    /// pass on a response the test never built.
1695    #[test]
1696    fn into_response_and_response_yield_the_carried_value_on_both_variants() {
1697        let inserted = PublishCommitOutcome::Inserted(response(1));
1698        let replayed = PublishCommitOutcome::IdempotentReplay(response(7));
1699
1700        assert_eq!(inserted.response().version, 1);
1701        assert_eq!(replayed.response().version, 7);
1702
1703        // `response()` borrows, so the outcome is still usable afterwards —
1704        // that is the property the registry needs (inspect, then consume).
1705        assert_eq!(inserted.into_response().version, 1);
1706        assert_eq!(replayed.into_response().version, 7);
1707    }
1708}