photoforge 0.1.0

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

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::time::Duration;

use reqwest::blocking::Client;
use reqwest::redirect::Policy;
use serde::{Deserialize, Serialize};

mod archive;
mod commons;
mod image;

pub use archive::{inspect_archive, verify_archive};

const DEFAULT_DISCOVERY_LIMIT: usize = 20;
const MAX_DISCOVERY_LIMIT: usize = 50;
const DEFAULT_MAX_DOWNLOAD_BYTES: u64 = 256 * 1024 * 1024;

/// Hard upper bound for every retained or publicly verified image.
///
/// Caller archive limits may be lower, but never higher, than 512 MiB.
pub const MAX_RETAINED_IMAGE_BYTES: u64 = 512 * 1024 * 1024;

/// Wikimedia Commons guidance for reusing content outside Wikimedia projects.
pub const COMMONS_REUSE_URL: &str =
    "https://commons.wikimedia.org/wiki/Commons:Reusing_content_outside_Wikimedia";

/// Exact contents of the package-included autonomous-agent guide.
pub const AGENT_GUIDE: &str = include_str!("../AGENT_GUIDE.md");

/// Result type returned by PhotoForge.
pub type Result<T> = std::result::Result<T, PhotoForgeError>;

/// A PhotoForge validation, provider, transfer, or archive failure.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PhotoForgeError {
    /// Discovery text or a Commons file URL was empty, malformed, or unsafe.
    #[error("invalid photo target: {0}")]
    InvalidTarget(String),
    /// A client or archive option was invalid.
    #[error("invalid PhotoForge option: {0}")]
    InvalidOption(String),
    /// Wikimedia Commons returned a non-success HTTP status.
    #[error("{provider} API returned HTTP {status}: {body}")]
    ProviderApi {
        /// Stable provider slug.
        provider: &'static str,
        /// HTTP status code.
        status: u16,
        /// Bounded provider diagnostic.
        body: String,
    },
    /// Wikimedia Commons returned an Action API error envelope.
    #[error("{provider} API error {code}: {info}")]
    ProviderApiError {
        /// Stable provider slug.
        provider: &'static str,
        /// Action API error code.
        code: String,
        /// Bounded Action API diagnostic.
        info: String,
    },
    /// An exact file was absent or outside the automatic license/format policy.
    #[error("{provider} file '{photo}' was not found or is not eligible")]
    NotFound {
        /// Stable provider slug.
        provider: &'static str,
        /// Requested file title.
        photo: String,
    },
    /// A provider URL crossed a scheme, host, path, port, or credential boundary.
    #[error("refusing untrusted photo URL '{0}'")]
    UntrustedUrl(String),
    /// A local archive path was unsafe.
    #[error("refusing unsafe photo path '{0}'")]
    UnsafePath(String),
    /// A download exceeded its configured nonzero cap.
    #[error("photo download is {size} bytes, exceeding the {limit} byte limit")]
    DownloadLimitExceeded {
        /// Observed or advertised bytes.
        size: u64,
        /// Configured byte limit.
        limit: u64,
    },
    /// A provider response or manifest exceeded an internal bound.
    #[error("{label} is {size} bytes, exceeding the {limit} byte limit")]
    ResponseLimitExceeded {
        /// Kind of bounded data.
        label: String,
        /// Observed bytes.
        size: u64,
        /// Allowed bytes.
        limit: u64,
    },
    /// Metadata, image structure, or archived integrity evidence was inconsistent.
    #[error("photo verification failed for '{path}': {message}")]
    VerificationFailed {
        /// File identity or local path.
        path: String,
        /// Validation detail.
        message: String,
    },
    /// Existing output could not be attributed to PhotoForge and was preserved.
    #[error("refusing to replace unrecognized output '{}': {reason}", path.display())]
    UnrecognizedExistingOutput {
        /// Existing destination.
        path: PathBuf,
        /// Recognition failure.
        reason: String,
    },
    /// Staging, recovery, installation, rollback, or durability failed.
    #[error("archive transaction failed for '{}': {message}", path.display())]
    ArchiveTransaction {
        /// Destination or transaction path.
        path: PathBuf,
        /// Transaction detail.
        message: String,
    },
    /// The requested output root exists but is not a regular directory.
    #[error("output path '{}' is not a directory", .0.display())]
    OutputNotDirectory(PathBuf),
    /// Filesystem failure.
    #[error("I/O error: {0}")]
    Io(#[from] io::Error),
    /// HTTP transport failure.
    #[error("request error: {0}")]
    Request(String),
    /// JSON decoding failure.
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
}

