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