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