wyrd-client 0.3.0

Shared Wyrd client: transport, authentication, and composed client capabilities.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
//! Public `Cards` handle and client-side selector types.

use std::path::Path;
use std::sync::Arc;

use crate::WyrdClient;
#[cfg(feature = "internal")]
use futures_util::StreamExt;
#[cfg(feature = "internal")]
use reqwest::Method;
use wyrd_loader::DeclarationInput;
use wyrd_semver::VersionBlock;
use wyrd_spec::envelope::{Card, CardKind};
use wyrd_spec::error::WyrdError;
use wyrd_spec::ids::{CardName, CardUid, SpaceName};
use wyrd_spec::reference::CardRef;
#[cfg(feature = "internal")]
use wyrd_spec::registry::GetCardResponse;
use wyrd_spec::registry::{ListCardsRequest, ListCardsResponse};
#[cfg(feature = "internal")]
use wyrd_spec::storage::{DownloadInitRequest, DownloadInitResponse};

#[cfg(feature = "internal")]
use crate::cards::download;
#[cfg(feature = "internal")]
use crate::cards::download_progress::DownloadProgressDisplay;
use crate::cards::engine::{RegistryContext, RegistryEngine};
#[cfg(feature = "internal")]
use crate::cards::error::RegistryEngineError;
use crate::cards::progress::DeclarationProgressSink;
use crate::cards::reads;
use crate::cards::{BundleMode, CardGraphPuller, DeclarationReceipt, PullSummary};

/// A read-time Card lookup request.
///
/// A named selector without a version means latest Active. A UID selector is
/// exact; optional identity fields are consistency assertions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CardSelector {
    /// Select by kind, space, name, and optional exact version.
    Named {
        /// Card kind.
        kind: CardKind,
        /// Card space.
        space: SpaceName,
        /// Card name.
        name: CardName,
        /// Exact version, or `None` for latest Active reads.
        version: Option<VersionBlock>,
    },
    /// Select by an exact reference without changing its optional UID.
    Exact(CardRef),
    /// Select by exact UID with optional identity assertions.
    Uid {
        /// Card kind owning the UID.
        kind: CardKind,
        /// Exact Card UID.
        uid: CardUid,
        /// Optional asserted space.
        space: Option<SpaceName>,
        /// Optional asserted name.
        name: Option<CardName>,
        /// Optional asserted exact version.
        version: Option<VersionBlock>,
    },
}

impl CardSelector {
    /// Build a named selector whose read default is latest Active.
    ///
    /// # Arguments
    /// * `kind` - The Card kind.
    /// * `space` - The Card space.
    /// * `name` - The Card name.
    #[must_use]
    pub fn named(kind: CardKind, space: SpaceName, name: CardName) -> Self {
        Self::Named {
            kind,
            space,
            name,
            version: None,
        }
    }

    /// Build an exact selector from a resolved Card reference.
    ///
    /// # Arguments
    /// * `card_ref` - The exact reference to select, including its optional UID.
    #[must_use]
    pub fn exact(card_ref: CardRef) -> Self {
        Self::Exact(card_ref)
    }

    /// Build an exact UID selector.
    ///
    /// # Arguments
    /// * `kind` - The Card kind owning the UID.
    /// * `uid` - The exact Card UID.
    #[must_use]
    pub fn uid(kind: CardKind, uid: CardUid) -> Self {
        Self::Uid {
            kind,
            uid,
            space: None,
            name: None,
            version: None,
        }
    }

    /// Add an exact version assertion to a selector.
    ///
    /// # Arguments
    /// * `version` - The exact version the selected Card must have.
    #[must_use]
    pub fn with_version(mut self, version: VersionBlock) -> Self {
        match &mut self {
            Self::Exact(CardRef {
                version: selected, ..
            }) => *selected = version,
            Self::Named {
                version: selected, ..
            }
            | Self::Uid {
                version: selected, ..
            } => *selected = Some(version),
        }
        self
    }