impl From<reqwest::Error> for PhotoForgeError {
    fn from(error: reqwest::Error) -> Self {
        Self::Request(commons::error_chain(&error))
    }
}

/// Official photo providers supported by this release.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PhotoProvider {
    /// Wikimedia Commons through its official Action API.
    WikimediaCommons,
}

impl PhotoProvider {
    /// Stable provider list.
    pub const ALL: [Self; 1] = [Self::WikimediaCommons];

    /// Stable machine-readable provider name.
    #[must_use]
    pub const fn slug(self) -> &'static str {
        match self {
            Self::WikimediaCommons => "wikimedia-commons",
        }
    }

    /// Human-readable provider name.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::WikimediaCommons => "Wikimedia Commons",
        }
    }
}

impl fmt::Display for PhotoProvider {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.slug())
    }
}

/// A typed Wikimedia Commons discovery target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "kind", content = "value")]
pub enum PhotoTarget {
    /// Bounded literal free-text search.
    Search(String),
    /// Direct exact Commons category, with or without the `Category:` prefix.
    Category(String),
    /// Exact Commons file title, with or without the `File:` prefix.
    File(String),
    /// A bounded slice of the Commons featured-picture category, ranked locally.
    Top,
    /// Newest eligible files in a bounded newest-first raw Commons window.
    Latest,
}

impl PhotoTarget {
    /// Whether the target can produce more than one candidate.
    #[must_use]
    pub const fn is_collection(&self) -> bool {
        !matches!(self, Self::File(_))
    }
}

/// Parse bare search text, typed prefixes, aliases, or one canonical Commons file URL.
///
/// Only an HTTPS `commons.wikimedia.org/wiki/File:...` URL without credentials,
/// a fragment, a query, or a nonstandard port is accepted as a URL target.
pub fn parse_photo_target(input: &str) -> Result<PhotoTarget> {
    commons::parse_target(input)
}

/// License, creator, attribution, and restriction evidence from Commons.
///
/// These fields are retained evidence and do not guarantee that the uploader
/// owned every relevant right or that the intended use is lawful.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PhotoRights {
    /// Normalized automatic-scope identifier: CC0-1.0, CC-BY-4.0, or CC-BY-SA-4.0.
    pub license: String,
    /// Canonical exact Creative Commons HTTPS URL.
    pub license_url: String,
    /// Plain-text provider license label.
    pub raw_license_label: String,
    /// Plain-text creator (`Artist`) evidence.
    pub creator: String,
    /// Plain-text custom `Attribution` supplied by Commons.
    pub custom_attribution: String,
    /// Selected attribution line; callers must still review its sufficiency.
    pub attribution: String,
    /// Plain-text source `Credit`; `Own work` is never treated as a creator.
    pub source_credit: String,
    /// Plain-text `Permission` metadata. Automatic-scope results require this to be empty.
    pub permission: String,
    /// Plain-text provider usage terms, strictly cross-checked when nonempty.
    pub usage_terms: String,
    /// Raw plain-text `AttributionRequired` metadata, strictly parsed when nonempty.
    pub raw_attribution_required: String,
    /// Whether the accepted license requires attribution.
    pub attribution_required: bool,
    /// Plain-text `Restrictions` metadata. Automatic-scope results require this to be empty.
    pub restrictions: String,
    /// Plain-text `Copyrighted` metadata retained for contradiction checks.
    pub copyrighted: String,
    /// Plain-text `NonFree` metadata retained for contradiction checks.
    pub non_free: String,
    /// Plain-text `DeletionReason`; automatic-scope results require this to be empty.
    pub deletion_reason: String,
    /// UNIX timestamp when Commons metadata was retrieved.
    pub metadata_retrieved_at: u64,
    /// Wikimedia Commons reuse guidance, not a substitute for source review.
    pub provider_guidance_url: String,
}

