Skip to main content

devimg_core/
ai.rs

1use std::collections::BTreeSet;
2use std::path::{Path, PathBuf};
3
4use serde::{Deserialize, Serialize};
5
6use crate::config::{project_relative, resolve_project_path_checked, Config};
7use crate::manifest::{read_manifest, Manifest};
8use crate::pipeline::path_to_string;
9use crate::quality::manifest_quality_warnings;
10use crate::{scan_sources, Result};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
13#[serde(rename_all = "kebab-case")]
14pub enum AiProvider {
15    Openai,
16    Anthropic,
17}
18
19impl AiProvider {
20    pub fn label(self) -> &'static str {
21        match self {
22            Self::Openai => "openai",
23            Self::Anthropic => "anthropic",
24        }
25    }
26
27    pub fn credential_env_var(self) -> &'static str {
28        match self {
29            Self::Openai => "OPENAI_API_KEY",
30            Self::Anthropic => "ANTHROPIC_API_KEY",
31        }
32    }
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct AiConsentOptions {
37    pub provider: AiProvider,
38    pub model: String,
39    pub command: String,
40    pub config_path: PathBuf,
41    pub dry_run: bool,
42    pub include_images: bool,
43    pub output_path: Option<PathBuf>,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
47pub struct AiConsentPreview {
48    pub provider: AiProvider,
49    pub model: String,
50    pub command: String,
51    pub config_path: String,
52    pub project_root: String,
53    pub mode: String,
54    pub dry_run: bool,
55    pub paths_included: bool,
56    pub image_bytes_included: bool,
57    pub output_path: Option<String>,
58    pub manifest_path: String,
59    pub report_path: String,
60    pub manifest_readable: bool,
61    pub source_files: Vec<AiSelectedFile>,
62    pub generated_outputs: Vec<AiGeneratedOutput>,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
66pub struct AiSelectedFile {
67    pub source_name: String,
68    pub path: String,
69    pub role: String,
70    pub width: u32,
71    pub height: u32,
72    pub format: String,
73    pub bytes: u64,
74    pub hash: String,
75    pub image_bytes_included: bool,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
79pub struct AiGeneratedOutput {
80    pub source_path: String,
81    pub output_path: String,
82    pub preset: String,
83    pub fit: String,
84    pub width: u32,
85    pub height: u32,
86    pub format: String,
87    pub bytes: u64,
88    pub hash: String,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
92pub struct AiProviderResponse {
93    pub provider: AiProvider,
94    pub model: String,
95    pub request_kind: String,
96    pub network_called: bool,
97    pub selected_file_count: usize,
98    pub generated_output_count: usize,
99}
100
101pub trait AiProviderClient {
102    fn consent_response(&self, preview: &AiConsentPreview) -> AiProviderResponse;
103}
104
105pub trait AiReviewProviderClient {
106    fn review(&self, request: &AiReviewRequest) -> Result<AiReviewProviderPayload>;
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub struct MockAiProviderClient {
111    provider: AiProvider,
112}
113
114impl MockAiProviderClient {
115    pub fn new(provider: AiProvider) -> Self {
116        Self { provider }
117    }
118}
119
120impl AiProviderClient for MockAiProviderClient {
121    fn consent_response(&self, preview: &AiConsentPreview) -> AiProviderResponse {
122        AiProviderResponse {
123            provider: self.provider,
124            model: preview.model.clone(),
125            request_kind: "consent-preview".to_string(),
126            network_called: false,
127            selected_file_count: preview.source_files.len(),
128            generated_output_count: preview.generated_outputs.len(),
129        }
130    }
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct AiReviewOptions {
135    pub provider: AiProvider,
136    pub model: String,
137    pub command: String,
138    pub manifest_path: PathBuf,
139    pub project_root: PathBuf,
140    pub dry_run: bool,
141    pub include_images: bool,
142    pub image_detail: String,
143    pub max_images: usize,
144    pub ai_output_path: Option<PathBuf>,
145    pub markdown_path: Option<PathBuf>,
146}
147
148#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
149pub struct AiReviewRequest {
150    pub schema_version: u32,
151    pub provider: AiProvider,
152    pub model: String,
153    pub command: String,
154    pub manifest_path: String,
155    pub project_root: String,
156    pub mode: String,
157    pub dry_run: bool,
158    pub paths_included: bool,
159    pub image_bytes_included: bool,
160    pub image_detail: String,
161    pub max_images: usize,
162    pub ai_output_path: Option<String>,
163    pub markdown_path: Option<String>,
164    pub manifest_summary: AiReviewManifestSummary,
165    pub review_signals: Vec<String>,
166    pub outputs: Vec<AiReviewOutput>,
167    pub selected_images: Vec<AiReviewImageInput>,
168    pub skipped_image_count: usize,
169}
170
171#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
172pub struct AiReviewManifestSummary {
173    pub config_path: String,
174    pub config_hash: String,
175    pub source_count: usize,
176    pub output_count: usize,
177    pub source_bytes: u64,
178    pub output_bytes: u64,
179}
180
181#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
182pub struct AiReviewOutput {
183    pub source_path: String,
184    pub output_path: String,
185    pub preset: String,
186    pub fit: String,
187    pub width: u32,
188    pub height: u32,
189    pub format: String,
190    pub bytes: u64,
191    pub hash: String,
192    pub source_width: u32,
193    pub source_height: u32,
194    pub source_bytes: u64,
195    pub image_bytes_included: bool,
196    pub image_detail: Option<String>,
197}
198
199#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
200pub struct AiReviewImageInput {
201    pub output_path: String,
202    pub mime_type: String,
203    pub width: u32,
204    pub height: u32,
205    pub bytes: u64,
206    pub hash: String,
207    pub detail: String,
208}
209
210#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
211pub struct AiReviewProviderPayload {
212    #[serde(default)]
213    pub summary: String,
214    #[serde(default)]
215    pub observations: Vec<AiReviewObservation>,
216}
217
218#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
219pub struct AiReviewObservation {
220    pub category: String,
221    pub severity: String,
222    pub source_path: String,
223    pub preset: String,
224    pub output_path: String,
225    pub rationale: String,
226    pub suggested_next_command: String,
227}
228
229#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
230pub struct AiReviewReport {
231    pub schema_version: u32,
232    pub provider: AiProvider,
233    pub model: String,
234    pub command: String,
235    pub manifest_path: String,
236    pub project_root: String,
237    pub mode: String,
238    pub dry_run: bool,
239    pub paths_included: bool,
240    pub image_bytes_included: bool,
241    pub image_detail: String,
242    pub max_images: usize,
243    pub ai_output_path: Option<String>,
244    pub markdown_path: Option<String>,
245    pub provider_called: bool,
246    pub summary: AiReviewSummary,
247    pub review_signals: Vec<String>,
248    pub outputs: Vec<AiReviewOutput>,
249    pub selected_images: Vec<AiReviewImageInput>,
250    pub provider_summary: String,
251    pub observations: Vec<AiReviewObservation>,
252}
253
254#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
255pub struct AiReviewSummary {
256    pub source_count: usize,
257    pub output_count: usize,
258    pub selected_image_count: usize,
259    pub skipped_image_count: usize,
260    pub review_signal_count: usize,
261    pub observation_count: usize,
262}
263
264#[derive(Debug, Clone, PartialEq, Eq)]
265pub struct MockAiReviewProviderClient {
266    provider: AiProvider,
267    fail: bool,
268}
269
270impl MockAiReviewProviderClient {
271    pub fn new(provider: AiProvider) -> Self {
272        Self {
273            provider,
274            fail: false,
275        }
276    }
277
278    pub fn failing(provider: AiProvider) -> Self {
279        Self {
280            provider,
281            fail: true,
282        }
283    }
284}
285
286impl AiReviewProviderClient for MockAiReviewProviderClient {
287    fn review(&self, request: &AiReviewRequest) -> Result<AiReviewProviderPayload> {
288        if self.fail {
289            return Err(crate::DevimgError::config(
290                &request.manifest_path,
291                "mock AI review provider failure",
292            ));
293        }
294
295        let first = request.outputs.first();
296        Ok(AiReviewProviderPayload {
297            summary: format!("mock {} AI review", self.provider.label()),
298            observations: first
299                .map(|output| {
300                    vec![AiReviewObservation {
301                        category: "format-quality concern".to_string(),
302                        severity: "advisory".to_string(),
303                        source_path: output.source_path.clone(),
304                        preset: output.preset.clone(),
305                        output_path: output.output_path.clone(),
306                        rationale: "Mock review observation for provider boundary tests."
307                            .to_string(),
308                        suggested_next_command: format!(
309                            "devimg review --manifest {} --output .devimg/review.html",
310                            request.manifest_path
311                        ),
312                    }]
313                })
314                .unwrap_or_default(),
315        })
316    }
317}
318
319pub fn build_ai_consent_preview(
320    config: &Config,
321    options: &AiConsentOptions,
322) -> Result<AiConsentPreview> {
323    let manifest_path =
324        resolve_project_path_checked(config, &config.project.manifest, "manifest path")?;
325    let report_path = resolve_project_path_checked(config, &config.project.report, "report path")?;
326    let sources = scan_sources(config)?;
327    let source_files = sources
328        .into_iter()
329        .map(|source| AiSelectedFile {
330            source_name: source.source_name,
331            path: source.project_path,
332            role: "source-image".to_string(),
333            width: source.width,
334            height: source.height,
335            format: source.format.label().to_string(),
336            bytes: source.bytes,
337            hash: source.hash,
338            image_bytes_included: options.include_images,
339        })
340        .collect();
341
342    let mut manifest_readable = false;
343    let mut generated_outputs = Vec::new();
344    if let Ok(manifest) = read_manifest(&manifest_path) {
345        manifest_readable = true;
346        let mut seen = BTreeSet::new();
347        for output in manifest.outputs {
348            if seen.insert(output.output_path.clone()) {
349                generated_outputs.push(AiGeneratedOutput {
350                    source_path: output.source_path,
351                    output_path: output.output_path,
352                    preset: output.preset,
353                    fit: output.fit,
354                    width: output.width,
355                    height: output.height,
356                    format: output.format,
357                    bytes: output.bytes,
358                    hash: output.hash,
359                });
360            }
361        }
362        generated_outputs.sort_by(|left, right| left.output_path.cmp(&right.output_path));
363    }
364
365    Ok(AiConsentPreview {
366        provider: options.provider,
367        model: options.model.clone(),
368        command: options.command.clone(),
369        config_path: path_to_string(&options.config_path),
370        project_root: display_path(&config.project.root),
371        mode: if options.include_images {
372            "include-images".to_string()
373        } else {
374            "metadata-only".to_string()
375        },
376        dry_run: options.dry_run,
377        paths_included: true,
378        image_bytes_included: options.include_images,
379        output_path: options.output_path.as_deref().map(path_to_string),
380        manifest_path: path_to_string(&project_relative(config, &manifest_path)),
381        report_path: path_to_string(&project_relative(config, &report_path)),
382        manifest_readable,
383        source_files,
384        generated_outputs,
385    })
386}
387
388pub fn ai_consent_preview_to_json(preview: &AiConsentPreview) -> String {
389    serde_json::to_string_pretty(preview).expect("AI consent preview serialization cannot fail")
390        + "\n"
391}
392
393pub fn build_ai_review_request(manifest: &Manifest, options: &AiReviewOptions) -> AiReviewRequest {
394    let max_images = options.max_images.max(1);
395    let image_detail = options.image_detail.clone();
396    let mut outputs = manifest
397        .outputs
398        .iter()
399        .map(|output| AiReviewOutput {
400            source_path: output.source_path.clone(),
401            output_path: output.output_path.clone(),
402            preset: output.preset.clone(),
403            fit: output.fit.clone(),
404            width: output.width,
405            height: output.height,
406            format: output.format.clone(),
407            bytes: output.bytes,
408            hash: output.hash.clone(),
409            source_width: output.source_width,
410            source_height: output.source_height,
411            source_bytes: output.source_bytes,
412            image_bytes_included: false,
413            image_detail: None,
414        })
415        .collect::<Vec<_>>();
416    outputs.sort_by(|left, right| {
417        left.source_path
418            .cmp(&right.source_path)
419            .then(left.preset.cmp(&right.preset))
420            .then(left.width.cmp(&right.width))
421            .then(left.height.cmp(&right.height))
422            .then(left.format.cmp(&right.format))
423            .then(left.output_path.cmp(&right.output_path))
424    });
425
426    let selected_images = if options.include_images {
427        outputs
428            .iter()
429            .filter_map(|output| {
430                ai_image_mime_type(&output.format).map(|mime_type| AiReviewImageInput {
431                    output_path: output.output_path.clone(),
432                    mime_type: mime_type.to_string(),
433                    width: output.width,
434                    height: output.height,
435                    bytes: output.bytes,
436                    hash: output.hash.clone(),
437                    detail: image_detail.clone(),
438                })
439            })
440            .take(max_images)
441            .collect::<Vec<_>>()
442    } else {
443        Vec::new()
444    };
445    let selected_paths = selected_images
446        .iter()
447        .map(|image| image.output_path.clone())
448        .collect::<BTreeSet<_>>();
449    for output in &mut outputs {
450        if selected_paths.contains(&output.output_path) {
451            output.image_bytes_included = true;
452            output.image_detail = Some(image_detail.clone());
453        }
454    }
455
456    let output_count = manifest.outputs.len();
457    let skipped_image_count = if options.include_images {
458        output_count.saturating_sub(selected_images.len())
459    } else {
460        0
461    };
462    let mode = if options.include_images {
463        "include-images"
464    } else {
465        "metadata-only"
466    };
467
468    AiReviewRequest {
469        schema_version: 1,
470        provider: options.provider,
471        model: options.model.clone(),
472        command: options.command.clone(),
473        manifest_path: display_project_path(&options.project_root, &options.manifest_path),
474        project_root: display_path(&options.project_root),
475        mode: mode.to_string(),
476        dry_run: options.dry_run,
477        paths_included: true,
478        image_bytes_included: options.include_images,
479        image_detail,
480        max_images,
481        ai_output_path: options
482            .ai_output_path
483            .as_deref()
484            .map(|path| display_project_path(&options.project_root, path)),
485        markdown_path: options
486            .markdown_path
487            .as_deref()
488            .map(|path| display_project_path(&options.project_root, path)),
489        manifest_summary: AiReviewManifestSummary {
490            config_path: manifest.config_path.clone(),
491            config_hash: manifest.config_hash.clone(),
492            source_count: manifest_source_count(manifest),
493            output_count,
494            source_bytes: manifest.source_bytes_total(),
495            output_bytes: manifest.output_bytes_total(),
496        },
497        review_signals: manifest_quality_warnings(manifest),
498        outputs,
499        selected_images,
500        skipped_image_count,
501    }
502}
503
504pub fn build_ai_review_report(
505    request: &AiReviewRequest,
506    payload: AiReviewProviderPayload,
507    provider_called: bool,
508) -> AiReviewReport {
509    let observations = payload
510        .observations
511        .into_iter()
512        .map(normalize_ai_review_observation)
513        .collect::<Vec<_>>();
514    AiReviewReport {
515        schema_version: request.schema_version,
516        provider: request.provider,
517        model: request.model.clone(),
518        command: request.command.clone(),
519        manifest_path: request.manifest_path.clone(),
520        project_root: request.project_root.clone(),
521        mode: request.mode.clone(),
522        dry_run: request.dry_run,
523        paths_included: request.paths_included,
524        image_bytes_included: request.image_bytes_included,
525        image_detail: request.image_detail.clone(),
526        max_images: request.max_images,
527        ai_output_path: request.ai_output_path.clone(),
528        markdown_path: request.markdown_path.clone(),
529        provider_called,
530        summary: AiReviewSummary {
531            source_count: request.manifest_summary.source_count,
532            output_count: request.manifest_summary.output_count,
533            selected_image_count: request.selected_images.len(),
534            skipped_image_count: request.skipped_image_count,
535            review_signal_count: request.review_signals.len(),
536            observation_count: observations.len(),
537        },
538        review_signals: request.review_signals.clone(),
539        outputs: request.outputs.clone(),
540        selected_images: request.selected_images.clone(),
541        provider_summary: payload.summary,
542        observations,
543    }
544}
545
546pub fn build_ai_review_dry_run_report(request: &AiReviewRequest) -> AiReviewReport {
547    build_ai_review_report(
548        request,
549        AiReviewProviderPayload {
550            summary: "Dry run only; no provider call was made.".to_string(),
551            observations: Vec::new(),
552        },
553        false,
554    )
555}
556
557pub fn ai_review_report_to_json(report: &AiReviewReport) -> String {
558    serde_json::to_string_pretty(report).expect("AI review report serialization cannot fail") + "\n"
559}
560
561pub fn render_ai_review_markdown(report: &AiReviewReport) -> String {
562    let mut out = String::new();
563    out.push_str("# DevImg AI Review\n\n");
564    out.push_str("AI observations are advisory and must be reviewed by a human before changing source images or configuration.\n\n");
565    out.push_str("## Summary\n\n");
566    out.push_str(&format!("- Provider: `{}`\n", report.provider.label()));
567    out.push_str(&format!("- Model: `{}`\n", report.model));
568    out.push_str(&format!("- Mode: `{}`\n", report.mode));
569    out.push_str(&format!("- Dry run: `{}`\n", report.dry_run));
570    out.push_str(&format!(
571        "- Provider called: `{}`\n",
572        report.provider_called
573    ));
574    out.push_str(&format!("- Manifest: `{}`\n", report.manifest_path));
575    out.push_str(&format!(
576        "- Outputs reviewed: `{}`\n",
577        report.summary.output_count
578    ));
579    out.push_str(&format!(
580        "- Image inputs selected: `{}`\n",
581        report.summary.selected_image_count
582    ));
583    out.push_str(&format!(
584        "- Observations: `{}`\n\n",
585        report.summary.observation_count
586    ));
587
588    if !report.review_signals.is_empty() {
589        out.push_str("## Deterministic Signals\n\n");
590        for signal in &report.review_signals {
591            out.push_str(&format!("- {signal}\n"));
592        }
593        out.push('\n');
594    }
595
596    out.push_str("## Observations\n\n");
597    if report.observations.is_empty() {
598        out.push_str("No AI observations.\n");
599    } else {
600        for observation in &report.observations {
601            out.push_str(&format!("### {}\n\n", observation.category));
602            out.push_str(&format!("- Severity: `{}`\n", observation.severity));
603            out.push_str(&format!("- Source: `{}`\n", observation.source_path));
604            out.push_str(&format!("- Preset: `{}`\n", observation.preset));
605            out.push_str(&format!("- Output: `{}`\n", observation.output_path));
606            out.push_str(&format!("- Rationale: {}\n", observation.rationale));
607            out.push_str(&format!(
608                "- Suggested next command: `{}`\n\n",
609                observation.suggested_next_command
610            ));
611        }
612    }
613    out
614}
615
616pub fn ai_image_mime_type(format: &str) -> Option<&'static str> {
617    match format.to_ascii_lowercase().as_str() {
618        "png" => Some("image/png"),
619        "jpeg" | "jpg" => Some("image/jpeg"),
620        "webp" => Some("image/webp"),
621        "gif" => Some("image/gif"),
622        _ => None,
623    }
624}
625
626fn display_path(path: &Path) -> String {
627    let rendered = path_to_string(path);
628    if rendered.is_empty() {
629        ".".to_string()
630    } else {
631        rendered
632    }
633}
634
635fn display_project_path(project_root: &Path, path: &Path) -> String {
636    let absolute = if path.is_absolute() {
637        path.to_path_buf()
638    } else {
639        project_root.join(path)
640    };
641    absolute
642        .strip_prefix(project_root)
643        .map(path_to_string)
644        .unwrap_or_else(|_| path_to_string(path))
645}
646
647fn manifest_source_count(manifest: &Manifest) -> usize {
648    manifest
649        .outputs
650        .iter()
651        .map(|output| output.source_path.as_str())
652        .collect::<BTreeSet<_>>()
653        .len()
654}
655
656fn normalize_ai_review_observation(mut observation: AiReviewObservation) -> AiReviewObservation {
657    observation.severity = "advisory".to_string();
658    observation.category = normalize_observation_category(&observation.category).to_string();
659    observation
660}
661
662fn normalize_observation_category(category: &str) -> &'static str {
663    match category {
664        "crop risk" => "crop risk",
665        "readability risk" => "readability risk",
666        "excessive padding" => "excessive padding",
667        "low-resolution source" => "low-resolution source",
668        "format-quality concern" => "format-quality concern",
669        "accessibility note" => "accessibility note",
670        _ => "format-quality concern",
671    }
672}
673
674#[cfg(test)]
675mod tests {
676    use std::path::PathBuf;
677
678    use super::{
679        ai_consent_preview_to_json, ai_image_mime_type, ai_review_report_to_json,
680        build_ai_review_dry_run_report, build_ai_review_report, build_ai_review_request,
681        render_ai_review_markdown, AiConsentPreview, AiGeneratedOutput, AiProvider,
682        AiProviderClient, AiReviewOptions, AiReviewProviderClient, AiSelectedFile,
683        MockAiProviderClient, MockAiReviewProviderClient,
684    };
685    use crate::manifest::{Manifest, ManifestOutput};
686
687    #[test]
688    fn provider_labels_and_env_vars_are_stable() {
689        assert_eq!(AiProvider::Openai.label(), "openai");
690        assert_eq!(AiProvider::Openai.credential_env_var(), "OPENAI_API_KEY");
691        assert_eq!(AiProvider::Anthropic.label(), "anthropic");
692        assert_eq!(
693            AiProvider::Anthropic.credential_env_var(),
694            "ANTHROPIC_API_KEY"
695        );
696    }
697
698    #[test]
699    fn mock_provider_client_returns_stable_non_network_response() {
700        let preview = AiConsentPreview {
701            provider: AiProvider::Openai,
702            model: "test-model".to_string(),
703            command: "devimg ai consent".to_string(),
704            config_path: "devimg.toml".to_string(),
705            project_root: ".".to_string(),
706            mode: "metadata-only".to_string(),
707            dry_run: true,
708            paths_included: true,
709            image_bytes_included: false,
710            output_path: None,
711            manifest_path: "public/images/devimg-manifest.json".to_string(),
712            report_path: "devimg-report.md".to_string(),
713            manifest_readable: false,
714            source_files: vec![AiSelectedFile {
715                source_name: "portfolio".to_string(),
716                path: "assets/images/sample.png".to_string(),
717                role: "source-image".to_string(),
718                width: 100,
719                height: 50,
720                format: "png".to_string(),
721                bytes: 12,
722                hash: "blake3:source".to_string(),
723                image_bytes_included: false,
724            }],
725            generated_outputs: vec![AiGeneratedOutput {
726                source_path: "assets/images/sample.png".to_string(),
727                output_path: "public/images/generated/sample.webp".to_string(),
728                preset: "card".to_string(),
729                fit: "cover".to_string(),
730                width: 64,
731                height: 36,
732                format: "webp".to_string(),
733                bytes: 10,
734                hash: "blake3:output".to_string(),
735            }],
736        };
737
738        let response = MockAiProviderClient::new(AiProvider::Anthropic).consent_response(&preview);
739
740        assert_eq!(response.provider, AiProvider::Anthropic);
741        assert_eq!(response.model, "test-model");
742        assert_eq!(response.request_kind, "consent-preview");
743        assert!(!response.network_called);
744        assert_eq!(response.selected_file_count, 1);
745        assert_eq!(response.generated_output_count, 1);
746    }
747
748    #[test]
749    fn consent_preview_json_is_timestamp_free() {
750        let preview = AiConsentPreview {
751            provider: AiProvider::Anthropic,
752            model: "stable-model".to_string(),
753            command: "devimg ai consent".to_string(),
754            config_path: "devimg.toml".to_string(),
755            project_root: ".".to_string(),
756            mode: "metadata-only".to_string(),
757            dry_run: true,
758            paths_included: true,
759            image_bytes_included: false,
760            output_path: Some("/tmp/consent.json".to_string()),
761            manifest_path: "public/images/devimg-manifest.json".to_string(),
762            report_path: "devimg-report.md".to_string(),
763            manifest_readable: false,
764            source_files: Vec::new(),
765            generated_outputs: Vec::new(),
766        };
767
768        let json = ai_consent_preview_to_json(&preview);
769
770        assert!(json.contains("\"provider\": \"anthropic\""));
771        assert!(json.contains("\"model\": \"stable-model\""));
772        assert!(!json.contains("generated_at"));
773        assert!(!json.contains("timestamp"));
774    }
775
776    #[test]
777    fn ai_review_request_selects_metadata_and_image_inputs() {
778        let manifest = sample_manifest();
779        let request = build_ai_review_request(
780            &manifest,
781            &AiReviewOptions {
782                provider: AiProvider::Openai,
783                model: "vision-model".to_string(),
784                command: "devimg review --ai".to_string(),
785                manifest_path: PathBuf::from("/repo/public/images/devimg-manifest.json"),
786                project_root: PathBuf::from("/repo"),
787                dry_run: true,
788                include_images: true,
789                image_detail: "low".to_string(),
790                max_images: 1,
791                ai_output_path: Some(PathBuf::from("/repo/devimg-ai-review.json")),
792                markdown_path: Some(PathBuf::from("/tmp/devimg-ai-review.md")),
793            },
794        );
795
796        assert_eq!(request.provider, AiProvider::Openai);
797        assert_eq!(request.mode, "include-images");
798        assert_eq!(request.manifest_path, "public/images/devimg-manifest.json");
799        assert_eq!(
800            request.ai_output_path.as_deref(),
801            Some("devimg-ai-review.json")
802        );
803        assert_eq!(
804            request.markdown_path.as_deref(),
805            Some("/tmp/devimg-ai-review.md")
806        );
807        assert_eq!(request.manifest_summary.source_count, 1);
808        assert_eq!(request.manifest_summary.output_count, 2);
809        assert_eq!(request.outputs.len(), 2);
810        assert_eq!(request.selected_images.len(), 1);
811        assert_eq!(request.selected_images[0].mime_type, "image/webp");
812        let webp_output = request
813            .outputs
814            .iter()
815            .find(|output| output.format == "webp")
816            .expect("webp output exists");
817        let avif_output = request
818            .outputs
819            .iter()
820            .find(|output| output.format == "avif")
821            .expect("avif output exists");
822        assert!(webp_output.image_bytes_included);
823        assert!(!avif_output.image_bytes_included);
824        assert_eq!(request.skipped_image_count, 1);
825    }
826
827    #[test]
828    fn ai_review_dry_run_json_and_markdown_are_timestamp_free() {
829        let manifest = sample_manifest();
830        let request = build_ai_review_request(
831            &manifest,
832            &AiReviewOptions {
833                provider: AiProvider::Openai,
834                model: "dry-run-model".to_string(),
835                command: "devimg review --ai".to_string(),
836                manifest_path: PathBuf::from("public/images/devimg-manifest.json"),
837                project_root: PathBuf::from("."),
838                dry_run: true,
839                include_images: false,
840                image_detail: "low".to_string(),
841                max_images: 8,
842                ai_output_path: None,
843                markdown_path: None,
844            },
845        );
846        let report = build_ai_review_dry_run_report(&request);
847        let json = ai_review_report_to_json(&report);
848        let markdown = render_ai_review_markdown(&report);
849
850        assert!(json.contains("\"provider\": \"openai\""));
851        assert!(json.contains("\"dry_run\": true"));
852        assert!(json.contains("\"provider_called\": false"));
853        assert!(!json.contains("generated_at"));
854        assert!(!json.contains("timestamp"));
855        assert!(markdown.contains("# DevImg AI Review"));
856        assert!(markdown.contains("Dry run: `true`"));
857    }
858
859    #[test]
860    fn mock_ai_review_provider_returns_stable_payload_and_failure() {
861        let manifest = sample_manifest();
862        let request = build_ai_review_request(
863            &manifest,
864            &AiReviewOptions {
865                provider: AiProvider::Anthropic,
866                model: "mock-model".to_string(),
867                command: "devimg review --ai".to_string(),
868                manifest_path: PathBuf::from("public/images/devimg-manifest.json"),
869                project_root: PathBuf::from("."),
870                dry_run: false,
871                include_images: false,
872                image_detail: "low".to_string(),
873                max_images: 8,
874                ai_output_path: None,
875                markdown_path: None,
876            },
877        );
878
879        let payload = MockAiReviewProviderClient::new(AiProvider::Anthropic)
880            .review(&request)
881            .expect("mock provider succeeds");
882        let report = build_ai_review_report(&request, payload, true);
883
884        assert!(report.provider_called);
885        assert_eq!(report.provider_summary, "mock anthropic AI review");
886        assert_eq!(report.observations.len(), 1);
887        assert_eq!(report.observations[0].severity, "advisory");
888
889        let error = MockAiReviewProviderClient::failing(AiProvider::Openai)
890            .review(&request)
891            .expect_err("mock provider fails");
892        assert!(error
893            .to_string()
894            .contains("mock AI review provider failure"));
895    }
896
897    #[test]
898    fn ai_image_mime_type_matches_openai_supported_inputs() {
899        assert_eq!(ai_image_mime_type("png"), Some("image/png"));
900        assert_eq!(ai_image_mime_type("jpeg"), Some("image/jpeg"));
901        assert_eq!(ai_image_mime_type("jpg"), Some("image/jpeg"));
902        assert_eq!(ai_image_mime_type("webp"), Some("image/webp"));
903        assert_eq!(ai_image_mime_type("gif"), Some("image/gif"));
904        assert_eq!(ai_image_mime_type("avif"), None);
905    }
906
907    fn sample_manifest() -> Manifest {
908        Manifest {
909            version: 1,
910            generated_at: "unix:123".to_string(),
911            config_path: "devimg.toml".to_string(),
912            config_hash: "blake3:config".to_string(),
913            outputs: vec![
914                ManifestOutput {
915                    source_path: "assets/images/sample.png".to_string(),
916                    source_hash: "blake3:source".to_string(),
917                    source_width: 100,
918                    source_height: 80,
919                    source_bytes: 1000,
920                    output_path: "public/images/generated/sample.project-card.64.webp".to_string(),
921                    preset: "project-card".to_string(),
922                    fit: "cover".to_string(),
923                    width: 64,
924                    height: 64,
925                    format: "webp".to_string(),
926                    bytes: 700,
927                    hash: "blake3:webp".to_string(),
928                    operation_hash: "blake3:operation-webp".to_string(),
929                },
930                ManifestOutput {
931                    source_path: "assets/images/sample.png".to_string(),
932                    source_hash: "blake3:source".to_string(),
933                    source_width: 100,
934                    source_height: 80,
935                    source_bytes: 1000,
936                    output_path: "public/images/generated/sample.project-card.64.avif".to_string(),
937                    preset: "project-card".to_string(),
938                    fit: "cover".to_string(),
939                    width: 64,
940                    height: 64,
941                    format: "avif".to_string(),
942                    bytes: 600,
943                    hash: "blake3:avif".to_string(),
944                    operation_hash: "blake3:operation-avif".to_string(),
945                },
946            ],
947        }
948    }
949}