    /// Add optional identity assertions to a UID selector.
    ///
    /// # Arguments
    /// * `space` - The space the UID's Card must have, or `None`.
    /// * `name` - The name the UID's Card must have, or `None`.
    #[must_use]
    pub fn with_identity_assertions(
        mut self,
        space: Option<SpaceName>,
        name: Option<CardName>,
    ) -> Self {
        if let Self::Uid {
            space: selected_space,
            name: selected_name,
            ..
        } = &mut self
        {
            *selected_space = space;
            *selected_name = name;
        }
        self
    }
}

/// Cheap-to-clone, tenant-scoped Card registry handle.
#[derive(Clone)]
pub struct Cards {
    /// Shared registry engine that owns the authenticated transport, tenant
    /// scope, and declaration saga; cloning `Cards` only bumps this
    /// `Arc`, so every clone drives the same engine state.
    pub(crate) engine: Arc<RegistryEngine>,
}

impl Cards {
    /// Connect a registry handle through the ambient client.
    ///
    /// The client resolves the global configuration file, then the
    /// environment, then the saved user login selected by `WYRD_TENANT`, as
    /// [`WyrdClient::from_global`] does, and completes any credential exchange
    /// that credential requires before returning; a presented-as-is bearer or
    /// fresh cached token is reused without a request.
    ///
    /// # Errors
    /// Returns a Wyrd error when the global configuration cannot be read, no
    /// credential resolves, the saved-login selection fails, or a required
    /// exchange is refused or unreachable.
    pub async fn connect() -> Result<Self, WyrdError> {
        Ok(Self {
            engine: RegistryEngine::new(WyrdClient::connect_ambient().await?),
        })
    }

    /// Build a handle over `client` without completing any exchange.
    ///
    /// Test-only: offline unit tests construct the registry engine here;
    /// public callers use [`Self::connect`] or [`Self::connect_with`].
    ///
    /// # Arguments
    /// * `client` - The client every call is sent through.
    #[cfg(test)]
    pub(crate) fn new(client: WyrdClient) -> Self {
        Self {
            engine: RegistryEngine::new(client),
        }
    }

    /// Connect a handle that calls the server as `client`'s principal.
    ///
    /// Every registry read, write, and artifact transfer this handle and its
    /// clones issue shares `client`'s transport and token cache.
    ///
    /// # Arguments
    /// * `client` - The client every call is sent through, used as given.
    ///
    /// # Errors
    /// Returns the server's stable error when the client's required exchange
    /// is refused or unreachable.
    pub async fn connect_with(client: &WyrdClient) -> Result<Self, WyrdError> {
        Ok(Self {
            engine: RegistryEngine::new(client.connected().await?),
        })
    }

    /// Download and verify every server-declared artifact for one Card.
    ///
    /// The caller owns the destination and its lifetime. This method owns only
    /// registry selection, server download-plan creation, bounded transfer, and
    /// integrity verification; no Card receives a registry or storage handle.
    ///
    /// # Arguments
    /// * `card_uid` - The exact Card whose artifact inventory is downloaded.
    /// * `destination` - The directory the verified artifacts are published
    ///   to; an existing directory is replaced only after every transfer
    ///   verifies.
    ///
    /// # Errors
    /// Returns a Wyrd error when inventory lookup, destination preparation,
    /// transfer, or integrity verification fails.
    #[cfg(feature = "internal")]
    pub async fn download_artifacts_to(
        &self,
        card_uid: &CardUid,
        destination: impl AsRef<Path>,
    ) -> Result<(), WyrdError> {
        ArtifactMaterializer::new(self, card_uid, destination.as_ref())
            .materialize()
            .await
    }

    /// Clone the authenticated context for another focused registry capability.
    ///
    /// The returned context shares this handle's transport, authentication
    /// cache, and storage client without exposing their implementation types.
    #[must_use]
    #[cfg(feature = "internal")]
    pub fn registry_context(&self) -> RegistryContext {
        RegistryContext::new(Arc::clone(&self.engine))
    }