/// Current original Commons bitmap and revision evidence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PhotoFile {
    /// Exact original download URL on `upload.wikimedia.org`.
    pub url: String,
    /// Exact byte length reported by Commons, never above the 512 MiB hard limit.
    pub size: u64,
    /// Lowercase Commons SHA-1 digest.
    pub sha1: String,
    /// Accepted MIME type (`image/jpeg` or `image/png`).
    pub mime: String,
    /// Commons media type; accepted summaries always contain `BITMAP`.
    pub media_type: String,
    /// Pixel width.
    pub width: u32,
    /// Pixel height.
    pub height: u32,
    /// Current page revision ID when supplied by Commons.
    pub revision_id: Option<u64>,
    /// Current image revision timestamp when supplied by Commons.
    pub revision_timestamp: Option<String>,
}

/// One eligible Commons result with archival and source-review evidence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PhotoSummary {
    /// Owning provider.
    pub provider: PhotoProvider,
    /// Stable numeric Commons page ID.
    pub id: u64,
    /// Canonical Commons file title.
    pub title: String,
    /// Plain-text `ObjectName`, when supplied.
    pub object_name: String,
    /// Bounded plain-text image description.
    pub description: String,
    /// Commons category labels without the `Category:` prefix.
    pub categories: Vec<String>,
    /// Bounded provider assessment labels, such as featured or quality evidence.
    pub assessments: Vec<String>,
    /// Number of bounded global-usage records observed.
    pub usage_count: u64,
    /// Whether global-usage continuation completed within the request bound.
    pub usage_count_complete: bool,
    /// Canonical human-facing Commons file page.
    pub source_url: String,
    /// Strict license and attribution evidence.
    pub rights: PhotoRights,
    /// Current original bitmap evidence.
    pub file: PhotoFile,
}

/// Detailed evidence about bounded provider discovery and local eligibility.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiscoveryResult {
    /// Eligible, locally ranked results, limited by the client setting.
    pub photos: Vec<PhotoSummary>,
    /// Unique valid candidate IDs whose metadata was requested.
    pub candidate_count: usize,
    /// Candidates passing format, dimensions, URL, rights, and metadata policy.
    pub eligible_candidate_count: usize,
    /// Maximum provider-order raw window before ID deduplication.
    pub candidate_budget: usize,
    /// Whether provider continuation indicates additional candidates existed.
    pub candidate_cap_reached: bool,
}

/// Archive destination and byte-bound policy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArchiveOptions {
    /// Runtime-local root containing one numeric page-ID directory per photo.
    pub output: PathBuf,
    /// Fully verify and skip a fresh, nonvolatile metadata match.
    pub skip_existing: bool,
    /// Nonzero per-photo transfer cap no greater than [`MAX_RETAINED_IMAGE_BYTES`].
    pub max_download_bytes: u64,
}

impl Default for ArchiveOptions {
    fn default() -> Self {
        Self {
            output: PathBuf::from("photos"),
            skip_existing: false,
            max_download_bytes: DEFAULT_MAX_DOWNLOAD_BYTES,
        }
    }
}

/// Integrity evidence for the one image file in an archive.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PhotoIntegrity {
    /// Safe direct-child path (`photo.jpg` or `photo.png`).
    pub path: String,
    /// Exact retained bytes.
    pub bytes: u64,
    /// Lowercase local BLAKE3 digest.
    pub blake3: String,
    /// Lowercase Commons SHA-1 digest verified during transfer and inspection.
    pub commons_sha1: String,
}

/// Persistent, portable PhotoForge archive manifest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PhotoManifest {
    /// Manifest format version; version 0.1 writes `1`.
    pub format_version: String,
    /// Explicit archive ownership marker; version 0.1 writes `photoforge`.
    pub owner: String,
    /// Full fresh source, rights, revision, and file summary.
    pub photo: PhotoSummary,
    /// Verified local and provider integrity evidence.
    pub integrity: PhotoIntegrity,
    /// Marker written only for a complete staged archive.
    pub complete: bool,
}

/// One newly installed, repaired, or fully verified skipped photo archive.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArchivedPhoto {
    /// Commons numeric page ID.
    pub photo_id: u64,
    /// Canonical runtime-local archive directory; this `PathBuf` is not portable evidence.
    pub output: PathBuf,
    /// Exact retained image bytes.
    pub bytes_written: u64,
    /// Fully verified manifest.
    pub manifest: PhotoManifest,
}

