1use std::collections::{BTreeMap, BTreeSet};
2use std::fs;
3use std::io::ErrorKind;
4use std::path::{Path, PathBuf};
5
6use serde::{Deserialize, Serialize};
7
8use crate::config::{project_relative, resolve_project_path_checked, Config};
9use crate::manifest::{read_manifest, Manifest};
10use crate::pipeline::path_to_string;
11use crate::quality::manifest_quality_warnings;
12use crate::{scan_sources, Result};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
15#[serde(rename_all = "kebab-case")]
16pub enum AiProvider {
17 Openai,
18 Anthropic,
19}
20
21impl AiProvider {
22 pub fn label(self) -> &'static str {
23 match self {
24 Self::Openai => "openai",
25 Self::Anthropic => "anthropic",
26 }
27 }
28
29 pub fn credential_env_var(self) -> &'static str {
30 match self {
31 Self::Openai => "OPENAI_API_KEY",
32 Self::Anthropic => "ANTHROPIC_API_KEY",
33 }
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct AiConsentOptions {
39 pub provider: AiProvider,
40 pub model: String,
41 pub command: String,
42 pub config_path: PathBuf,
43 pub dry_run: bool,
44 pub include_images: bool,
45 pub output_path: Option<PathBuf>,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
49pub struct AiConsentPreview {
50 pub provider: AiProvider,
51 pub model: String,
52 pub command: String,
53 pub config_path: String,
54 pub project_root: String,
55 pub mode: String,
56 pub dry_run: bool,
57 pub paths_included: bool,
58 pub image_bytes_included: bool,
59 pub output_path: Option<String>,
60 pub manifest_path: String,
61 pub report_path: String,
62 pub manifest_readable: bool,
63 pub source_files: Vec<AiSelectedFile>,
64 pub generated_outputs: Vec<AiGeneratedOutput>,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
68pub struct AiSelectedFile {
69 pub source_name: String,
70 pub path: String,
71 pub role: String,
72 pub width: u32,
73 pub height: u32,
74 pub format: String,
75 pub bytes: u64,
76 pub hash: String,
77 pub image_bytes_included: bool,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
81pub struct AiGeneratedOutput {
82 pub source_path: String,
83 pub output_path: String,
84 pub preset: String,
85 pub fit: String,
86 pub width: u32,
87 pub height: u32,
88 pub format: String,
89 pub bytes: u64,
90 pub hash: String,
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
94pub struct AiProviderResponse {
95 pub provider: AiProvider,
96 pub model: String,
97 pub request_kind: String,
98 pub network_called: bool,
99 pub selected_file_count: usize,
100 pub generated_output_count: usize,
101}
102
103pub trait AiProviderClient {
104 fn consent_response(&self, preview: &AiConsentPreview) -> AiProviderResponse;
105}
106
107pub trait AiReviewProviderClient {
108 fn review(&self, request: &AiReviewRequest) -> Result<AiReviewProviderPayload>;
109}
110
111pub trait AiAltProviderClient {
112 fn alt(&self, request: &AiAltRequest) -> Result<AiAltProviderPayload>;
113}
114
115pub trait AiDraftProviderClient {
116 fn draft(&self, request: &AiDraftRequest) -> Result<AiDraftProviderPayload>;
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub struct MockAiProviderClient {
121 provider: AiProvider,
122}
123
124impl MockAiProviderClient {
125 pub fn new(provider: AiProvider) -> Self {
126 Self { provider }
127 }
128}
129
130impl AiProviderClient for MockAiProviderClient {
131 fn consent_response(&self, preview: &AiConsentPreview) -> AiProviderResponse {
132 AiProviderResponse {
133 provider: self.provider,
134 model: preview.model.clone(),
135 request_kind: "consent-preview".to_string(),
136 network_called: false,
137 selected_file_count: preview.source_files.len(),
138 generated_output_count: preview.generated_outputs.len(),
139 }
140 }
141}
142
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub struct AiReviewOptions {
145 pub provider: AiProvider,
146 pub model: String,
147 pub command: String,
148 pub manifest_path: PathBuf,
149 pub project_root: PathBuf,
150 pub dry_run: bool,
151 pub include_images: bool,
152 pub image_detail: String,
153 pub max_images: usize,
154 pub ai_output_path: Option<PathBuf>,
155 pub markdown_path: Option<PathBuf>,
156}
157
158#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
159pub struct AiReviewRequest {
160 pub schema_version: u32,
161 pub provider: AiProvider,
162 pub model: String,
163 pub command: String,
164 pub manifest_path: String,
165 pub project_root: String,
166 pub mode: String,
167 pub dry_run: bool,
168 pub paths_included: bool,
169 pub image_bytes_included: bool,
170 pub image_detail: String,
171 pub max_images: usize,
172 pub ai_output_path: Option<String>,
173 pub markdown_path: Option<String>,
174 pub manifest_summary: AiReviewManifestSummary,
175 pub review_signals: Vec<String>,
176 pub outputs: Vec<AiReviewOutput>,
177 pub selected_images: Vec<AiReviewImageInput>,
178 pub skipped_image_count: usize,
179}
180
181#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
182pub struct AiReviewManifestSummary {
183 pub config_path: String,
184 pub config_hash: String,
185 pub source_count: usize,
186 pub output_count: usize,
187 pub source_bytes: u64,
188 pub output_bytes: u64,
189}
190
191#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
192pub struct AiReviewOutput {
193 pub source_path: String,
194 pub output_path: String,
195 pub preset: String,
196 pub fit: String,
197 pub width: u32,
198 pub height: u32,
199 pub format: String,
200 pub bytes: u64,
201 pub hash: String,
202 pub source_width: u32,
203 pub source_height: u32,
204 pub source_bytes: u64,
205 pub image_bytes_included: bool,
206 pub image_detail: Option<String>,
207}
208
209#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
210pub struct AiReviewImageInput {
211 pub output_path: String,
212 pub mime_type: String,
213 pub width: u32,
214 pub height: u32,
215 pub bytes: u64,
216 pub hash: String,
217 pub detail: String,
218}
219
220#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
221pub struct AiReviewProviderPayload {
222 #[serde(default)]
223 pub summary: String,
224 #[serde(default)]
225 pub observations: Vec<AiReviewObservation>,
226}
227
228#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
229pub struct AiReviewObservation {
230 pub category: String,
231 pub severity: String,
232 pub source_path: String,
233 pub preset: String,
234 pub output_path: String,
235 pub rationale: String,
236 pub suggested_next_command: String,
237}
238
239#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
240pub struct AiReviewReport {
241 pub schema_version: u32,
242 pub provider: AiProvider,
243 pub model: String,
244 pub command: String,
245 pub manifest_path: String,
246 pub project_root: String,
247 pub mode: String,
248 pub dry_run: bool,
249 pub paths_included: bool,
250 pub image_bytes_included: bool,
251 pub image_detail: String,
252 pub max_images: usize,
253 pub ai_output_path: Option<String>,
254 pub markdown_path: Option<String>,
255 pub provider_called: bool,
256 pub summary: AiReviewSummary,
257 pub review_signals: Vec<String>,
258 pub outputs: Vec<AiReviewOutput>,
259 pub selected_images: Vec<AiReviewImageInput>,
260 pub provider_summary: String,
261 pub observations: Vec<AiReviewObservation>,
262}
263
264#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
265pub struct AiReviewSummary {
266 pub source_count: usize,
267 pub output_count: usize,
268 pub selected_image_count: usize,
269 pub skipped_image_count: usize,
270 pub review_signal_count: usize,
271 pub observation_count: usize,
272}
273
274#[derive(Debug, Clone, PartialEq, Eq)]
275pub struct AiAltOptions {
276 pub provider: AiProvider,
277 pub model: String,
278 pub command: String,
279 pub config_path: PathBuf,
280 pub manifest_path: PathBuf,
281 pub project_root: PathBuf,
282 pub dry_run: bool,
283 pub include_images: bool,
284 pub image_detail: String,
285 pub max_images: usize,
286 pub output_path: Option<PathBuf>,
287 pub markdown_path: Option<PathBuf>,
288}
289
290#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
291pub struct AiAltRequest {
292 pub schema_version: u32,
293 pub provider: AiProvider,
294 pub model: String,
295 pub command: String,
296 pub config_path: String,
297 pub manifest_path: String,
298 pub project_root: String,
299 pub mode: String,
300 pub dry_run: bool,
301 pub paths_included: bool,
302 pub image_bytes_included: bool,
303 pub image_detail: String,
304 pub max_images: usize,
305 pub output_path: Option<String>,
306 pub markdown_path: Option<String>,
307 pub manifest_summary: AiAltManifestSummary,
308 pub sources: Vec<AiAltSource>,
309 pub selected_images: Vec<AiAltImageInput>,
310 pub skipped_image_count: usize,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
314pub struct AiAltManifestSummary {
315 pub config_path: String,
316 pub config_hash: String,
317 pub source_count: usize,
318 pub output_count: usize,
319 pub source_bytes: u64,
320 pub output_bytes: u64,
321}
322
323#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
324pub struct AiAltSource {
325 pub source_path: String,
326 pub source_hash: String,
327 pub source_width: u32,
328 pub source_height: u32,
329 pub source_bytes: u64,
330 pub representative_image_path: String,
331 pub representative_image_width: u32,
332 pub representative_image_height: u32,
333 pub representative_image_format: String,
334 pub image_bytes_included: bool,
335 pub image_detail: Option<String>,
336 pub variants: Vec<AiAltVariant>,
337}
338
339#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
340pub struct AiAltVariant {
341 pub output_path: String,
342 pub preset: String,
343 pub fit: String,
344 pub width: u32,
345 pub height: u32,
346 pub format: String,
347 pub bytes: u64,
348 pub hash: String,
349}
350
351#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
352pub struct AiAltImageInput {
353 pub source_path: String,
354 pub image_path: String,
355 pub mime_type: String,
356 pub width: u32,
357 pub height: u32,
358 pub bytes: u64,
359 pub hash: String,
360 pub detail: String,
361}
362
363#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
364pub struct AiAltProviderPayload {
365 #[serde(default)]
366 pub summary: String,
367 #[serde(default)]
368 pub drafts: Vec<AiAltDraft>,
369}
370
371#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
372pub struct AiAltDraft {
373 pub source_path: String,
374 pub representative_image_path: String,
375 pub candidate_alt_text: String,
376 pub review_note: String,
377 pub confidence: String,
378 pub image_category: String,
379 pub warnings: Vec<String>,
380}
381
382#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
383pub struct AiAltReport {
384 pub schema_version: u32,
385 pub provider: AiProvider,
386 pub model: String,
387 pub command: String,
388 pub config_path: String,
389 pub manifest_path: String,
390 pub project_root: String,
391 pub mode: String,
392 pub dry_run: bool,
393 pub paths_included: bool,
394 pub image_bytes_included: bool,
395 pub image_detail: String,
396 pub max_images: usize,
397 pub output_path: Option<String>,
398 pub markdown_path: Option<String>,
399 pub provider_called: bool,
400 pub summary: AiAltReportSummary,
401 pub sources: Vec<AiAltSource>,
402 pub selected_images: Vec<AiAltImageInput>,
403 pub provider_summary: String,
404 pub drafts: Vec<AiAltDraft>,
405}
406
407#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
408pub struct AiAltReportSummary {
409 pub source_count: usize,
410 pub output_count: usize,
411 pub selected_image_count: usize,
412 pub skipped_image_count: usize,
413 pub draft_count: usize,
414}
415
416#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
417#[serde(rename_all = "kebab-case")]
418pub enum AiDraftType {
419 ReleaseNotes,
420 ReadmeSnippet,
421 ProjectPageCopy,
422 BlogOutline,
423 SocialPostOutline,
424}
425
426impl AiDraftType {
427 pub fn label(self) -> &'static str {
428 match self {
429 Self::ReleaseNotes => "release-notes",
430 Self::ReadmeSnippet => "readme-snippet",
431 Self::ProjectPageCopy => "project-page-copy",
432 Self::BlogOutline => "blog-outline",
433 Self::SocialPostOutline => "social-post-outline",
434 }
435 }
436
437 pub fn title(self) -> &'static str {
438 match self {
439 Self::ReleaseNotes => "Release Notes",
440 Self::ReadmeSnippet => "README Snippet",
441 Self::ProjectPageCopy => "Project Page Copy",
442 Self::BlogOutline => "Blog Outline",
443 Self::SocialPostOutline => "Social Post Outline",
444 }
445 }
446}
447
448#[derive(Debug, Clone, PartialEq, Eq)]
449pub struct AiDraftOptions {
450 pub draft_type: AiDraftType,
451 pub provider: Option<AiProvider>,
452 pub model: Option<String>,
453 pub command: String,
454 pub config_path: PathBuf,
455 pub project_root: PathBuf,
456 pub output_path: PathBuf,
457 pub dry_run: bool,
458 pub compare_json_path: Option<PathBuf>,
459 pub ai_review_json_path: Option<PathBuf>,
460 pub review_html_path: Option<PathBuf>,
461 pub changelog_path: Option<PathBuf>,
462}
463
464#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
465pub struct AiDraftRequest {
466 pub schema_version: u32,
467 pub draft_type: AiDraftType,
468 pub provider: Option<AiProvider>,
469 pub model: Option<String>,
470 pub command: String,
471 pub config_path: String,
472 pub project_root: String,
473 pub mode: String,
474 pub dry_run: bool,
475 pub output_path: String,
476 pub manifest_summary: AiDraftManifestSummary,
477 pub report_summary: AiDraftArtifactSummary,
478 pub changelog_summary: Option<AiDraftArtifactSummary>,
479 pub optional_artifacts: Vec<AiDraftArtifactSummary>,
480}
481
482#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
483pub struct AiDraftManifestSummary {
484 pub path: String,
485 pub readable: bool,
486 pub read_error: Option<String>,
487 pub config_hash: Option<String>,
488 pub source_count: usize,
489 pub output_count: usize,
490 pub source_bytes: u64,
491 pub output_bytes: u64,
492 pub outputs: Vec<AiDraftManifestOutputSummary>,
493}
494
495#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
496pub struct AiDraftManifestOutputSummary {
497 pub source_path: String,
498 pub output_path: String,
499 pub preset: String,
500 pub fit: String,
501 pub width: u32,
502 pub height: u32,
503 pub format: String,
504 pub bytes: u64,
505}
506
507#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
508pub struct AiDraftArtifactSummary {
509 pub label: String,
510 pub path: String,
511 pub readable: bool,
512 pub read_error: Option<String>,
513 pub bytes: u64,
514 pub line_count: usize,
515 pub excerpt: String,
516}
517
518#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
519pub struct AiDraftProviderPayload {
520 #[serde(default)]
521 pub summary: String,
522 #[serde(default)]
523 pub sections: Vec<AiDraftSection>,
524}
525
526#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
527pub struct AiDraftSection {
528 pub heading: String,
529 pub body: String,
530 #[serde(default)]
531 pub bullets: Vec<String>,
532}
533
534#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
535pub struct AiDraftReport {
536 pub schema_version: u32,
537 pub draft_type: AiDraftType,
538 pub provider: Option<AiProvider>,
539 pub model: Option<String>,
540 pub command: String,
541 pub config_path: String,
542 pub project_root: String,
543 pub mode: String,
544 pub dry_run: bool,
545 pub output_path: String,
546 pub provider_called: bool,
547 pub summary: AiDraftReportSummary,
548 pub manifest_summary: AiDraftManifestSummary,
549 pub report_summary: AiDraftArtifactSummary,
550 pub changelog_summary: Option<AiDraftArtifactSummary>,
551 pub optional_artifacts: Vec<AiDraftArtifactSummary>,
552 pub provider_summary: String,
553 pub sections: Vec<AiDraftSection>,
554}
555
556#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
557pub struct AiDraftReportSummary {
558 pub source_count: usize,
559 pub output_count: usize,
560 pub optional_artifact_count: usize,
561 pub section_count: usize,
562}
563
564#[derive(Debug, Clone, PartialEq, Eq)]
565pub struct MockAiReviewProviderClient {
566 provider: AiProvider,
567 fail: bool,
568}
569
570impl MockAiReviewProviderClient {
571 pub fn new(provider: AiProvider) -> Self {
572 Self {
573 provider,
574 fail: false,
575 }
576 }
577
578 pub fn failing(provider: AiProvider) -> Self {
579 Self {
580 provider,
581 fail: true,
582 }
583 }
584}
585
586impl AiReviewProviderClient for MockAiReviewProviderClient {
587 fn review(&self, request: &AiReviewRequest) -> Result<AiReviewProviderPayload> {
588 if self.fail {
589 return Err(crate::DevimgError::config(
590 &request.manifest_path,
591 "mock AI review provider failure",
592 ));
593 }
594
595 let first = request.outputs.first();
596 Ok(AiReviewProviderPayload {
597 summary: format!("mock {} AI review", self.provider.label()),
598 observations: first
599 .map(|output| {
600 vec![AiReviewObservation {
601 category: "format-quality concern".to_string(),
602 severity: "advisory".to_string(),
603 source_path: output.source_path.clone(),
604 preset: output.preset.clone(),
605 output_path: output.output_path.clone(),
606 rationale: "Mock review observation for provider boundary tests."
607 .to_string(),
608 suggested_next_command: format!(
609 "devimg review --manifest {} --output .devimg/review.html",
610 request.manifest_path
611 ),
612 }]
613 })
614 .unwrap_or_default(),
615 })
616 }
617}
618
619#[derive(Debug, Clone, PartialEq, Eq)]
620pub struct MockAiAltProviderClient {
621 provider: AiProvider,
622 fail: bool,
623}
624
625impl MockAiAltProviderClient {
626 pub fn new(provider: AiProvider) -> Self {
627 Self {
628 provider,
629 fail: false,
630 }
631 }
632
633 pub fn failing(provider: AiProvider) -> Self {
634 Self {
635 provider,
636 fail: true,
637 }
638 }
639}
640
641impl AiAltProviderClient for MockAiAltProviderClient {
642 fn alt(&self, request: &AiAltRequest) -> Result<AiAltProviderPayload> {
643 if self.fail {
644 return Err(crate::DevimgError::config(
645 &request.config_path,
646 "mock AI alt provider failure",
647 ));
648 }
649
650 Ok(AiAltProviderPayload {
651 summary: format!("mock {} alt text", self.provider.label()),
652 drafts: request
653 .sources
654 .iter()
655 .map(|source| AiAltDraft {
656 source_path: source.source_path.clone(),
657 representative_image_path: source.representative_image_path.clone(),
658 candidate_alt_text: "Mock draft alt text for provider boundary tests."
659 .to_string(),
660 review_note: "Review before using in application code.".to_string(),
661 confidence: "medium".to_string(),
662 image_category: "unknown".to_string(),
663 warnings: vec!["needs-human-review".to_string()],
664 })
665 .collect(),
666 })
667 }
668}
669
670#[derive(Debug, Clone, PartialEq, Eq)]
671pub struct MockAiDraftProviderClient {
672 provider: AiProvider,
673 fail: bool,
674}
675
676impl MockAiDraftProviderClient {
677 pub fn new(provider: AiProvider) -> Self {
678 Self {
679 provider,
680 fail: false,
681 }
682 }
683
684 pub fn failing(provider: AiProvider) -> Self {
685 Self {
686 provider,
687 fail: true,
688 }
689 }
690}
691
692impl AiDraftProviderClient for MockAiDraftProviderClient {
693 fn draft(&self, request: &AiDraftRequest) -> Result<AiDraftProviderPayload> {
694 if self.fail {
695 return Err(crate::DevimgError::config(
696 &request.config_path,
697 "mock AI draft provider failure",
698 ));
699 }
700
701 Ok(AiDraftProviderPayload {
702 summary: format!("mock {} draft", self.provider.label()),
703 sections: vec![
704 AiDraftSection {
705 heading: request.draft_type.title().to_string(),
706 body: "Mock provider draft for provider boundary tests.".to_string(),
707 bullets: vec![
708 format!("Draft type: {}", request.draft_type.label()),
709 format!(
710 "Outputs summarized: {}",
711 request.manifest_summary.output_count
712 ),
713 ],
714 },
715 AiDraftSection {
716 heading: "Review Notes".to_string(),
717 body: "Review before publishing.".to_string(),
718 bullets: vec!["needs-human-review".to_string()],
719 },
720 ],
721 })
722 }
723}
724
725pub fn build_ai_consent_preview(
726 config: &Config,
727 options: &AiConsentOptions,
728) -> Result<AiConsentPreview> {
729 let manifest_path =
730 resolve_project_path_checked(config, &config.project.manifest, "manifest path")?;
731 let report_path = resolve_project_path_checked(config, &config.project.report, "report path")?;
732 let sources = scan_sources(config)?;
733 let source_files = sources
734 .into_iter()
735 .map(|source| AiSelectedFile {
736 source_name: source.source_name,
737 path: source.project_path,
738 role: "source-image".to_string(),
739 width: source.width,
740 height: source.height,
741 format: source.format.label().to_string(),
742 bytes: source.bytes,
743 hash: source.hash,
744 image_bytes_included: options.include_images,
745 })
746 .collect();
747
748 let mut manifest_readable = false;
749 let mut generated_outputs = Vec::new();
750 if let Ok(manifest) = read_manifest(&manifest_path) {
751 manifest_readable = true;
752 let mut seen = BTreeSet::new();
753 for output in manifest.outputs {
754 if seen.insert(output.output_path.clone()) {
755 generated_outputs.push(AiGeneratedOutput {
756 source_path: output.source_path,
757 output_path: output.output_path,
758 preset: output.preset,
759 fit: output.fit,
760 width: output.width,
761 height: output.height,
762 format: output.format,
763 bytes: output.bytes,
764 hash: output.hash,
765 });
766 }
767 }
768 generated_outputs.sort_by(|left, right| left.output_path.cmp(&right.output_path));
769 }
770
771 Ok(AiConsentPreview {
772 provider: options.provider,
773 model: options.model.clone(),
774 command: options.command.clone(),
775 config_path: path_to_string(&options.config_path),
776 project_root: display_path(&config.project.root),
777 mode: if options.include_images {
778 "include-images".to_string()
779 } else {
780 "metadata-only".to_string()
781 },
782 dry_run: options.dry_run,
783 paths_included: true,
784 image_bytes_included: options.include_images,
785 output_path: options.output_path.as_deref().map(path_to_string),
786 manifest_path: path_to_string(&project_relative(config, &manifest_path)),
787 report_path: path_to_string(&project_relative(config, &report_path)),
788 manifest_readable,
789 source_files,
790 generated_outputs,
791 })
792}
793
794pub fn ai_consent_preview_to_json(preview: &AiConsentPreview) -> String {
795 serde_json::to_string_pretty(preview).expect("AI consent preview serialization cannot fail")
796 + "\n"
797}
798
799pub fn build_ai_review_request(manifest: &Manifest, options: &AiReviewOptions) -> AiReviewRequest {
800 let max_images = options.max_images.max(1);
801 let image_detail = options.image_detail.clone();
802 let mut outputs = manifest
803 .outputs
804 .iter()
805 .map(|output| AiReviewOutput {
806 source_path: output.source_path.clone(),
807 output_path: output.output_path.clone(),
808 preset: output.preset.clone(),
809 fit: output.fit.clone(),
810 width: output.width,
811 height: output.height,
812 format: output.format.clone(),
813 bytes: output.bytes,
814 hash: output.hash.clone(),
815 source_width: output.source_width,
816 source_height: output.source_height,
817 source_bytes: output.source_bytes,
818 image_bytes_included: false,
819 image_detail: None,
820 })
821 .collect::<Vec<_>>();
822 outputs.sort_by(|left, right| {
823 left.source_path
824 .cmp(&right.source_path)
825 .then(left.preset.cmp(&right.preset))
826 .then(left.width.cmp(&right.width))
827 .then(left.height.cmp(&right.height))
828 .then(left.format.cmp(&right.format))
829 .then(left.output_path.cmp(&right.output_path))
830 });
831
832 let selected_images = if options.include_images {
833 outputs
834 .iter()
835 .filter_map(|output| {
836 ai_image_mime_type(&output.format).map(|mime_type| AiReviewImageInput {
837 output_path: output.output_path.clone(),
838 mime_type: mime_type.to_string(),
839 width: output.width,
840 height: output.height,
841 bytes: output.bytes,
842 hash: output.hash.clone(),
843 detail: image_detail.clone(),
844 })
845 })
846 .take(max_images)
847 .collect::<Vec<_>>()
848 } else {
849 Vec::new()
850 };
851 let selected_paths = selected_images
852 .iter()
853 .map(|image| image.output_path.clone())
854 .collect::<BTreeSet<_>>();
855 for output in &mut outputs {
856 if selected_paths.contains(&output.output_path) {
857 output.image_bytes_included = true;
858 output.image_detail = Some(image_detail.clone());
859 }
860 }
861
862 let output_count = manifest.outputs.len();
863 let skipped_image_count = if options.include_images {
864 output_count.saturating_sub(selected_images.len())
865 } else {
866 0
867 };
868 let mode = if options.include_images {
869 "include-images"
870 } else {
871 "metadata-only"
872 };
873
874 AiReviewRequest {
875 schema_version: 1,
876 provider: options.provider,
877 model: options.model.clone(),
878 command: options.command.clone(),
879 manifest_path: display_project_path(&options.project_root, &options.manifest_path),
880 project_root: display_path(&options.project_root),
881 mode: mode.to_string(),
882 dry_run: options.dry_run,
883 paths_included: true,
884 image_bytes_included: options.include_images,
885 image_detail,
886 max_images,
887 ai_output_path: options
888 .ai_output_path
889 .as_deref()
890 .map(|path| display_project_path(&options.project_root, path)),
891 markdown_path: options
892 .markdown_path
893 .as_deref()
894 .map(|path| display_project_path(&options.project_root, path)),
895 manifest_summary: AiReviewManifestSummary {
896 config_path: manifest.config_path.clone(),
897 config_hash: manifest.config_hash.clone(),
898 source_count: manifest_source_count(manifest),
899 output_count,
900 source_bytes: manifest.source_bytes_total(),
901 output_bytes: manifest.output_bytes_total(),
902 },
903 review_signals: manifest_quality_warnings(manifest),
904 outputs,
905 selected_images,
906 skipped_image_count,
907 }
908}
909
910pub fn build_ai_review_report(
911 request: &AiReviewRequest,
912 payload: AiReviewProviderPayload,
913 provider_called: bool,
914) -> AiReviewReport {
915 let observations = payload
916 .observations
917 .into_iter()
918 .map(normalize_ai_review_observation)
919 .collect::<Vec<_>>();
920 AiReviewReport {
921 schema_version: request.schema_version,
922 provider: request.provider,
923 model: request.model.clone(),
924 command: request.command.clone(),
925 manifest_path: request.manifest_path.clone(),
926 project_root: request.project_root.clone(),
927 mode: request.mode.clone(),
928 dry_run: request.dry_run,
929 paths_included: request.paths_included,
930 image_bytes_included: request.image_bytes_included,
931 image_detail: request.image_detail.clone(),
932 max_images: request.max_images,
933 ai_output_path: request.ai_output_path.clone(),
934 markdown_path: request.markdown_path.clone(),
935 provider_called,
936 summary: AiReviewSummary {
937 source_count: request.manifest_summary.source_count,
938 output_count: request.manifest_summary.output_count,
939 selected_image_count: request.selected_images.len(),
940 skipped_image_count: request.skipped_image_count,
941 review_signal_count: request.review_signals.len(),
942 observation_count: observations.len(),
943 },
944 review_signals: request.review_signals.clone(),
945 outputs: request.outputs.clone(),
946 selected_images: request.selected_images.clone(),
947 provider_summary: payload.summary,
948 observations,
949 }
950}
951
952pub fn build_ai_review_dry_run_report(request: &AiReviewRequest) -> AiReviewReport {
953 build_ai_review_report(
954 request,
955 AiReviewProviderPayload {
956 summary: "Dry run only; no provider call was made.".to_string(),
957 observations: Vec::new(),
958 },
959 false,
960 )
961}
962
963pub fn ai_review_report_to_json(report: &AiReviewReport) -> String {
964 serde_json::to_string_pretty(report).expect("AI review report serialization cannot fail") + "\n"
965}
966
967pub fn render_ai_review_markdown(report: &AiReviewReport) -> String {
968 let mut out = String::new();
969 out.push_str("# DevImg AI Review\n\n");
970 out.push_str("AI observations are advisory and must be reviewed by a human before changing source images or configuration.\n\n");
971 out.push_str("## Summary\n\n");
972 out.push_str(&format!("- Provider: `{}`\n", report.provider.label()));
973 out.push_str(&format!("- Model: `{}`\n", report.model));
974 out.push_str(&format!("- Mode: `{}`\n", report.mode));
975 out.push_str(&format!("- Dry run: `{}`\n", report.dry_run));
976 out.push_str(&format!(
977 "- Provider called: `{}`\n",
978 report.provider_called
979 ));
980 out.push_str(&format!("- Manifest: `{}`\n", report.manifest_path));
981 out.push_str(&format!(
982 "- Outputs reviewed: `{}`\n",
983 report.summary.output_count
984 ));
985 out.push_str(&format!(
986 "- Image inputs selected: `{}`\n",
987 report.summary.selected_image_count
988 ));
989 out.push_str(&format!(
990 "- Observations: `{}`\n\n",
991 report.summary.observation_count
992 ));
993
994 if !report.review_signals.is_empty() {
995 out.push_str("## Deterministic Signals\n\n");
996 for signal in &report.review_signals {
997 out.push_str(&format!("- {signal}\n"));
998 }
999 out.push('\n');
1000 }
1001
1002 out.push_str("## Observations\n\n");
1003 if report.observations.is_empty() {
1004 out.push_str("No AI observations.\n");
1005 } else {
1006 for observation in &report.observations {
1007 out.push_str(&format!("### {}\n\n", observation.category));
1008 out.push_str(&format!("- Severity: `{}`\n", observation.severity));
1009 out.push_str(&format!("- Source: `{}`\n", observation.source_path));
1010 out.push_str(&format!("- Preset: `{}`\n", observation.preset));
1011 out.push_str(&format!("- Output: `{}`\n", observation.output_path));
1012 out.push_str(&format!("- Rationale: {}\n", observation.rationale));
1013 out.push_str(&format!(
1014 "- Suggested next command: `{}`\n\n",
1015 observation.suggested_next_command
1016 ));
1017 }
1018 }
1019 out
1020}
1021
1022pub fn build_ai_alt_request(manifest: &Manifest, options: &AiAltOptions) -> AiAltRequest {
1023 let max_images = options.max_images.max(1);
1024 let image_detail = options.image_detail.clone();
1025 let mut grouped = BTreeMap::<String, AiAltSourceBuilder>::new();
1026 for output in &manifest.outputs {
1027 let source = grouped
1028 .entry(output.source_path.clone())
1029 .or_insert_with(|| AiAltSourceBuilder {
1030 source_path: output.source_path.clone(),
1031 source_hash: output.source_hash.clone(),
1032 source_width: output.source_width,
1033 source_height: output.source_height,
1034 source_bytes: output.source_bytes,
1035 variants: Vec::new(),
1036 });
1037 source.variants.push(AiAltVariant {
1038 output_path: output.output_path.clone(),
1039 preset: output.preset.clone(),
1040 fit: output.fit.clone(),
1041 width: output.width,
1042 height: output.height,
1043 format: output.format.clone(),
1044 bytes: output.bytes,
1045 hash: output.hash.clone(),
1046 });
1047 }
1048
1049 let mut selected_images = Vec::new();
1050 let mut sources = Vec::new();
1051 for mut builder in grouped.into_values() {
1052 builder.variants.sort_by(|left, right| {
1053 left.preset
1054 .cmp(&right.preset)
1055 .then(left.width.cmp(&right.width))
1056 .then(left.height.cmp(&right.height))
1057 .then(left.format.cmp(&right.format))
1058 .then(left.output_path.cmp(&right.output_path))
1059 });
1060 let representative = builder.representative_image();
1061 let mut image_bytes_included = false;
1062 let mut image_detail_for_source = None;
1063 if options.include_images && selected_images.len() < max_images {
1064 if let Some(image) = representative.as_image_input(&builder.source_path, &image_detail)
1065 {
1066 image_bytes_included = true;
1067 image_detail_for_source = Some(image_detail.clone());
1068 selected_images.push(image);
1069 }
1070 }
1071
1072 sources.push(AiAltSource {
1073 source_path: builder.source_path,
1074 source_hash: builder.source_hash,
1075 source_width: builder.source_width,
1076 source_height: builder.source_height,
1077 source_bytes: builder.source_bytes,
1078 representative_image_path: representative.path,
1079 representative_image_width: representative.width,
1080 representative_image_height: representative.height,
1081 representative_image_format: representative.format,
1082 image_bytes_included,
1083 image_detail: image_detail_for_source,
1084 variants: builder.variants,
1085 });
1086 }
1087
1088 let skipped_image_count = if options.include_images {
1089 sources.len().saturating_sub(selected_images.len())
1090 } else {
1091 0
1092 };
1093 let mode = if options.include_images {
1094 "include-images"
1095 } else {
1096 "metadata-only"
1097 };
1098
1099 AiAltRequest {
1100 schema_version: 1,
1101 provider: options.provider,
1102 model: options.model.clone(),
1103 command: options.command.clone(),
1104 config_path: display_project_path(&options.project_root, &options.config_path),
1105 manifest_path: display_project_path(&options.project_root, &options.manifest_path),
1106 project_root: display_path(&options.project_root),
1107 mode: mode.to_string(),
1108 dry_run: options.dry_run,
1109 paths_included: true,
1110 image_bytes_included: options.include_images,
1111 image_detail,
1112 max_images,
1113 output_path: options
1114 .output_path
1115 .as_deref()
1116 .map(|path| display_project_path(&options.project_root, path)),
1117 markdown_path: options
1118 .markdown_path
1119 .as_deref()
1120 .map(|path| display_project_path(&options.project_root, path)),
1121 manifest_summary: AiAltManifestSummary {
1122 config_path: manifest.config_path.clone(),
1123 config_hash: manifest.config_hash.clone(),
1124 source_count: manifest_source_count(manifest),
1125 output_count: manifest.outputs.len(),
1126 source_bytes: manifest.source_bytes_total(),
1127 output_bytes: manifest.output_bytes_total(),
1128 },
1129 sources,
1130 selected_images,
1131 skipped_image_count,
1132 }
1133}
1134
1135pub fn build_ai_alt_report(
1136 request: &AiAltRequest,
1137 payload: AiAltProviderPayload,
1138 provider_called: bool,
1139) -> AiAltReport {
1140 let drafts = normalize_ai_alt_drafts(request, payload.drafts);
1141 AiAltReport {
1142 schema_version: request.schema_version,
1143 provider: request.provider,
1144 model: request.model.clone(),
1145 command: request.command.clone(),
1146 config_path: request.config_path.clone(),
1147 manifest_path: request.manifest_path.clone(),
1148 project_root: request.project_root.clone(),
1149 mode: request.mode.clone(),
1150 dry_run: request.dry_run,
1151 paths_included: request.paths_included,
1152 image_bytes_included: request.image_bytes_included,
1153 image_detail: request.image_detail.clone(),
1154 max_images: request.max_images,
1155 output_path: request.output_path.clone(),
1156 markdown_path: request.markdown_path.clone(),
1157 provider_called,
1158 summary: AiAltReportSummary {
1159 source_count: request.sources.len(),
1160 output_count: request.manifest_summary.output_count,
1161 selected_image_count: request.selected_images.len(),
1162 skipped_image_count: request.skipped_image_count,
1163 draft_count: drafts.len(),
1164 },
1165 sources: request.sources.clone(),
1166 selected_images: request.selected_images.clone(),
1167 provider_summary: payload.summary,
1168 drafts,
1169 }
1170}
1171
1172pub fn build_ai_alt_placeholder_report(request: &AiAltRequest) -> AiAltReport {
1173 let drafts = request
1174 .sources
1175 .iter()
1176 .map(|source| AiAltDraft {
1177 source_path: source.source_path.clone(),
1178 representative_image_path: source.representative_image_path.clone(),
1179 candidate_alt_text: String::new(),
1180 review_note: "Metadata-only placeholder; inspect the image and write human-reviewed alt text before application use.".to_string(),
1181 confidence: "low".to_string(),
1182 image_category: "unknown".to_string(),
1183 warnings: vec!["needs-human-review".to_string()],
1184 })
1185 .collect();
1186 build_ai_alt_report(
1187 request,
1188 AiAltProviderPayload {
1189 summary: "Metadata-only placeholder; no provider call was made.".to_string(),
1190 drafts,
1191 },
1192 false,
1193 )
1194}
1195
1196pub fn ai_alt_report_to_json(report: &AiAltReport) -> String {
1197 serde_json::to_string_pretty(report).expect("AI alt report serialization cannot fail") + "\n"
1198}
1199
1200pub fn render_ai_alt_markdown(report: &AiAltReport) -> String {
1201 let mut out = String::new();
1202 out.push_str("# DevImg Alt-Text Drafts\n\n");
1203 out.push_str("Alt text is draft content and must be reviewed by a human before application use. DevImg does not insert this text into application code.\n\n");
1204 out.push_str("## Summary\n\n");
1205 out.push_str(&format!("- Provider: `{}`\n", report.provider.label()));
1206 out.push_str(&format!("- Model: `{}`\n", report.model));
1207 out.push_str(&format!("- Mode: `{}`\n", report.mode));
1208 out.push_str(&format!("- Dry run: `{}`\n", report.dry_run));
1209 out.push_str(&format!(
1210 "- Provider called: `{}`\n",
1211 report.provider_called
1212 ));
1213 out.push_str(&format!("- Manifest: `{}`\n", report.manifest_path));
1214 out.push_str(&format!("- Sources: `{}`\n", report.summary.source_count));
1215 out.push_str(&format!(
1216 "- Image inputs selected: `{}`\n",
1217 report.summary.selected_image_count
1218 ));
1219 out.push_str(&format!("- Drafts: `{}`\n\n", report.summary.draft_count));
1220
1221 out.push_str("## Drafts\n\n");
1222 if report.drafts.is_empty() {
1223 out.push_str("No alt-text drafts.\n");
1224 } else {
1225 for draft in &report.drafts {
1226 out.push_str(&format!("### {}\n\n", draft.source_path));
1227 out.push_str(&format!(
1228 "- Representative image: `{}`\n",
1229 draft.representative_image_path
1230 ));
1231 out.push_str(&format!("- Category: `{}`\n", draft.image_category));
1232 out.push_str(&format!("- Confidence: `{}`\n", draft.confidence));
1233 out.push_str(&format!(
1234 "- Candidate alt text: {}\n",
1235 if draft.candidate_alt_text.is_empty() {
1236 "_No draft generated in metadata-only mode._"
1237 } else {
1238 draft.candidate_alt_text.as_str()
1239 }
1240 ));
1241 out.push_str(&format!("- Review note: {}\n", draft.review_note));
1242 if !draft.warnings.is_empty() {
1243 out.push_str(&format!("- Warnings: `{}`\n", draft.warnings.join("`, `")));
1244 }
1245 out.push('\n');
1246 }
1247 }
1248 out
1249}
1250
1251pub fn build_ai_draft_request(config: &Config, options: &AiDraftOptions) -> AiDraftRequest {
1252 let manifest_path =
1253 resolve_project_path_checked(config, &config.project.manifest, "manifest path")
1254 .unwrap_or_else(|_| config.project.root.join(&config.project.manifest));
1255 let report_path = resolve_project_path_checked(config, &config.project.report, "report path")
1256 .unwrap_or_else(|_| config.project.root.join(&config.project.report));
1257 let manifest_summary = summarize_draft_manifest(&manifest_path, &config.project.root);
1258 let report_summary =
1259 summarize_draft_artifact("devimg-report", &report_path, &config.project.root);
1260 let changelog_summary = options
1261 .changelog_path
1262 .as_ref()
1263 .map(|path| summarize_draft_artifact("changelog", path, &config.project.root));
1264 let mut optional_artifacts = Vec::new();
1265 if let Some(path) = &options.compare_json_path {
1266 optional_artifacts.push(summarize_draft_artifact(
1267 "compare-json",
1268 path,
1269 &config.project.root,
1270 ));
1271 }
1272 if let Some(path) = &options.ai_review_json_path {
1273 optional_artifacts.push(summarize_draft_artifact(
1274 "ai-review-json",
1275 path,
1276 &config.project.root,
1277 ));
1278 }
1279 if let Some(path) = &options.review_html_path {
1280 optional_artifacts.push(summarize_draft_artifact(
1281 "review-html",
1282 path,
1283 &config.project.root,
1284 ));
1285 }
1286
1287 AiDraftRequest {
1288 schema_version: 1,
1289 draft_type: options.draft_type,
1290 provider: options.provider,
1291 model: options.model.clone(),
1292 command: options.command.clone(),
1293 config_path: display_project_path(&options.project_root, &options.config_path),
1294 project_root: display_path(&options.project_root),
1295 mode: if options.provider.is_some() {
1296 "provider-draft".to_string()
1297 } else {
1298 "metadata-only".to_string()
1299 },
1300 dry_run: options.dry_run,
1301 output_path: display_project_path(&options.project_root, &options.output_path),
1302 manifest_summary,
1303 report_summary,
1304 changelog_summary,
1305 optional_artifacts,
1306 }
1307}
1308
1309pub fn build_ai_draft_report(
1310 request: &AiDraftRequest,
1311 payload: AiDraftProviderPayload,
1312 provider_called: bool,
1313) -> AiDraftReport {
1314 let sections = normalize_ai_draft_sections(request, payload.sections);
1315 AiDraftReport {
1316 schema_version: request.schema_version,
1317 draft_type: request.draft_type,
1318 provider: request.provider,
1319 model: request.model.clone(),
1320 command: request.command.clone(),
1321 config_path: request.config_path.clone(),
1322 project_root: request.project_root.clone(),
1323 mode: request.mode.clone(),
1324 dry_run: request.dry_run,
1325 output_path: request.output_path.clone(),
1326 provider_called,
1327 summary: AiDraftReportSummary {
1328 source_count: request.manifest_summary.source_count,
1329 output_count: request.manifest_summary.output_count,
1330 optional_artifact_count: request.optional_artifacts.len(),
1331 section_count: sections.len(),
1332 },
1333 manifest_summary: request.manifest_summary.clone(),
1334 report_summary: request.report_summary.clone(),
1335 changelog_summary: request.changelog_summary.clone(),
1336 optional_artifacts: request.optional_artifacts.clone(),
1337 provider_summary: sanitize_draft_text(&payload.summary, 800),
1338 sections,
1339 }
1340}
1341
1342pub fn build_ai_draft_placeholder_report(request: &AiDraftRequest) -> AiDraftReport {
1343 build_ai_draft_report(request, local_ai_draft_payload(request), false)
1344}
1345
1346pub fn ai_draft_report_to_json(report: &AiDraftReport) -> String {
1347 serde_json::to_string_pretty(report).expect("AI draft report serialization cannot fail") + "\n"
1348}
1349
1350pub fn render_ai_draft_markdown(report: &AiDraftReport) -> String {
1351 let mut out = String::new();
1352 out.push_str("# Draft; review before publishing\n\n");
1353 out.push_str("This Markdown is an advisory draft generated from DevImg metadata and optional local text artifacts. DevImg does not publish, commit, post, or edit application content.\n\n");
1354
1355 out.push_str("## Summary\n\n");
1356 out.push_str(&format!("- Draft type: `{}`\n", report.draft_type.label()));
1357 out.push_str(&format!("- Mode: `{}`\n", report.mode));
1358 out.push_str(&format!("- Dry run: `{}`\n", report.dry_run));
1359 out.push_str(&format!(
1360 "- Provider called: `{}`\n",
1361 report.provider_called
1362 ));
1363 if let Some(provider) = report.provider {
1364 out.push_str(&format!("- Provider: `{}`\n", provider.label()));
1365 }
1366 if let Some(model) = &report.model {
1367 out.push_str(&format!("- Model: `{model}`\n"));
1368 }
1369 out.push_str(&format!("- Config: `{}`\n", report.config_path));
1370 out.push_str(&format!("- Project root: `{}`\n", report.project_root));
1371 out.push_str(&format!("- Output: `{}`\n", report.output_path));
1372 out.push_str(&format!(
1373 "- Manifest outputs summarized: `{}`\n",
1374 report.summary.output_count
1375 ));
1376 out.push_str(&format!(
1377 "- Optional artifacts summarized: `{}`\n\n",
1378 report.summary.optional_artifact_count
1379 ));
1380
1381 out.push_str("## Source Context\n\n");
1382 push_draft_manifest_context(&mut out, &report.manifest_summary);
1383 push_draft_artifact_context(&mut out, "DevImg report", &report.report_summary);
1384 if let Some(changelog) = &report.changelog_summary {
1385 push_draft_artifact_context(&mut out, "Changelog", changelog);
1386 }
1387 for artifact in &report.optional_artifacts {
1388 push_draft_artifact_context(&mut out, &artifact.label, artifact);
1389 }
1390 out.push('\n');
1391
1392 out.push_str("## Draft\n\n");
1393 for section in &report.sections {
1394 out.push_str(&format!("### {}\n\n", section.heading));
1395 if !section.body.is_empty() {
1396 out.push_str(§ion.body);
1397 out.push_str("\n\n");
1398 }
1399 for bullet in §ion.bullets {
1400 out.push_str(&format!("- {bullet}\n"));
1401 }
1402 out.push('\n');
1403 }
1404
1405 out.push_str("## Review Checklist\n\n");
1406 out.push_str("- Confirm the prose against the current product behavior and release state.\n");
1407 out.push_str("- Remove placeholders, overclaims, and internal file paths before publishing.\n");
1408 out.push_str("- Keep this artifact uncommitted unless a human intentionally promotes it.\n");
1409 out
1410}
1411
1412fn summarize_draft_manifest(path: &Path, project_root: &Path) -> AiDraftManifestSummary {
1413 match read_manifest(path) {
1414 Ok(manifest) => {
1415 let mut outputs = manifest
1416 .outputs
1417 .iter()
1418 .map(|output| AiDraftManifestOutputSummary {
1419 source_path: output.source_path.clone(),
1420 output_path: output.output_path.clone(),
1421 preset: output.preset.clone(),
1422 fit: output.fit.clone(),
1423 width: output.width,
1424 height: output.height,
1425 format: output.format.clone(),
1426 bytes: output.bytes,
1427 })
1428 .collect::<Vec<_>>();
1429 outputs.sort_by(|left, right| {
1430 left.source_path
1431 .cmp(&right.source_path)
1432 .then(left.preset.cmp(&right.preset))
1433 .then(left.width.cmp(&right.width))
1434 .then(left.height.cmp(&right.height))
1435 .then(left.format.cmp(&right.format))
1436 .then(left.output_path.cmp(&right.output_path))
1437 });
1438 AiDraftManifestSummary {
1439 path: display_project_path(project_root, path),
1440 readable: true,
1441 read_error: None,
1442 config_hash: Some(manifest.config_hash.clone()),
1443 source_count: manifest_source_count(&manifest),
1444 output_count: manifest.outputs.len(),
1445 source_bytes: manifest.source_bytes_total(),
1446 output_bytes: manifest.output_bytes_total(),
1447 outputs,
1448 }
1449 }
1450 Err(error) => AiDraftManifestSummary {
1451 path: display_project_path(project_root, path),
1452 readable: false,
1453 read_error: Some(sanitize_draft_text(&error.to_string(), 240)),
1454 config_hash: None,
1455 source_count: 0,
1456 output_count: 0,
1457 source_bytes: 0,
1458 output_bytes: 0,
1459 outputs: Vec::new(),
1460 },
1461 }
1462}
1463
1464fn summarize_draft_artifact(
1465 label: &str,
1466 path: &Path,
1467 project_root: &Path,
1468) -> AiDraftArtifactSummary {
1469 match fs::read_to_string(path) {
1470 Ok(raw) => AiDraftArtifactSummary {
1471 label: label.to_string(),
1472 path: display_project_path(project_root, path),
1473 readable: true,
1474 read_error: None,
1475 bytes: raw.len() as u64,
1476 line_count: raw.lines().count(),
1477 excerpt: deterministic_draft_excerpt(&raw),
1478 },
1479 Err(source) => AiDraftArtifactSummary {
1480 label: label.to_string(),
1481 path: display_project_path(project_root, path),
1482 readable: false,
1483 read_error: Some(if source.kind() == ErrorKind::NotFound {
1484 "file not found".to_string()
1485 } else {
1486 sanitize_draft_text(&source.to_string(), 240)
1487 }),
1488 bytes: 0,
1489 line_count: 0,
1490 excerpt: String::new(),
1491 },
1492 }
1493}
1494
1495fn deterministic_draft_excerpt(raw: &str) -> String {
1496 sanitize_draft_text(raw, 4000)
1497}
1498
1499fn local_ai_draft_payload(request: &AiDraftRequest) -> AiDraftProviderPayload {
1500 let context = draft_context_bullets(request);
1501 let sections = match request.draft_type {
1502 AiDraftType::ReleaseNotes => vec![
1503 AiDraftSection {
1504 heading: "Release Notes Draft".to_string(),
1505 body: "Use this as a starting point for human-written release notes.".to_string(),
1506 bullets: context.clone(),
1507 },
1508 AiDraftSection {
1509 heading: "Validation Notes".to_string(),
1510 body: "Before publishing, confirm that every item maps to committed code, tests, and release artifacts.".to_string(),
1511 bullets: artifact_review_bullets(request),
1512 },
1513 ],
1514 AiDraftType::ReadmeSnippet => vec![
1515 AiDraftSection {
1516 heading: "README Snippet Draft".to_string(),
1517 body: "Add a concise, user-facing description of the DevImg image workflow and any generated artifacts that are relevant to this project.".to_string(),
1518 bullets: context.clone(),
1519 },
1520 AiDraftSection {
1521 heading: "Integration Notes".to_string(),
1522 body: "Keep commands copyable, avoid provider-key assumptions, and explain which outputs are generated versus human-authored.".to_string(),
1523 bullets: artifact_review_bullets(request),
1524 },
1525 ],
1526 AiDraftType::ProjectPageCopy => vec![
1527 AiDraftSection {
1528 heading: "Project Page Copy Draft".to_string(),
1529 body: "Position the project around deterministic image optimization, checked generated artifacts, and reviewable AI-assisted draft workflows.".to_string(),
1530 bullets: context.clone(),
1531 },
1532 AiDraftSection {
1533 heading: "Proof Points".to_string(),
1534 body: "Use concrete pipeline facts from the manifest and report instead of broad marketing claims.".to_string(),
1535 bullets: artifact_review_bullets(request),
1536 },
1537 ],
1538 AiDraftType::BlogOutline => vec![
1539 AiDraftSection {
1540 heading: "Blog Outline Draft".to_string(),
1541 body: "Frame the post around the problem, the DevImg workflow, verification, and what remains human-reviewed.".to_string(),
1542 bullets: context.clone(),
1543 },
1544 AiDraftSection {
1545 heading: "Sections To Fill".to_string(),
1546 body: "Turn each bullet into a short section only after verifying the current repository state.".to_string(),
1547 bullets: artifact_review_bullets(request),
1548 },
1549 ],
1550 AiDraftType::SocialPostOutline => vec![
1551 AiDraftSection {
1552 heading: "Social Post Outline Draft".to_string(),
1553 body: "Draft short post angles that point to concrete DevImg outcomes without implying automatic publication or unreviewed AI prose.".to_string(),
1554 bullets: context.clone(),
1555 },
1556 AiDraftSection {
1557 heading: "Post Variants".to_string(),
1558 body: "Keep each variant concise and review all claims before posting.".to_string(),
1559 bullets: artifact_review_bullets(request),
1560 },
1561 ],
1562 };
1563 AiDraftProviderPayload {
1564 summary: if request.provider.is_some() && request.dry_run {
1565 "Dry run only; no provider call was made.".to_string()
1566 } else {
1567 "Metadata-only draft; no provider call was made.".to_string()
1568 },
1569 sections,
1570 }
1571}
1572
1573fn draft_context_bullets(request: &AiDraftRequest) -> Vec<String> {
1574 let mut bullets = Vec::new();
1575 bullets.push(format!(
1576 "Summarized `{}` source image(s) and `{}` generated output(s).",
1577 request.manifest_summary.source_count, request.manifest_summary.output_count
1578 ));
1579 bullets.push(format!(
1580 "DevImg report `{}` is `{}`.",
1581 request.report_summary.path,
1582 if request.report_summary.readable {
1583 "readable"
1584 } else {
1585 "not readable"
1586 }
1587 ));
1588 if let Some(changelog) = &request.changelog_summary {
1589 bullets.push(format!(
1590 "Changelog `{}` is `{}`.",
1591 changelog.path,
1592 if changelog.readable {
1593 "readable"
1594 } else {
1595 "not readable"
1596 }
1597 ));
1598 }
1599 for artifact in &request.optional_artifacts {
1600 bullets.push(format!(
1601 "{} `{}` is `{}`.",
1602 artifact.label,
1603 artifact.path,
1604 if artifact.readable {
1605 "readable"
1606 } else {
1607 "not readable"
1608 }
1609 ));
1610 }
1611 bullets
1612}
1613
1614fn artifact_review_bullets(request: &AiDraftRequest) -> Vec<String> {
1615 let mut bullets = vec![
1616 "Treat this draft as review input, not publishable final copy.".to_string(),
1617 "Do not paste internal-only paths, command output, or generated file hashes into public prose without review.".to_string(),
1618 format!(
1619 "Run `{}` and inspect `{}` before using this draft.",
1620 request.command, request.output_path
1621 ),
1622 ];
1623 if request.provider.is_some() && request.dry_run {
1624 bullets.push("Dry-run provider mode did not call any external AI service.".to_string());
1625 }
1626 bullets
1627}
1628
1629fn normalize_ai_draft_sections(
1630 request: &AiDraftRequest,
1631 sections: Vec<AiDraftSection>,
1632) -> Vec<AiDraftSection> {
1633 let normalized = sections
1634 .into_iter()
1635 .filter_map(|section| {
1636 let heading = sanitize_draft_text(§ion.heading, 120);
1637 let body = sanitize_draft_text(§ion.body, 3000);
1638 let bullets = section
1639 .bullets
1640 .into_iter()
1641 .map(|bullet| sanitize_draft_text(&bullet, 500))
1642 .filter(|bullet| !bullet.is_empty())
1643 .collect::<Vec<_>>();
1644 if heading.is_empty() && body.is_empty() && bullets.is_empty() {
1645 None
1646 } else {
1647 Some(AiDraftSection {
1648 heading: if heading.is_empty() {
1649 request.draft_type.title().to_string()
1650 } else {
1651 heading
1652 },
1653 body,
1654 bullets,
1655 })
1656 }
1657 })
1658 .collect::<Vec<_>>();
1659
1660 if normalized.is_empty() {
1661 local_ai_draft_payload(request).sections
1662 } else {
1663 normalized
1664 }
1665}
1666
1667fn sanitize_draft_text(raw: &str, max_bytes: usize) -> String {
1668 let mut sanitized = String::new();
1669 for (index, line) in raw
1670 .replace("\r\n", "\n")
1671 .replace('\r', "\n")
1672 .lines()
1673 .enumerate()
1674 {
1675 if index > 0 {
1676 sanitized.push('\n');
1677 }
1678 if is_sensitive_draft_line(line) {
1679 sanitized.push_str("[redacted sensitive provider or image data]");
1680 } else {
1681 sanitized.push_str(line.trim_end());
1682 }
1683 }
1684
1685 truncate_to_bytes(sanitized.trim().to_string(), max_bytes)
1686}
1687
1688fn is_sensitive_draft_line(line: &str) -> bool {
1689 let lowered = line.to_ascii_lowercase();
1690 lowered.contains("openai_api_key")
1691 || lowered.contains("anthropic_api_key")
1692 || lowered.contains("data:image/")
1693 || lowered.contains(";base64,")
1694}
1695
1696fn truncate_to_bytes(value: String, max_bytes: usize) -> String {
1697 if value.len() <= max_bytes {
1698 return value;
1699 }
1700
1701 let mut end = 0;
1702 for (index, ch) in value.char_indices() {
1703 let next = index + ch.len_utf8();
1704 if next > max_bytes {
1705 break;
1706 }
1707 end = next;
1708 }
1709 let mut truncated = value[..end].trim_end().to_string();
1710 truncated.push_str("\n[excerpt truncated]");
1711 truncated
1712}
1713
1714fn push_draft_manifest_context(out: &mut String, manifest: &AiDraftManifestSummary) {
1715 out.push_str(&format!("- Manifest: `{}`\n", manifest.path));
1716 out.push_str(&format!("- Manifest readable: `{}`\n", manifest.readable));
1717 if let Some(error) = &manifest.read_error {
1718 out.push_str(&format!("- Manifest read note: {error}\n"));
1719 }
1720 out.push_str(&format!("- Sources: `{}`\n", manifest.source_count));
1721 out.push_str(&format!("- Outputs: `{}`\n", manifest.output_count));
1722 out.push_str(&format!("- Source bytes: `{}`\n", manifest.source_bytes));
1723 out.push_str(&format!("- Output bytes: `{}`\n", manifest.output_bytes));
1724 if !manifest.outputs.is_empty() {
1725 out.push_str("- Output presets:\n");
1726 for output in manifest.outputs.iter().take(12) {
1727 out.push_str(&format!(
1728 " - `{}` `{}` {}x{} `{}` (`{}` bytes)\n",
1729 output.source_path,
1730 output.preset,
1731 output.width,
1732 output.height,
1733 output.format,
1734 output.bytes
1735 ));
1736 }
1737 if manifest.outputs.len() > 12 {
1738 out.push_str(" - additional outputs omitted from Markdown context\n");
1739 }
1740 }
1741}
1742
1743fn push_draft_artifact_context(out: &mut String, label: &str, artifact: &AiDraftArtifactSummary) {
1744 out.push_str(&format!("- {label}: `{}`\n", artifact.path));
1745 out.push_str(&format!(" - Readable: `{}`\n", artifact.readable));
1746 if let Some(error) = &artifact.read_error {
1747 out.push_str(&format!(" - Read note: {error}\n"));
1748 }
1749 if artifact.readable {
1750 out.push_str(&format!(" - Bytes: `{}`\n", artifact.bytes));
1751 out.push_str(&format!(" - Lines: `{}`\n", artifact.line_count));
1752 if !artifact.excerpt.is_empty() {
1753 out.push_str(" - Excerpt:\n\n");
1754 out.push_str("```text\n");
1755 out.push_str(&artifact.excerpt);
1756 out.push_str("\n```\n");
1757 }
1758 }
1759}
1760
1761pub fn ai_image_mime_type(format: &str) -> Option<&'static str> {
1762 match format.to_ascii_lowercase().as_str() {
1763 "png" => Some("image/png"),
1764 "jpeg" | "jpg" => Some("image/jpeg"),
1765 "webp" => Some("image/webp"),
1766 "gif" => Some("image/gif"),
1767 _ => None,
1768 }
1769}
1770
1771#[derive(Debug, Clone, PartialEq, Eq)]
1772struct AiAltSourceBuilder {
1773 source_path: String,
1774 source_hash: String,
1775 source_width: u32,
1776 source_height: u32,
1777 source_bytes: u64,
1778 variants: Vec<AiAltVariant>,
1779}
1780
1781impl AiAltSourceBuilder {
1782 fn representative_image(&self) -> AiAltRepresentativeImage {
1783 let source_format = path_extension(&self.source_path);
1784 if ai_image_mime_type(&source_format).is_some() {
1785 return AiAltRepresentativeImage {
1786 path: self.source_path.clone(),
1787 width: self.source_width,
1788 height: self.source_height,
1789 format: source_format,
1790 bytes: self.source_bytes,
1791 hash: self.source_hash.clone(),
1792 };
1793 }
1794
1795 self.variants
1796 .iter()
1797 .filter(|variant| ai_image_mime_type(&variant.format).is_some())
1798 .max_by_key(|variant| u64::from(variant.width) * u64::from(variant.height))
1799 .map(|variant| AiAltRepresentativeImage {
1800 path: variant.output_path.clone(),
1801 width: variant.width,
1802 height: variant.height,
1803 format: variant.format.clone(),
1804 bytes: variant.bytes,
1805 hash: variant.hash.clone(),
1806 })
1807 .or_else(|| {
1808 self.variants
1809 .first()
1810 .map(|variant| AiAltRepresentativeImage {
1811 path: variant.output_path.clone(),
1812 width: variant.width,
1813 height: variant.height,
1814 format: variant.format.clone(),
1815 bytes: variant.bytes,
1816 hash: variant.hash.clone(),
1817 })
1818 })
1819 .unwrap_or_else(|| AiAltRepresentativeImage {
1820 path: self.source_path.clone(),
1821 width: self.source_width,
1822 height: self.source_height,
1823 format: source_format,
1824 bytes: self.source_bytes,
1825 hash: self.source_hash.clone(),
1826 })
1827 }
1828}
1829
1830#[derive(Debug, Clone, PartialEq, Eq)]
1831struct AiAltRepresentativeImage {
1832 path: String,
1833 width: u32,
1834 height: u32,
1835 format: String,
1836 bytes: u64,
1837 hash: String,
1838}
1839
1840impl AiAltRepresentativeImage {
1841 fn as_image_input(&self, source_path: &str, detail: &str) -> Option<AiAltImageInput> {
1842 ai_image_mime_type(&self.format).map(|mime_type| AiAltImageInput {
1843 source_path: source_path.to_string(),
1844 image_path: self.path.clone(),
1845 mime_type: mime_type.to_string(),
1846 width: self.width,
1847 height: self.height,
1848 bytes: self.bytes,
1849 hash: self.hash.clone(),
1850 detail: detail.to_string(),
1851 })
1852 }
1853}
1854
1855fn display_path(path: &Path) -> String {
1856 let rendered = path_to_string(path);
1857 if rendered.is_empty() {
1858 ".".to_string()
1859 } else {
1860 rendered
1861 }
1862}
1863
1864fn display_project_path(project_root: &Path, path: &Path) -> String {
1865 let absolute = if path.is_absolute() {
1866 path.to_path_buf()
1867 } else {
1868 project_root.join(path)
1869 };
1870 absolute
1871 .strip_prefix(project_root)
1872 .map(path_to_string)
1873 .unwrap_or_else(|_| path_to_string(path))
1874}
1875
1876fn manifest_source_count(manifest: &Manifest) -> usize {
1877 manifest
1878 .outputs
1879 .iter()
1880 .map(|output| output.source_path.as_str())
1881 .collect::<BTreeSet<_>>()
1882 .len()
1883}
1884
1885fn path_extension(path: &str) -> String {
1886 Path::new(path)
1887 .extension()
1888 .and_then(|extension| extension.to_str())
1889 .unwrap_or("unknown")
1890 .to_ascii_lowercase()
1891}
1892
1893fn normalize_ai_review_observation(mut observation: AiReviewObservation) -> AiReviewObservation {
1894 observation.severity = "advisory".to_string();
1895 observation.category = normalize_observation_category(&observation.category).to_string();
1896 observation
1897}
1898
1899fn normalize_observation_category(category: &str) -> &'static str {
1900 match category {
1901 "crop risk" => "crop risk",
1902 "readability risk" => "readability risk",
1903 "excessive padding" => "excessive padding",
1904 "low-resolution source" => "low-resolution source",
1905 "format-quality concern" => "format-quality concern",
1906 "accessibility note" => "accessibility note",
1907 _ => "format-quality concern",
1908 }
1909}
1910
1911fn normalize_ai_alt_drafts(request: &AiAltRequest, drafts: Vec<AiAltDraft>) -> Vec<AiAltDraft> {
1912 let mut by_source = drafts
1913 .into_iter()
1914 .map(|mut draft| {
1915 draft.confidence = normalize_alt_confidence(&draft.confidence).to_string();
1916 draft.image_category = normalize_alt_category(&draft.image_category).to_string();
1917 draft.warnings = normalize_alt_warnings(draft.warnings);
1918 draft
1919 })
1920 .map(|draft| (draft.source_path.clone(), draft))
1921 .collect::<BTreeMap<_, _>>();
1922
1923 request
1924 .sources
1925 .iter()
1926 .map(|source| {
1927 let mut draft = by_source
1928 .remove(&source.source_path)
1929 .unwrap_or_else(|| AiAltDraft {
1930 source_path: source.source_path.clone(),
1931 representative_image_path: source.representative_image_path.clone(),
1932 candidate_alt_text: String::new(),
1933 review_note: "Provider did not return a draft for this source; write human-reviewed alt text manually.".to_string(),
1934 confidence: "low".to_string(),
1935 image_category: "unknown".to_string(),
1936 warnings: vec!["needs-human-review".to_string()],
1937 });
1938 draft.source_path = source.source_path.clone();
1939 draft.representative_image_path = source.representative_image_path.clone();
1940 draft
1941 })
1942 .collect()
1943}
1944
1945fn normalize_alt_confidence(confidence: &str) -> &'static str {
1946 match confidence {
1947 "low" => "low",
1948 "medium" => "medium",
1949 "high" => "high",
1950 _ => "low",
1951 }
1952}
1953
1954fn normalize_alt_category(category: &str) -> &'static str {
1955 match category {
1956 "content-photo" => "content-photo",
1957 "screenshot" => "screenshot",
1958 "logo" => "logo",
1959 "illustration" => "illustration",
1960 "diagram" => "diagram",
1961 "icon" => "icon",
1962 "decorative" => "decorative",
1963 "text-heavy" => "text-heavy",
1964 "unknown" => "unknown",
1965 _ => "unknown",
1966 }
1967}
1968
1969fn normalize_alt_warnings(warnings: Vec<String>) -> Vec<String> {
1970 let mut normalized = warnings
1971 .into_iter()
1972 .map(|warning| match warning.as_str() {
1973 "decorative" => "decorative",
1974 "text-heavy" => "text-heavy",
1975 "logo" => "logo",
1976 "screenshot" => "screenshot",
1977 "uncertain-description" => "uncertain-description",
1978 "needs-human-review" => "needs-human-review",
1979 _ => "needs-human-review",
1980 })
1981 .map(ToString::to_string)
1982 .collect::<BTreeSet<_>>()
1983 .into_iter()
1984 .collect::<Vec<_>>();
1985 if normalized.is_empty() {
1986 normalized.push("needs-human-review".to_string());
1987 }
1988 normalized
1989}
1990
1991#[cfg(test)]
1992mod tests {
1993 use std::path::PathBuf;
1994
1995 use super::{
1996 ai_alt_report_to_json, ai_consent_preview_to_json, ai_image_mime_type,
1997 ai_review_report_to_json, build_ai_alt_placeholder_report, build_ai_alt_report,
1998 build_ai_alt_request, build_ai_draft_placeholder_report, build_ai_draft_report,
1999 build_ai_review_dry_run_report, build_ai_review_report, build_ai_review_request,
2000 render_ai_alt_markdown, render_ai_draft_markdown, render_ai_review_markdown, AiAltOptions,
2001 AiAltProviderClient, AiConsentPreview, AiDraftArtifactSummary, AiDraftManifestSummary,
2002 AiDraftProviderClient, AiDraftRequest, AiDraftSection, AiDraftType, AiGeneratedOutput,
2003 AiProvider, AiProviderClient, AiReviewOptions, AiReviewProviderClient, AiSelectedFile,
2004 MockAiAltProviderClient, MockAiDraftProviderClient, MockAiProviderClient,
2005 MockAiReviewProviderClient,
2006 };
2007 use crate::manifest::{Manifest, ManifestOutput};
2008
2009 #[test]
2010 fn provider_labels_and_env_vars_are_stable() {
2011 assert_eq!(AiProvider::Openai.label(), "openai");
2012 assert_eq!(AiProvider::Openai.credential_env_var(), "OPENAI_API_KEY");
2013 assert_eq!(AiProvider::Anthropic.label(), "anthropic");
2014 assert_eq!(
2015 AiProvider::Anthropic.credential_env_var(),
2016 "ANTHROPIC_API_KEY"
2017 );
2018 }
2019
2020 #[test]
2021 fn mock_provider_client_returns_stable_non_network_response() {
2022 let preview = AiConsentPreview {
2023 provider: AiProvider::Openai,
2024 model: "test-model".to_string(),
2025 command: "devimg ai consent".to_string(),
2026 config_path: "devimg.toml".to_string(),
2027 project_root: ".".to_string(),
2028 mode: "metadata-only".to_string(),
2029 dry_run: true,
2030 paths_included: true,
2031 image_bytes_included: false,
2032 output_path: None,
2033 manifest_path: "public/images/devimg-manifest.json".to_string(),
2034 report_path: "devimg-report.md".to_string(),
2035 manifest_readable: false,
2036 source_files: vec![AiSelectedFile {
2037 source_name: "portfolio".to_string(),
2038 path: "assets/images/sample.png".to_string(),
2039 role: "source-image".to_string(),
2040 width: 100,
2041 height: 50,
2042 format: "png".to_string(),
2043 bytes: 12,
2044 hash: "blake3:source".to_string(),
2045 image_bytes_included: false,
2046 }],
2047 generated_outputs: vec![AiGeneratedOutput {
2048 source_path: "assets/images/sample.png".to_string(),
2049 output_path: "public/images/generated/sample.webp".to_string(),
2050 preset: "card".to_string(),
2051 fit: "cover".to_string(),
2052 width: 64,
2053 height: 36,
2054 format: "webp".to_string(),
2055 bytes: 10,
2056 hash: "blake3:output".to_string(),
2057 }],
2058 };
2059
2060 let response = MockAiProviderClient::new(AiProvider::Anthropic).consent_response(&preview);
2061
2062 assert_eq!(response.provider, AiProvider::Anthropic);
2063 assert_eq!(response.model, "test-model");
2064 assert_eq!(response.request_kind, "consent-preview");
2065 assert!(!response.network_called);
2066 assert_eq!(response.selected_file_count, 1);
2067 assert_eq!(response.generated_output_count, 1);
2068 }
2069
2070 #[test]
2071 fn consent_preview_json_is_timestamp_free() {
2072 let preview = AiConsentPreview {
2073 provider: AiProvider::Anthropic,
2074 model: "stable-model".to_string(),
2075 command: "devimg ai consent".to_string(),
2076 config_path: "devimg.toml".to_string(),
2077 project_root: ".".to_string(),
2078 mode: "metadata-only".to_string(),
2079 dry_run: true,
2080 paths_included: true,
2081 image_bytes_included: false,
2082 output_path: Some("/tmp/consent.json".to_string()),
2083 manifest_path: "public/images/devimg-manifest.json".to_string(),
2084 report_path: "devimg-report.md".to_string(),
2085 manifest_readable: false,
2086 source_files: Vec::new(),
2087 generated_outputs: Vec::new(),
2088 };
2089
2090 let json = ai_consent_preview_to_json(&preview);
2091
2092 assert!(json.contains("\"provider\": \"anthropic\""));
2093 assert!(json.contains("\"model\": \"stable-model\""));
2094 assert!(!json.contains("generated_at"));
2095 assert!(!json.contains("timestamp"));
2096 }
2097
2098 #[test]
2099 fn ai_review_request_selects_metadata_and_image_inputs() {
2100 let manifest = sample_manifest();
2101 let request = build_ai_review_request(
2102 &manifest,
2103 &AiReviewOptions {
2104 provider: AiProvider::Openai,
2105 model: "vision-model".to_string(),
2106 command: "devimg review --ai".to_string(),
2107 manifest_path: PathBuf::from("/repo/public/images/devimg-manifest.json"),
2108 project_root: PathBuf::from("/repo"),
2109 dry_run: true,
2110 include_images: true,
2111 image_detail: "low".to_string(),
2112 max_images: 1,
2113 ai_output_path: Some(PathBuf::from("/repo/devimg-ai-review.json")),
2114 markdown_path: Some(PathBuf::from("/tmp/devimg-ai-review.md")),
2115 },
2116 );
2117
2118 assert_eq!(request.provider, AiProvider::Openai);
2119 assert_eq!(request.mode, "include-images");
2120 assert_eq!(request.manifest_path, "public/images/devimg-manifest.json");
2121 assert_eq!(
2122 request.ai_output_path.as_deref(),
2123 Some("devimg-ai-review.json")
2124 );
2125 assert_eq!(
2126 request.markdown_path.as_deref(),
2127 Some("/tmp/devimg-ai-review.md")
2128 );
2129 assert_eq!(request.manifest_summary.source_count, 1);
2130 assert_eq!(request.manifest_summary.output_count, 2);
2131 assert_eq!(request.outputs.len(), 2);
2132 assert_eq!(request.selected_images.len(), 1);
2133 assert_eq!(request.selected_images[0].mime_type, "image/webp");
2134 let webp_output = request
2135 .outputs
2136 .iter()
2137 .find(|output| output.format == "webp")
2138 .expect("webp output exists");
2139 let avif_output = request
2140 .outputs
2141 .iter()
2142 .find(|output| output.format == "avif")
2143 .expect("avif output exists");
2144 assert!(webp_output.image_bytes_included);
2145 assert!(!avif_output.image_bytes_included);
2146 assert_eq!(request.skipped_image_count, 1);
2147 }
2148
2149 #[test]
2150 fn ai_review_dry_run_json_and_markdown_are_timestamp_free() {
2151 let manifest = sample_manifest();
2152 let request = build_ai_review_request(
2153 &manifest,
2154 &AiReviewOptions {
2155 provider: AiProvider::Openai,
2156 model: "dry-run-model".to_string(),
2157 command: "devimg review --ai".to_string(),
2158 manifest_path: PathBuf::from("public/images/devimg-manifest.json"),
2159 project_root: PathBuf::from("."),
2160 dry_run: true,
2161 include_images: false,
2162 image_detail: "low".to_string(),
2163 max_images: 8,
2164 ai_output_path: None,
2165 markdown_path: None,
2166 },
2167 );
2168 let report = build_ai_review_dry_run_report(&request);
2169 let json = ai_review_report_to_json(&report);
2170 let markdown = render_ai_review_markdown(&report);
2171
2172 assert!(json.contains("\"provider\": \"openai\""));
2173 assert!(json.contains("\"dry_run\": true"));
2174 assert!(json.contains("\"provider_called\": false"));
2175 assert!(!json.contains("generated_at"));
2176 assert!(!json.contains("timestamp"));
2177 assert!(markdown.contains("# DevImg AI Review"));
2178 assert!(markdown.contains("Dry run: `true`"));
2179 }
2180
2181 #[test]
2182 fn mock_ai_review_provider_returns_stable_payload_and_failure() {
2183 let manifest = sample_manifest();
2184 let request = build_ai_review_request(
2185 &manifest,
2186 &AiReviewOptions {
2187 provider: AiProvider::Anthropic,
2188 model: "mock-model".to_string(),
2189 command: "devimg review --ai".to_string(),
2190 manifest_path: PathBuf::from("public/images/devimg-manifest.json"),
2191 project_root: PathBuf::from("."),
2192 dry_run: false,
2193 include_images: false,
2194 image_detail: "low".to_string(),
2195 max_images: 8,
2196 ai_output_path: None,
2197 markdown_path: None,
2198 },
2199 );
2200
2201 let payload = MockAiReviewProviderClient::new(AiProvider::Anthropic)
2202 .review(&request)
2203 .expect("mock provider succeeds");
2204 let report = build_ai_review_report(&request, payload, true);
2205
2206 assert!(report.provider_called);
2207 assert_eq!(report.provider_summary, "mock anthropic AI review");
2208 assert_eq!(report.observations.len(), 1);
2209 assert_eq!(report.observations[0].severity, "advisory");
2210
2211 let error = MockAiReviewProviderClient::failing(AiProvider::Openai)
2212 .review(&request)
2213 .expect_err("mock provider fails");
2214 assert!(error
2215 .to_string()
2216 .contains("mock AI review provider failure"));
2217 }
2218
2219 #[test]
2220 fn ai_alt_request_groups_sources_and_selects_representative_images() {
2221 let manifest = sample_manifest();
2222 let request = build_ai_alt_request(
2223 &manifest,
2224 &AiAltOptions {
2225 provider: AiProvider::Openai,
2226 model: "alt-model".to_string(),
2227 command: "devimg alt".to_string(),
2228 config_path: PathBuf::from("/repo/devimg.toml"),
2229 manifest_path: PathBuf::from("/repo/public/images/devimg-manifest.json"),
2230 project_root: PathBuf::from("/repo"),
2231 dry_run: true,
2232 include_images: true,
2233 image_detail: "low".to_string(),
2234 max_images: 1,
2235 output_path: Some(PathBuf::from("/repo/devimg-alt.json")),
2236 markdown_path: Some(PathBuf::from("/tmp/devimg-alt.md")),
2237 },
2238 );
2239
2240 assert_eq!(request.provider, AiProvider::Openai);
2241 assert_eq!(request.mode, "include-images");
2242 assert_eq!(request.config_path, "devimg.toml");
2243 assert_eq!(request.manifest_path, "public/images/devimg-manifest.json");
2244 assert_eq!(request.output_path.as_deref(), Some("devimg-alt.json"));
2245 assert_eq!(request.markdown_path.as_deref(), Some("/tmp/devimg-alt.md"));
2246 assert_eq!(request.sources.len(), 1);
2247 assert_eq!(request.sources[0].variants.len(), 2);
2248 assert_eq!(
2249 request.sources[0].representative_image_path,
2250 "assets/images/sample.png"
2251 );
2252 assert!(request.sources[0].image_bytes_included);
2253 assert_eq!(request.selected_images.len(), 1);
2254 assert_eq!(request.selected_images[0].mime_type, "image/png");
2255 assert_eq!(request.skipped_image_count, 0);
2256 }
2257
2258 #[test]
2259 fn ai_alt_placeholder_json_and_markdown_are_timestamp_free() {
2260 let manifest = sample_manifest();
2261 let request = build_ai_alt_request(
2262 &manifest,
2263 &AiAltOptions {
2264 provider: AiProvider::Openai,
2265 model: "dry-run-model".to_string(),
2266 command: "devimg alt".to_string(),
2267 config_path: PathBuf::from("devimg.toml"),
2268 manifest_path: PathBuf::from("public/images/devimg-manifest.json"),
2269 project_root: PathBuf::from("."),
2270 dry_run: true,
2271 include_images: false,
2272 image_detail: "low".to_string(),
2273 max_images: 8,
2274 output_path: None,
2275 markdown_path: None,
2276 },
2277 );
2278 let report = build_ai_alt_placeholder_report(&request);
2279 let json = ai_alt_report_to_json(&report);
2280 let markdown = render_ai_alt_markdown(&report);
2281
2282 assert!(json.contains("\"provider\": \"openai\""));
2283 assert!(json.contains("\"provider_called\": false"));
2284 assert!(json.contains("\"candidate_alt_text\": \"\""));
2285 assert!(!json.contains("generated_at"));
2286 assert!(!json.contains("timestamp"));
2287 assert!(markdown.contains("# DevImg Alt-Text Drafts"));
2288 assert!(markdown.contains("Provider called: `false`"));
2289 assert!(markdown.contains("_No draft generated in metadata-only mode._"));
2290 }
2291
2292 #[test]
2293 fn mock_ai_alt_provider_returns_stable_payload_and_failure() {
2294 let manifest = sample_manifest();
2295 let request = build_ai_alt_request(
2296 &manifest,
2297 &AiAltOptions {
2298 provider: AiProvider::Anthropic,
2299 model: "mock-model".to_string(),
2300 command: "devimg alt".to_string(),
2301 config_path: PathBuf::from("devimg.toml"),
2302 manifest_path: PathBuf::from("public/images/devimg-manifest.json"),
2303 project_root: PathBuf::from("."),
2304 dry_run: false,
2305 include_images: false,
2306 image_detail: "low".to_string(),
2307 max_images: 8,
2308 output_path: None,
2309 markdown_path: None,
2310 },
2311 );
2312
2313 let payload = MockAiAltProviderClient::new(AiProvider::Anthropic)
2314 .alt(&request)
2315 .expect("mock provider succeeds");
2316 let report = build_ai_alt_report(&request, payload, true);
2317
2318 assert!(report.provider_called);
2319 assert_eq!(report.provider_summary, "mock anthropic alt text");
2320 assert_eq!(report.drafts.len(), 1);
2321 assert_eq!(report.drafts[0].confidence, "medium");
2322 assert_eq!(report.drafts[0].warnings, vec!["needs-human-review"]);
2323
2324 let error = MockAiAltProviderClient::failing(AiProvider::Openai)
2325 .alt(&request)
2326 .expect_err("mock provider fails");
2327 assert!(error.to_string().contains("mock AI alt provider failure"));
2328 }
2329
2330 #[test]
2331 fn ai_draft_placeholder_markdown_is_timestamp_free_and_review_marked() {
2332 let request = sample_draft_request(AiDraftType::ProjectPageCopy, None, None, true);
2333 let report = build_ai_draft_placeholder_report(&request);
2334 let markdown = render_ai_draft_markdown(&report);
2335 let json = serde_json::to_string_pretty(&report).expect("draft report serializes");
2336
2337 assert_eq!(report.draft_type, AiDraftType::ProjectPageCopy);
2338 assert_eq!(report.mode, "metadata-only");
2339 assert!(!report.provider_called);
2340 assert_eq!(report.summary.source_count, 1);
2341 assert_eq!(report.summary.output_count, 2);
2342 assert!(markdown.starts_with("# Draft; review before publishing"));
2343 assert!(markdown.contains("- Draft type: `project-page-copy`"));
2344 assert!(markdown.contains("- Provider called: `false`"));
2345 assert!(markdown.contains("## Draft"));
2346 assert!(!markdown.contains("generated_at"));
2347 assert!(!json.contains("timestamp"));
2348 }
2349
2350 #[test]
2351 fn mock_ai_draft_provider_returns_stable_payload_and_failure() {
2352 let request = sample_draft_request(
2353 AiDraftType::ReleaseNotes,
2354 Some(AiProvider::Anthropic),
2355 Some("mock-model".to_string()),
2356 false,
2357 );
2358
2359 let payload = MockAiDraftProviderClient::new(AiProvider::Anthropic)
2360 .draft(&request)
2361 .expect("mock provider succeeds");
2362 let report = build_ai_draft_report(&request, payload, true);
2363
2364 assert!(report.provider_called);
2365 assert_eq!(report.provider_summary, "mock anthropic draft");
2366 assert_eq!(report.sections.len(), 2);
2367 assert_eq!(report.sections[0].heading, "Release Notes");
2368
2369 let error = MockAiDraftProviderClient::failing(AiProvider::Openai)
2370 .draft(&request)
2371 .expect_err("mock provider fails");
2372 assert!(error.to_string().contains("mock AI draft provider failure"));
2373 }
2374
2375 #[test]
2376 fn ai_draft_provider_payload_is_normalized_before_markdown() {
2377 let request = sample_draft_request(
2378 AiDraftType::BlogOutline,
2379 Some(AiProvider::Openai),
2380 Some("draft-model".to_string()),
2381 false,
2382 );
2383 let report = build_ai_draft_report(
2384 &request,
2385 super::AiDraftProviderPayload {
2386 summary: "summary with data:image/png;base64,abc".to_string(),
2387 sections: vec![AiDraftSection {
2388 heading: String::new(),
2389 body: "body\nOPENAI_API_KEY=test-secret\nok".to_string(),
2390 bullets: vec!["ANTHROPIC_API_KEY=test-secret".to_string()],
2391 }],
2392 },
2393 true,
2394 );
2395 let markdown = render_ai_draft_markdown(&report);
2396
2397 assert_eq!(
2398 report.provider_summary,
2399 "[redacted sensitive provider or image data]"
2400 );
2401 assert_eq!(report.sections[0].heading, "Blog Outline");
2402 assert!(!markdown.contains("test-secret"));
2403 assert!(!markdown.contains("data:image"));
2404 assert!(markdown.contains("[redacted sensitive provider or image data]"));
2405 }
2406
2407 #[test]
2408 fn ai_image_mime_type_matches_openai_supported_inputs() {
2409 assert_eq!(ai_image_mime_type("png"), Some("image/png"));
2410 assert_eq!(ai_image_mime_type("jpeg"), Some("image/jpeg"));
2411 assert_eq!(ai_image_mime_type("jpg"), Some("image/jpeg"));
2412 assert_eq!(ai_image_mime_type("webp"), Some("image/webp"));
2413 assert_eq!(ai_image_mime_type("gif"), Some("image/gif"));
2414 assert_eq!(ai_image_mime_type("avif"), None);
2415 }
2416
2417 fn sample_manifest() -> Manifest {
2418 Manifest {
2419 version: 1,
2420 generated_at: "unix:123".to_string(),
2421 config_path: "devimg.toml".to_string(),
2422 config_hash: "blake3:config".to_string(),
2423 outputs: vec![
2424 ManifestOutput {
2425 source_path: "assets/images/sample.png".to_string(),
2426 source_hash: "blake3:source".to_string(),
2427 source_width: 100,
2428 source_height: 80,
2429 source_bytes: 1000,
2430 output_path: "public/images/generated/sample.project-card.64.webp".to_string(),
2431 preset: "project-card".to_string(),
2432 fit: "cover".to_string(),
2433 width: 64,
2434 height: 64,
2435 format: "webp".to_string(),
2436 bytes: 700,
2437 hash: "blake3:webp".to_string(),
2438 operation_hash: "blake3:operation-webp".to_string(),
2439 },
2440 ManifestOutput {
2441 source_path: "assets/images/sample.png".to_string(),
2442 source_hash: "blake3:source".to_string(),
2443 source_width: 100,
2444 source_height: 80,
2445 source_bytes: 1000,
2446 output_path: "public/images/generated/sample.project-card.64.avif".to_string(),
2447 preset: "project-card".to_string(),
2448 fit: "cover".to_string(),
2449 width: 64,
2450 height: 64,
2451 format: "avif".to_string(),
2452 bytes: 600,
2453 hash: "blake3:avif".to_string(),
2454 operation_hash: "blake3:operation-avif".to_string(),
2455 },
2456 ],
2457 }
2458 }
2459
2460 fn sample_draft_request(
2461 draft_type: AiDraftType,
2462 provider: Option<AiProvider>,
2463 model: Option<String>,
2464 dry_run: bool,
2465 ) -> AiDraftRequest {
2466 AiDraftRequest {
2467 schema_version: 1,
2468 draft_type,
2469 provider,
2470 model,
2471 command: "devimg draft".to_string(),
2472 config_path: "devimg.toml".to_string(),
2473 project_root: ".".to_string(),
2474 mode: if provider.is_some() {
2475 "provider-draft".to_string()
2476 } else {
2477 "metadata-only".to_string()
2478 },
2479 dry_run,
2480 output_path: "devimg-draft.md".to_string(),
2481 manifest_summary: AiDraftManifestSummary {
2482 path: "public/images/devimg-manifest.json".to_string(),
2483 readable: true,
2484 read_error: None,
2485 config_hash: Some("blake3:config".to_string()),
2486 source_count: 1,
2487 output_count: 2,
2488 source_bytes: 1000,
2489 output_bytes: 1300,
2490 outputs: Vec::new(),
2491 },
2492 report_summary: AiDraftArtifactSummary {
2493 label: "devimg-report".to_string(),
2494 path: "devimg-report.md".to_string(),
2495 readable: true,
2496 read_error: None,
2497 bytes: 120,
2498 line_count: 4,
2499 excerpt: "Dev Image Pipeline Report".to_string(),
2500 },
2501 changelog_summary: None,
2502 optional_artifacts: Vec::new(),
2503 }
2504 }
2505}