    /// Loads one Card document from disk and declares it through the authenticated registry.
    ///
    /// The loader resolves the document and its local source context before this method
    /// delegates the durable write to [`Self::declare`].
    ///
    /// # Arguments
    /// * `path` - A Card file, or a bundle directory whose Card files and
    ///   their local sources are declared together.
    ///
    /// # Errors
    ///
    /// Returns `WYRD_LOADER_400_INVALID_ENVELOPE`, carrying the loader's per-file
    /// diagnostics, when the document cannot be loaded or converted into a
    /// declaration request (the same code `wyrd declare` reports for that tree),
    /// or the registry's error when it rejects the declaration.
    pub async fn declare_from_path(
        &self,
        path: impl AsRef<Path>,
    ) -> Result<DeclarationReceipt, WyrdError> {
        let tree = wyrd_loader::load(path.as_ref())?;
        let input = wyrd_loader::build_declaration_input(tree)?;
        self.declare(&input).await
    }

    /// Declare a loader-produced composite input and drive its private
    /// artifact transfer and server-owned completion lifecycle.
    ///
    /// Native language card holders lower into this input at their language
    /// adapter boundary. Local source paths are consumed only by the private
    /// saga and never enter the request body.
    ///
    /// # Arguments
    /// * `input` - The loader-produced declaration input, including local artifact sources.
    ///
    /// # Errors
    /// Returns a Wyrd error when validation, declaration, artifact upload, or
    /// server-owned completion fails.
    pub async fn declare(&self, input: &DeclarationInput) -> Result<DeclarationReceipt, WyrdError> {
        crate::cards::saga::declare(&self.engine, input, None)
            .await
            .map_err(Into::into)
    }

    /// Declare a loader-produced composite input and forward typed progress
    /// events to the caller while the saga runs.
    ///
    /// The callback may be invoked concurrently for up to four active
    /// artifact transfers. Callers that update shared state must provide their
    /// own synchronization; the callback itself must be safe to call from
    /// multiple asynchronous tasks.
    ///
    /// # Arguments
    /// * `input` - The loader-produced declaration input, including local artifact sources.
    /// * `progress` - The callback that receives each typed progress event.
    ///
    /// # Errors
    /// Returns a Wyrd error when validation, declaration, artifact upload, or
    /// server-owned completion fails.
    pub async fn declare_with_progress(
        &self,
        input: &DeclarationInput,
        progress: DeclarationProgressSink,
    ) -> Result<DeclarationReceipt, WyrdError> {
        crate::cards::saga::declare(&self.engine, input, Some(progress))
            .await
            .map_err(Into::into)
    }

    /// Fetch one Card envelope using exact or latest selector semantics.
    ///
    /// # Arguments
    /// * `selector` - The Card to read; a named selector without a version reads the latest Active version.
    ///
    /// # Errors
    /// Returns a Wyrd error when the selector is invalid, the Card is absent,
    /// or the server request fails.
    pub async fn get(&self, selector: CardSelector) -> Result<Card, WyrdError> {
        reads::get(&self.engine.client, &selector)
            .await
            .map_err(Into::into)
    }

    /// Fetch one Card response with its server-derived timestamps.
    ///
    /// # Arguments
    /// * `selector` - The Card to read; a named selector without a version reads the latest Active version.
    ///
    /// # Errors
    /// Returns a Wyrd error when the selector is invalid, the Card is absent,
    /// or the server request fails.
    #[cfg(feature = "internal")]
    pub async fn get_response(&self, selector: CardSelector) -> Result<GetCardResponse, WyrdError> {
        reads::get_response(&self.engine.client, &selector)
            .await
            .map_err(Into::into)
    }

    /// List metadata-only Card summaries through the typed server query.
    ///
    /// # Arguments
    /// * `request` - The kind, space, name, version-range, status, and paging filters.
    ///
    /// # Errors
    /// Returns a Wyrd error when the request is invalid or the server query
    /// fails.
    pub async fn list(&self, request: ListCardsRequest) -> Result<ListCardsResponse, WyrdError> {
        reads::list(&self.engine.client, request)
            .await
            .map_err(Into::into)
    }

    /// Plan one authorized artifact download through the typed storage
    /// contract.
    ///
    /// # Arguments
    /// * `request` - The Card UID, artifact path, and optional URL lifetime.
    ///
    /// # Errors
    /// Returns a Wyrd error when the Card or artifact is absent, unauthorized,
    /// or the server cannot mint a download plan.
    #[cfg(feature = "internal")]
    pub async fn download_init(
        &self,
        request: DownloadInitRequest,
    ) -> Result<DownloadInitResponse, WyrdError> {
        self.engine
            .client
            .request_json(Method::POST, "/v1/cards/download/init", Some(&request))
            .await
    }