/// One selected photo that could not be archived.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArchiveFailure {
    /// Selected Commons page ID.
    pub photo_id: u64,
    /// Runtime-local intended destination when it could be safely formed.
    pub output: Option<PathBuf>,
    /// Bounded diagnostic.
    pub message: String,
}

/// Aggregate result after every selected unique page ID was attempted.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArchiveSummary {
    /// Number of selected unique page IDs.
    pub selected: usize,
    /// Exact unique page IDs in first-selected order.
    pub selected_ids: Vec<u64>,
    /// Number newly installed or repaired.
    pub archived: usize,
    /// Number fully verified and skipped.
    pub skipped: usize,
    /// Number of accumulated per-photo failures.
    pub failed: usize,
    /// Newly downloaded bytes.
    pub bytes_written: u64,
    /// Full records for newly installed or repaired photos.
    pub photos: Vec<ArchivedPhoto>,
    /// Full verified records for every claimed skip.
    pub skipped_photos: Vec<ArchivedPhoto>,
    /// Per-photo failures.
    pub failures: Vec<ArchiveFailure>,
}

impl ArchiveSummary {
    /// Whether every selected unique photo archived or verified successfully.
    #[must_use]
    pub fn is_success(&self) -> bool {
        self.failures.is_empty()
    }
}

/// Current phase of a synchronous archive operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArchiveProgressPhase {
    /// Output validation and aggregate setup.
    Starting,
    /// Original bytes are being streamed.
    Downloading,
    /// Staged or existing bytes are being fully verified.
    Verifying,
    /// A staged archive is being installed transactionally.
    Installing,
    /// One fully verified existing archive was skipped.
    Skipped,
    /// One selected photo failed independently.
    Failed,
    /// Every selected unique photo was attempted.
    Completed,
}

/// Bounded aggregate and active-photo progress snapshot.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArchiveProgress {
    /// Current operation phase.
    pub phase: ArchiveProgressPhase,
    /// Selected unique photo count.
    pub total_photos: usize,
    /// Completed archive, skip, or failure attempts.
    pub completed_photos: usize,
    /// Newly archived or repaired count.
    pub archived_photos: usize,
    /// Fully verified skip count.
    pub skipped_photos: usize,
    /// Failure count.
    pub failed_photos: usize,
    /// Newly downloaded bytes, including the active transfer.
    pub bytes_written: u64,
    /// Active Commons page ID.
    pub active_photo_id: Option<u64>,
    /// Bounded active title.
    pub active_title: Option<String>,
    /// Fixed active relative output path.
    pub active_file: Option<String>,
    /// Active downloaded bytes.
    pub active_bytes_written: u64,
    /// Exact Commons byte length for the active transfer.
    pub active_total_bytes: Option<u64>,
}

/// Blocking, redirect-free, no-system-proxy Wikimedia Commons client.
#[derive(Clone)]
pub struct PhotoForge {
    pub(crate) provider: PhotoProvider,
    pub(crate) client: Client,
    pub(crate) discovery_limit: usize,
}

impl PhotoForge {
    /// Build a redirect-free, no-system-proxy Commons client with a required User-Agent.
    pub fn with_user_agent(user_agent: &str) -> Result<Self> {
        let user_agent = user_agent.trim();
        if user_agent.is_empty() {
            return Err(PhotoForgeError::InvalidOption(
                "User-Agent must not be blank".to_string(),
            ));
        }
        if user_agent.len() > 512 || user_agent.chars().any(char::is_control) {
            return Err(PhotoForgeError::InvalidOption(
                "User-Agent must contain at most 512 bytes and no control characters".to_string(),
            ));
        }
        let client = Client::builder()
            .user_agent(user_agent)
            .redirect(Policy::none())
            .no_proxy()
            .connect_timeout(Duration::from_secs(20))
            .timeout(Duration::from_secs(90))
            .build()?;
        Ok(Self {
            provider: PhotoProvider::WikimediaCommons,
            client,
            discovery_limit: DEFAULT_DISCOVERY_LIMIT,
        })
    }

    /// Set the result limit, clamped to 1 through 50.
    #[must_use]
    pub fn with_discovery_limit(mut self, limit: usize) -> Self {
        self.discovery_limit = limit.clamp(1, MAX_DISCOVERY_LIMIT);
        self
    }