    /// Soft-delete one Card. Named selectors must include an exact version.
    ///
    /// # Arguments
    /// * `selector` - The exact Card to delete.
    ///
    /// # Errors
    /// Returns a Wyrd error when the selector is not exact, the Card is absent,
    /// or the server mutation fails.
    pub async fn delete(&self, selector: CardSelector) -> Result<(), WyrdError> {
        crate::cards::reads::delete(&self.engine.client, selector)
            .await
            .map_err(Into::into)
    }

    /// Resolve the latest Active version to an exact `CardRef`.
    ///
    /// # Arguments
    /// * `kind` - The Card kind.
    /// * `space` - The Card space.
    /// * `name` - The Card name.
    ///
    /// # Errors
    /// Returns a Wyrd error when no Active version matches or the server query
    /// fails.
    pub async fn resolve_latest(
        &self,
        kind: CardKind,
        space: SpaceName,
        name: CardName,
    ) -> Result<CardRef, WyrdError> {
        reads::resolve_latest(&self.engine.client, kind, space, name)
            .await
            .map_err(Into::into)
    }

    /// Pull a declared Card's reachable graph as a local bundle.
    ///
    /// Resolves `selector`, reads every Card its relationships reach, and
    /// publishes them under `destination` in the Card bundle layout
    /// [`crate::state::WyrdState::from_path`] loads. Publication is atomic:
    /// the bundle is staged beside `destination` and renamed into place, so a
    /// failed pull leaves any prior bundle intact.
    ///
    /// # Arguments
    /// * `selector` - The root Card; a named selector without a version reads
    ///   the latest Active version.
    /// * `destination` - The bundle directory to publish.
    /// * `mode` - [`BundleMode::Complete`] also downloads and verifies every
    ///   artifact; [`BundleMode::MetadataOnly`] writes Card metadata only.
    ///
    /// # Errors
    /// Returns a Wyrd error when the graph cannot be resolved, the destination
    /// is invalid, an artifact cannot be downloaded or verified, or the staged
    /// bundle cannot be published.
    pub async fn pull(
        &self,
        selector: CardSelector,
        destination: impl AsRef<Path>,
        mode: BundleMode,
    ) -> Result<PullSummary, WyrdError> {
        CardGraphPuller::new(RegistryContext::new(Arc::clone(&self.engine)))
            .pull(&selector, destination.as_ref(), mode)
            .await
    }
}

/// Builds one complete verified artifact publication before exposing it.
///
/// The materializer retains the authenticated registry engine, exact card UID,
/// and caller-selected destination for one operation. It writes only beneath a
/// random sibling staging directory and renames that complete directory into
/// place after every transfer verifies, so failed transfers cannot alter a
/// prior destination.
#[cfg(feature = "internal")]
struct ArtifactMaterializer<'a> {
    /// Authenticated registry transport and storage client.
    engine: &'a Arc<RegistryEngine>,
    /// Exact server-assigned owner of the inventory.
    card_uid: &'a CardUid,
    /// Final caller-visible artifact root.
    destination: &'a Path,
}

/// Runs the staged download and atomic publication workflow.
#[cfg(feature = "internal")]
impl<'a> ArtifactMaterializer<'a> {
    /// Create a materializer for one Card inventory and destination.
    #[must_use]
    fn new(cards: &'a Cards, card_uid: &'a CardUid, destination: &'a Path) -> Self {
        Self {
            engine: &cards.engine,
            card_uid,
            destination,
        }
    }

    /// Fetch, verify, and atomically publish the complete artifact inventory.
    ///
    /// # Errors
    /// Returns a Wyrd error when inventory planning, staging creation, any
    /// transfer, digest verification, or final publication fails. On transfer
    /// failure the staging directory is dropped and the destination is not
    /// modified. The workflow clears its stdout transfer display before either
    /// a result or error becomes visible to its caller.
    ///
    /// # Cancellation
    /// Cancellation drops the unpublished staging directory and may remove the
    /// active display without completing its bars. The prior destination
    /// remains unchanged.
    async fn materialize(&self) -> Result<(), WyrdError> {
        let inventory = reads::list_artifacts(&self.engine.client, self.card_uid)
            .await
            .map_err(WyrdError::from)?;
        let parent =
            self.destination
                .parent()
                .ok_or_else(|| WyrdError::RegistryInvalidCardSpec {
                    message: "artifact destination must have a parent directory".to_owned(),
                    details: serde_json::json!({ "destination": self.destination }),
                })?;
        tokio::fs::create_dir_all(parent)
            .await
            .map_err(RegistryEngineError::from)
            .map_err(WyrdError::from)?;
        let staging = tempfile::Builder::new()
            .prefix(".wyrd-artifacts-")
            .tempdir_in(parent)
            .map_err(RegistryEngineError::from)
            .map_err(WyrdError::from)?;
        let staging_root = staging.path().join("publication");
        tokio::fs::create_dir(&staging_root)
            .await
            .map_err(RegistryEngineError::from)
            .map_err(WyrdError::from)?;
        let display = Arc::new(DownloadProgressDisplay::stdout());
        let downloads =
            futures_util::stream::iter(inventory.artifacts.into_iter().map(|artifact| {
                let engine = Arc::clone(self.engine);
                let card_uid = self.card_uid.clone();
                let staging_root = staging_root.clone();
                let display = Arc::clone(&display);
                async move {
                    let path = staging_root.join(artifact.relative_path.as_str());
                    if let Some(parent) = path.parent() {
                        tokio::fs::create_dir_all(parent)
                            .await
                            .map_err(RegistryEngineError::from)?;
                    }
                    download::download_artifact(
                        &engine.client,
                        &engine.storage,
                        &card_uid,
                        &artifact.relative_path,
                        &path,
                        display,
                    )
                    .await
                }
            }))
            .buffer_unordered(4)
            .collect::<Vec<_>>()
            .await;
        let result = match downloads.into_iter().find_map(Result::err) {
            Some(error) => Err(WyrdError::from(error)),
            None => self.publish(&staging_root, staging.path()).await,
        };
        display.clear();
        result
    }

    /// Replace the destination only after the complete staging tree verifies.
    ///
    /// The old destination is first renamed beneath the private staging root.
    /// If publishing the new tree fails, that old tree is restored before the
    /// error is returned. Dropping the staging guard removes the superseded
    /// tree only after the new publication is visible.
    ///
    /// # Errors
    /// Returns a Wyrd error if either rename fails. A failed publish attempts
    /// to restore the prior destination; restoration failure is reported with
    /// the original publish failure retained in diagnostics.
    async fn publish(&self, staging_root: &Path, staging_parent: &Path) -> Result<(), WyrdError> {
        let previous = staging_parent.join("previous");
        let had_previous = self.destination.exists();
        if had_previous {
            tokio::fs::rename(self.destination, &previous)
                .await
                .map_err(RegistryEngineError::from)
                .map_err(WyrdError::from)?;
        }
        if let Err(error) = tokio::fs::rename(staging_root, self.destination).await {
            if had_previous {
                let _ = tokio::fs::rename(&previous, self.destination).await;
            }
            return Err(RegistryEngineError::from(error).into());
        }
        Ok(())
    }
}