    /// Provider used by this client.
    #[must_use]
    pub const fn provider(&self) -> PhotoProvider {
        self.provider
    }

    /// Discover eligible Commons JPEG and PNG files.
    pub fn discover(&self, target: &PhotoTarget) -> Result<Vec<PhotoSummary>> {
        Ok(self.discover_detailed(target)?.photos)
    }

    /// Discover files with explicit bounded-candidate evidence.
    pub fn discover_detailed(&self, target: &PhotoTarget) -> Result<DiscoveryResult> {
        commons::discover(self, target)
    }

    /// Archive every selected unique page ID and accumulate per-photo failures.
    pub fn archive(
        &self,
        photos: &[PhotoSummary],
        options: &ArchiveOptions,
    ) -> Result<ArchiveSummary> {
        archive::archive(self, photos, options, None)
    }

    /// Archive with synchronous bounded progress snapshots.
    pub fn archive_with_progress<F>(
        &self,
        photos: &[PhotoSummary],
        options: &ArchiveOptions,
        mut progress: F,
    ) -> Result<ArchiveSummary>
    where
        F: FnMut(ArchiveProgress),
    {
        archive::archive(self, photos, options, Some(&mut progress))
    }

    /// Read and fully verify one PhotoForge archive directory.
    pub fn inspect_archive(&self, directory: impl AsRef<Path>) -> Result<PhotoManifest> {
        inspect_archive(directory)
    }

    /// Fully verify one PhotoForge archive directory.
    pub fn verify_archive(&self, directory: impl AsRef<Path>) -> Result<PhotoManifest> {
        verify_archive(directory)
    }
}

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

    #[test]
    fn client_requires_a_bounded_clean_user_agent_and_clamps_limit() {
        assert!(PhotoForge::with_user_agent("").is_err());
        assert!(PhotoForge::with_user_agent("bad\nagent").is_err());
        let forge = PhotoForge::with_user_agent("photoforge-test/0.1 (test@example.invalid)")
            .unwrap()
            .with_discovery_limit(0);
        assert_eq!(forge.discovery_limit, 1);
        assert_eq!(forge.provider(), PhotoProvider::WikimediaCommons);
        assert_eq!(PhotoProvider::ALL, [PhotoProvider::WikimediaCommons]);
    }

    #[test]
    fn archive_defaults_are_bounded_and_photo_native() {
        let options = ArchiveOptions::default();
        assert_eq!(options.output, PathBuf::from("photos"));
        assert!(!options.skip_existing);
        assert_eq!(options.max_download_bytes, 256 * 1024 * 1024);
    }

    #[test]
    fn embedded_guide_is_exact() {
        assert_eq!(AGENT_GUIDE.as_bytes(), include_bytes!("../AGENT_GUIDE.md"));
    }

    #[test]
    fn public_provider_target_and_progress_json_names_are_stable() {
        assert_eq!(
            serde_json::to_string(&PhotoProvider::WikimediaCommons).unwrap(),
            "\"wikimedia-commons\""
        );
        assert_eq!(
            serde_json::to_value(PhotoTarget::Search("blue flower".to_string())).unwrap(),
            serde_json::json!({"kind":"search","value":"blue flower"})
        );
        assert_eq!(
            serde_json::to_value(PhotoTarget::Top).unwrap(),
            serde_json::json!({"kind":"top"})
        );
        assert_eq!(
            serde_json::from_value::<PhotoTarget>(serde_json::json!({
                "kind":"category",
                "value":"Flowers"
            }))
            .unwrap(),
            PhotoTarget::Category("Flowers".to_string())
        );
        for (phase, expected) in [
            (ArchiveProgressPhase::Starting, "starting"),
            (ArchiveProgressPhase::Downloading, "downloading"),
            (ArchiveProgressPhase::Verifying, "verifying"),
            (ArchiveProgressPhase::Installing, "installing"),
            (ArchiveProgressPhase::Skipped, "skipped"),
            (ArchiveProgressPhase::Failed, "failed"),
            (ArchiveProgressPhase::Completed, "completed"),
        ] {
            assert_eq!(serde_json::to_value(phase).unwrap(), expected);
            assert_eq!(
                serde_json::from_value::<ArchiveProgressPhase>(serde_json::json!(expected))
                    .unwrap(),
                phase
            );
        }
    }
}