/// Selector construction and handle behavior.
#[cfg(test)]
mod tests {
    use base64::Engine;
    use secrecy::SecretString;
    use sha2::{Digest, Sha256};
    use wiremock::matchers::{body_json, method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    use super::{CardSelector, Cards};
    use crate::cards::BundleMode;
    use wyrd_semver::VersionBlock;
    use wyrd_spec::card::verifier::DriftBaselineState;
    use wyrd_spec::envelope::{CardKind, Spec};
    use wyrd_spec::ids::{CardName, CardUid, SpaceName};
    use wyrd_spec::reference::CardRef;

    /// A client pointed at `server` with a static credential.
    ///
    /// # Panics
    /// Panics if the static configuration cannot build a client.
    fn test_client(server: &MockServer) -> crate::WyrdClient {
        crate::WyrdClient::with_config(crate::config::ClientConfig {
            credential: Some(SecretString::from("test-api-key")),
            http: crate::transport::HttpConfig {
                base_url: server.uri(),
                ..crate::transport::HttpConfig::default()
            },
            ..crate::config::ClientConfig::default()
        })
        .expect("static config builds a client")
    }

    /// Preserve an existing publication and remove private staging when a later
    /// artifact fails integrity verification.
    #[tokio::test]
    async fn bad_second_digest_preserves_destination_and_removes_staging() {
        let server = MockServer::start().await;
        let card_uid =
            CardUid::new("01890f28-7c4a-7cc3-98e7-4f4a3c2d1b00").expect("test uid is valid");
        let first = b"verified-first";
        let second = b"corrupt-second";
        let first_digest = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(first));
        let second_digest =
            base64::engine::general_purpose::STANDARD.encode(Sha256::digest(second));
        Mock::given(method("POST"))
            .and(path("/auth/token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "test-access-token",
                "refresh_token": "unused-refresh-token",
                "token_type": "Bearer",
                "expires_in": 3600
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path(format!("/v1/cards/{card_uid}/artifacts")))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "artifacts": [
                    {
                        "relative_path": "first.bin",
                        "sha256": first_digest.clone(),
                        "size_bytes": first.len(),
                        "content_type": null
                    },
                    {
                        "relative_path": "nested/second.bin",
                        "sha256": second_digest.clone(),
                        "size_bytes": second.len(),
                        "content_type": null
                    }
                ]
            })))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/v1/cards/download/init"))
            .and(body_json(serde_json::json!({
                "card_uid": card_uid.clone(),
                "relative_path": "first.bin",
                "ttl_secs": null
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "plan": {
                    "get_url": format!("{}/download/first", server.uri()),
                    "ttl_secs": 0
                },
                "size_bytes": first.len(),
                "sha256": first_digest.clone()
            })))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/v1/cards/download/init"))
            .and(body_json(serde_json::json!({
                "card_uid": card_uid.clone(),
                "relative_path": "nested/second.bin",
                "ttl_secs": null
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "plan": {
                    "get_url": format!("{}/download/second", server.uri()),
                    "ttl_secs": 0
                },
                "size_bytes": second.len(),
                "sha256": first_digest.clone()
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/download/first"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(first))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/download/second"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(second))
            .mount(&server)
            .await;

        let parent = tempfile::tempdir().expect("test parent is created");
        let destination = parent.path().join("artifacts");
        std::fs::create_dir(&destination).expect("existing destination is created");
        std::fs::write(destination.join("existing.txt"), b"keep")
            .expect("existing publication is written");
        let cards = Cards::new(test_client(&server));

        let error = cards
            .download_artifacts_to(&card_uid, &destination)
            .await
            .expect_err("bad second digest must reject the publication");

        assert!(matches!(
            error,
            wyrd_spec::error::WyrdError::RegistryArtifactVerifyFailed { .. }
        ));
        assert_eq!(
            std::fs::read(destination.join("existing.txt"))
                .expect("existing publication remains readable"),
            b"keep"
        );
        let staging_remains = std::fs::read_dir(parent.path())
            .expect("test parent is readable")
            .filter_map(Result::ok)
            .any(|entry| {
                entry
                    .file_name()
                    .to_string_lossy()
                    .starts_with(".wyrd-artifacts-")
            });
        assert!(!staging_remains);
    }

    /// One declared envelope for each Card kind `cards.get` types, paired
    /// with its kind so the stub server can answer the matching exact read.
    ///
    /// The Verifier carries a building Drift baseline so the status projection
    /// is exercised alongside the spec projection.
    fn supported_kind_envelopes() -> Vec<(CardKind, serde_json::Value)> {
        let baseline_ref = serde_json::json!({
            "kind": "Data",
            "name": "churn-training",
            "space": "retention",
            "version": "1.0.0",
            "uid": "01890f28-7c4a-7cc3-98e7-4f4a3c2d1b01"
        });
        let specs = [
            (
                CardKind::Data,
                serde_json::json!({
                    "interface": {"kind": "Parquet", "meta": {"compression": "Snappy"}},
                    "schema": {"columns": [{"name": "feature", "dtype": "float64"}]},
                    "stats": {"row_count": 1, "col_count": 1, "byte_count": 8, "sha256": "00"}
                }),
            ),
            (
                CardKind::Model,
                serde_json::json!({
                    "interface": {"kind": "Sklearn", "meta": {"framework_version": "1.4.0"}},
                    "task_type": "BinaryClassification",
                    "signature": {
                        "inputs": [{"name": "feature", "dtype": "float64"}],
                        "outputs": [{"name": "prediction", "dtype": "float64"}]
                    }
                }),
            ),
            (
                CardKind::Prompt,
                serde_json::json!({
                    "provider": "openai",
                    "model": "gpt-4o",
                    "messages": [{"role": "user", "content": "hi"}]
                }),
            ),
            (
                CardKind::Agent,
                serde_json::json!({
                    "prompt": {"kind": "Prompt", "name": "triage", "space": "retention", "version": "1.0.0"},
                    "execution_route": {"kind": "native"}
                }),
            ),
            (
                CardKind::Verifier,
                serde_json::json!({
                    "inputs": {"current": {"type": "samples", "features": ["feature"]}},
                    "requirements": [{
                        "id": "feature-stable",
                        "statement": "The feature keeps its training distribution.",
                        "check": {
                            "kind": "drift",
                            "on": "inputs.current",
                            "method": "Psi",
                            "signal": {
                                "kind": "Distribution",
                                "baseline_ref": baseline_ref.clone(),
                                "features": ["feature"]
                            },
                            "condition": {"kind": "Statistical"},
                            "profile": {
                                "kind": "Psi",
                                "binning_strategy": {"kind": "Quantile", "n_bins": 10},
                                "threshold": {"kind": "Fixed", "value": 0.25}
                            }
                        }
                    }]
                }),
            ),
            (
                CardKind::Service,
                serde_json::json!({"description": "churn remediation"}),
            ),
            (
                CardKind::Trigger,
                serde_json::json!({"kind": "schedule", "cron": "*/5 * * * *", "tz": "UTC"}),
            ),
            (
                CardKind::Operator,
                serde_json::json!({
                    "kind": "notify",
                    "channel": {
                        "kind": "slack",
                        "connection": "ops-slack",
                        "channel_id": "C0123456789",
                        "text": "drift"
                    }
                }),
            ),
        ];
        specs
            .into_iter()
            .map(|(kind, spec)| {
                let status = if kind == CardKind::Verifier {
                    serde_json::json!({
                        "phase": "active",
                        "verification": {"baseline": {"state": "building", "data": baseline_ref.clone()}}
                    })
                } else {
                    serde_json::json!({"phase": "active"})
                };
                let card = serde_json::json!({
                    "apiVersion": "wyrd/v1",
                    "kind": kind.wire_name(),
                    "metadata": {"space": "retention", "name": "subject", "version": "1.0.0"},
                    "spec": spec,
                    "status": status
                });
                (kind, card)
            })
            .collect()
    }

    /// Every kind `cards.get` supports deserializes into its own typed `Spec`
    /// variant, and a Drift Verifier's baseline state arrives typed on
    /// `status.verification`.
    #[tokio::test]
    async fn supported_kinds_project_typed_specs_and_status() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/auth/token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "test-access-token",
                "refresh_token": "unused-refresh-token",
                "token_type": "Bearer",
                "expires_in": 3600
            })))
            .mount(&server)
            .await;
        let envelopes = supported_kind_envelopes();
        for (kind, card) in &envelopes {
            Mock::given(method("GET"))
                .and(path("/v1/cards/by-ref"))
                .and(query_param("kind", kind.wire_name()))
                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "card": card,
                    "created_at": "2026-01-01T00:00:00Z",
                    "updated_at": "2026-01-01T00:00:00Z"
                })))
                .mount(&server)
                .await;
        }
        let cards = Cards::new(test_client(&server));

        for (kind, _) in envelopes {
            let card_ref: CardRef = format!("retention/{}/subject@1.0.0", kind.wire_name())
                .parse()
                .expect("test card ref is valid");
            let card = cards
                .get(CardSelector::exact(card_ref))
                .await
                .unwrap_or_else(|error| panic!("{kind:?} card is readable: {error}"));
            let typed = matches!(
                (&kind, &card.spec),
                (CardKind::Data, Spec::Data(_))
                    | (CardKind::Model, Spec::Model(_))
                    | (CardKind::Prompt, Spec::Prompt(_))
                    | (CardKind::Agent, Spec::Agent(_))
                    | (CardKind::Verifier, Spec::Verifier(_))
                    | (CardKind::Service, Spec::Service(_))
                    | (CardKind::Trigger, Spec::Trigger(_))
                    | (CardKind::Operator, Spec::Operator(_))
            );
            assert!(typed, "{kind:?} projects its own typed spec");
            let baseline = card
                .status
                .as_ref()
                .and_then(|status| status.verification.as_ref())
                .and_then(|verification| verification.baseline.as_ref());
            if kind == CardKind::Verifier {
                let baseline = baseline.expect("drift verifier carries a typed baseline");
                assert_eq!(baseline.state, DriftBaselineState::Building);
            } else {
                assert!(baseline.is_none(), "{kind:?} carries no baseline");
            }
        }
    }

    /// `Cards::pull` publishes a declared Service's graph as a bundle
    /// that `WyrdState::from_path` loads with the root the server returned.
    ///
    /// # Panics
    /// Panics when the pull fails, the bundle does not load, or the loaded
    /// root differs from the declared Card.
    #[tokio::test]
    async fn pull_publishes_a_bundle_the_state_loads() {
        let server = MockServer::start().await;
        let uid = "01890f28-7c4a-7cc3-98e7-4f4a3c2d1b00";
        Mock::given(method("POST"))
            .and(path("/auth/token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "test-access-token",
                "refresh_token": "unused-refresh-token",
                "token_type": "Bearer",
                "expires_in": 3600
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/v1/cards/by-ref"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "card": {
                    "apiVersion": "wyrd/v1",
                    "kind": "Service",
                    "metadata": {
                        "space": "retention",
                        "name": "subject",
                        "version": "1.0.0",
                        "uid": uid
                    },
                    "spec": {"description": "churn remediation"},
                    "status": {"phase": "active"}
                },
                "created_at": "2026-01-01T00:00:00Z",
                "updated_at": "2026-01-01T00:00:00Z"
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path(format!("/v1/cards/{uid}/artifacts")))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"artifacts": []})),
            )
            .mount(&server)
            .await;
        let cards = Cards::new(test_client(&server));
        let parent = tempfile::tempdir().expect("test parent is created");
        let destination = parent.path().join("bundle");
        let card_ref: CardRef = "retention/Service/subject@1.0.0"
            .parse()
            .expect("test card ref is valid");

        let summary = cards
            .pull(
                CardSelector::exact(card_ref),
                &destination,
                BundleMode::Complete,
            )
            .await
            .expect("the declared graph pulls");
        let state =
            crate::state::WyrdState::from_path(&destination).expect("the published bundle loads");

        assert_eq!(summary.card_count, 1);
        assert_eq!(
            state.root_ref().uid.as_ref().map(ToString::to_string),
            Some(uid.to_owned())
        );
    }

    /// Keep latest and exact selector construction semantically distinct.
    #[test]
    fn selector_constructors_keep_latest_and_exact_distinct() {
        let kind = CardKind::Prompt;
        let space = SpaceName::new("prod").expect("test space is valid");
        let name = CardName::new("prompt").expect("test name is valid");
        let latest = CardSelector::named(kind.clone(), space.clone(), name.clone());
        assert!(matches!(latest, CardSelector::Named { version: None, .. }));
        let exact =
            latest.with_version(VersionBlock::parse("1.0.0").expect("test version is valid"));
        assert!(matches!(
            exact,
            CardSelector::Named {
                version: Some(_),
                ..
            }
        ));
        let uid = CardUid::new("01890f28-7c4a-7cc3-98e7-4f4a3c2d1b00").expect("test uid is valid");
        assert!(matches!(
            CardSelector::uid(kind, uid),
            CardSelector::Uid { .. }
        ));
    }
}