Skip to main content

devimg_core/
suggest.rs

1use serde::Serialize;
2use serde_json::{json, Value};
3use std::collections::{BTreeMap, BTreeSet};
4
5use crate::config::{project_relative, resolve_project_path_checked, Config};
6use crate::doctor::{doctor, DoctorDiagnostic, DoctorOptions};
7use crate::manifest::{read_manifest, ManifestOutput};
8use crate::pipeline::{path_to_string, Operation};
9use crate::warnings::{
10    split_code_and_message, warning_info, BUDGET_FAILED, PLAN_NO_VARIANTS, QUALITY_ALLOWED_UPSCALE,
11    QUALITY_COVER_CROP, QUALITY_GENERATED_UPSCALE, QUALITY_LOW_LOSSY,
12    QUALITY_OUTPUT_LARGER_THAN_SOURCE, QUALITY_SKIPPED_UPSCALE,
13};
14use crate::{build_plan, scan_sources, DevimgError, Result};
15
16const SUGGESTION_VERSION: u32 = 1;
17const DEFAULT_CONFIG_PATH: &str = "devimg.toml";
18
19#[derive(Debug, Clone, Copy)]
20pub struct SuggestOptions {
21    pub metadata_only: bool,
22}
23
24impl Default for SuggestOptions {
25    fn default() -> Self {
26        Self {
27            metadata_only: true,
28        }
29    }
30}
31
32#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
33pub struct SuggestionReport {
34    pub version: u32,
35    pub config_path: String,
36    pub mode: String,
37    pub summary: SuggestionSummary,
38    pub items: Vec<SuggestionItem>,
39}
40
41#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
42pub struct SuggestionSummary {
43    pub suggestion_count: usize,
44    pub error_count: usize,
45    pub warning_count: usize,
46    pub advisory_count: usize,
47}
48
49#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
50pub struct SuggestionItem {
51    pub id: String,
52    pub source_path: Option<String>,
53    pub source_kind: Option<String>,
54    pub output_path: Option<String>,
55    pub preset: Option<String>,
56    pub width: Option<u32>,
57    pub format: Option<String>,
58    pub warning_code: String,
59    pub severity: String,
60    pub acknowledged: bool,
61    pub rationale: String,
62    pub suggested_config: Option<SuggestedConfigPatch>,
63    pub commands: Vec<String>,
64}
65
66#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
67pub struct SuggestedConfigPatch {
68    pub target: String,
69    pub source_path: Option<String>,
70    pub preset: Option<String>,
71    pub changes: BTreeMap<String, Value>,
72    pub toml_hint: String,
73}
74
75#[derive(Debug, Clone)]
76struct SuggestionMetadata {
77    source_path: String,
78    output_path: String,
79    preset: String,
80    width: u32,
81    format: String,
82}
83
84#[derive(Debug, Default)]
85struct SuggestionContext {
86    operations_by_output: BTreeMap<String, SuggestionMetadata>,
87    operations_by_source_preset_width: BTreeMap<(String, String, u32), Vec<SuggestionMetadata>>,
88    outputs_by_output: BTreeMap<String, SuggestionMetadata>,
89    source_paths: BTreeSet<String>,
90}
91
92#[derive(Debug, Default)]
93struct SuggestionFields {
94    source_path: Option<String>,
95    output_path: Option<String>,
96    preset: Option<String>,
97    width: Option<u32>,
98    format: Option<String>,
99}
100
101pub fn suggest(config: &Config, options: SuggestOptions) -> Result<SuggestionReport> {
102    if !options.metadata_only {
103        return Err(DevimgError::config(
104            &config.path,
105            "devimg suggest currently requires --metadata-only",
106        ));
107    }
108
109    let doctor_report = doctor(config, DoctorOptions::default())?;
110    let context = SuggestionContext::new(config);
111    let mut items = Vec::new();
112
113    for diagnostic in &doctor_report.issues {
114        items.push(suggestion_from_diagnostic(
115            config, &context, diagnostic, "error", false,
116        ));
117    }
118    for diagnostic in &doctor_report.warnings {
119        items.push(suggestion_from_diagnostic(
120            config,
121            &context,
122            diagnostic,
123            severity_for_warning(&diagnostic.code),
124            false,
125        ));
126    }
127    for diagnostic in &doctor_report.acknowledged_warnings {
128        items.push(suggestion_from_diagnostic(
129            config,
130            &context,
131            diagnostic,
132            severity_for_warning(&diagnostic.code),
133            true,
134        ));
135    }
136
137    items.sort_by(compare_suggestions);
138    items.dedup_by(|left, right| left.id == right.id);
139
140    let summary = SuggestionSummary {
141        suggestion_count: items.len(),
142        error_count: items.iter().filter(|item| item.severity == "error").count(),
143        warning_count: items
144            .iter()
145            .filter(|item| item.severity == "warning")
146            .count(),
147        advisory_count: items
148            .iter()
149            .filter(|item| item.severity == "advisory")
150            .count(),
151    };
152
153    Ok(SuggestionReport {
154        version: SUGGESTION_VERSION,
155        config_path: path_to_string(&config.path),
156        mode: "metadata-only".to_string(),
157        summary,
158        items,
159    })
160}
161
162pub fn suggestion_report_to_json(report: &SuggestionReport) -> String {
163    serde_json::to_string_pretty(report).expect("suggestion report serialization cannot fail")
164        + "\n"
165}
166
167pub fn render_suggestion_markdown(report: &SuggestionReport) -> String {
168    let mut out = String::new();
169    out.push_str("# DevImg Suggestions\n\n");
170    out.push_str("Deterministic suggestions generated from local DevImg diagnostics. No external AI provider was called.\n\n");
171    out.push_str("## Summary\n\n");
172    out.push_str(&format!("- Config: `{}`\n", report.config_path));
173    out.push_str(&format!("- Mode: `{}`\n", report.mode));
174    out.push_str(&format!(
175        "- Suggestions: `{}`\n",
176        report.summary.suggestion_count
177    ));
178    out.push_str(&format!("- Errors: `{}`\n", report.summary.error_count));
179    out.push_str(&format!("- Warnings: `{}`\n", report.summary.warning_count));
180    out.push_str(&format!(
181        "- Advisories: `{}`\n\n",
182        report.summary.advisory_count
183    ));
184
185    out.push_str("## Items\n\n");
186    if report.items.is_empty() {
187        out.push_str("No suggestions.\n");
188        return out;
189    }
190
191    for item in &report.items {
192        let location = item
193            .output_path
194            .as_ref()
195            .or(item.source_path.as_ref())
196            .map(String::as_str)
197            .unwrap_or(".");
198        out.push_str(&format!(
199            "- `{}` `{}` at `{}`: {}\n",
200            item.severity, item.warning_code, location, item.rationale
201        ));
202        if let Some(patch) = &item.suggested_config {
203            let changes = serde_json::to_string(&patch.changes)
204                .expect("suggested config changes serialization cannot fail");
205            out.push_str(&format!(
206                "  - Suggested config: target `{}` changes `{}`\n",
207                patch.target, changes
208            ));
209            out.push_str(&format!("  - Hint: {}\n", patch.toml_hint));
210        } else {
211            out.push_str("  - Suggested config: manual review or regeneration required.\n");
212        }
213        if !item.commands.is_empty() {
214            out.push_str("  - Commands:\n");
215            for command in &item.commands {
216                out.push_str(&format!("    - `{command}`\n"));
217            }
218        }
219    }
220
221    out
222}
223
224impl SuggestionContext {
225    fn new(config: &Config) -> Self {
226        let mut context = Self::default();
227
228        if let Ok(sources) = scan_sources(config) {
229            for source in &sources {
230                context.source_paths.insert(source.project_path.clone());
231            }
232            if let Ok(plan) = build_plan(config, &sources) {
233                for operation in &plan.operations {
234                    let metadata = SuggestionMetadata::from_operation(operation);
235                    context
236                        .operations_by_output
237                        .insert(metadata.output_path.clone(), metadata.clone());
238                    context
239                        .operations_by_source_preset_width
240                        .entry((
241                            metadata.source_path.clone(),
242                            metadata.preset.clone(),
243                            metadata.width,
244                        ))
245                        .or_default()
246                        .push(metadata);
247                }
248            }
249        }
250
251        if let Ok(manifest_path) =
252            resolve_project_path_checked(config, &config.project.manifest, "manifest path")
253        {
254            if let Ok(manifest) = read_manifest(&manifest_path) {
255                for output in &manifest.outputs {
256                    let metadata = SuggestionMetadata::from_output(output);
257                    context
258                        .outputs_by_output
259                        .insert(metadata.output_path.clone(), metadata);
260                }
261            }
262        }
263
264        context
265    }
266
267    fn enrich(&self, fields: &mut SuggestionFields) {
268        if let Some(output_path) = &fields.output_path {
269            if let Some(metadata) = self
270                .outputs_by_output
271                .get(output_path)
272                .or_else(|| self.operations_by_output.get(output_path))
273            {
274                fields.apply(metadata);
275            }
276        }
277
278        let Some(source_path) = &fields.source_path else {
279            return;
280        };
281        let Some(preset) = &fields.preset else {
282            return;
283        };
284        let Some(width) = fields.width else {
285            return;
286        };
287        if let Some(metadatas) = self.operations_by_source_preset_width.get(&(
288            source_path.clone(),
289            preset.clone(),
290            width,
291        )) {
292            if fields.format.is_none() {
293                let formats = metadatas
294                    .iter()
295                    .map(|metadata| metadata.format.as_str())
296                    .collect::<BTreeSet<_>>();
297                if formats.len() == 1 {
298                    fields.format = formats.iter().next().map(|format| (*format).to_string());
299                }
300            }
301            if fields.output_path.is_none() && metadatas.len() == 1 {
302                fields.output_path = Some(metadatas[0].output_path.clone());
303            }
304        }
305    }
306
307    fn is_source_path(&self, path: &str) -> bool {
308        self.source_paths.contains(path)
309    }
310}
311
312impl SuggestionMetadata {
313    fn from_operation(operation: &Operation) -> Self {
314        Self {
315            source_path: operation.source.project_path.clone(),
316            output_path: operation.output_project_path.clone(),
317            preset: operation.preset.clone(),
318            width: operation.width,
319            format: operation.format.label().to_string(),
320        }
321    }
322
323    fn from_output(output: &ManifestOutput) -> Self {
324        Self {
325            source_path: output.source_path.clone(),
326            output_path: output.output_path.clone(),
327            preset: output.preset.clone(),
328            width: output.width,
329            format: output.format.clone(),
330        }
331    }
332}
333
334impl SuggestionFields {
335    fn apply(&mut self, metadata: &SuggestionMetadata) {
336        self.source_path
337            .get_or_insert_with(|| metadata.source_path.clone());
338        self.output_path
339            .get_or_insert_with(|| metadata.output_path.clone());
340        self.preset.get_or_insert_with(|| metadata.preset.clone());
341        self.width.get_or_insert(metadata.width);
342        self.format.get_or_insert_with(|| metadata.format.clone());
343    }
344}
345
346fn suggestion_from_diagnostic(
347    config: &Config,
348    context: &SuggestionContext,
349    diagnostic: &DoctorDiagnostic,
350    severity: &str,
351    acknowledged: bool,
352) -> SuggestionItem {
353    let mut fields = fields_from_diagnostic(context, diagnostic);
354    context.enrich(&mut fields);
355    let message = split_code_and_message(&diagnostic.message).1;
356    if fields.format.is_none() {
357        fields.format = lossy_format_from_message(message);
358    }
359
360    let source_kind = source_kind(&diagnostic.code, &fields, diagnostic.path.as_str());
361    let suggested_config = suggested_config_patch(&diagnostic.code, &fields, message);
362    let commands = commands_for_diagnostic(config, diagnostic, &fields);
363    let id = suggestion_id(diagnostic, &fields, severity, acknowledged);
364
365    SuggestionItem {
366        id,
367        source_path: fields.source_path,
368        source_kind,
369        output_path: fields.output_path,
370        preset: fields.preset,
371        width: fields.width,
372        format: fields.format,
373        warning_code: diagnostic.code.clone(),
374        severity: severity.to_string(),
375        acknowledged,
376        rationale: diagnostic.message.clone(),
377        suggested_config,
378        commands,
379    }
380}
381
382fn fields_from_diagnostic(
383    context: &SuggestionContext,
384    diagnostic: &DoctorDiagnostic,
385) -> SuggestionFields {
386    let mut fields = SuggestionFields::default();
387    let info = warning_info(&diagnostic.message);
388    if info.code == diagnostic.code {
389        fields.source_path = info.source;
390        fields.output_path = info.output;
391        fields.preset = info.preset;
392        fields.width = info.width;
393    }
394
395    if fields.output_path.is_none()
396        && (context.outputs_by_output.contains_key(&diagnostic.path)
397            || context.operations_by_output.contains_key(&diagnostic.path)
398            || output_like_code(&diagnostic.code))
399    {
400        fields.output_path = Some(diagnostic.path.clone());
401    }
402
403    if fields.source_path.is_none() && context.is_source_path(&diagnostic.path) {
404        fields.source_path = Some(diagnostic.path.clone());
405    }
406
407    fields
408}
409
410fn severity_for_warning(code: &str) -> &'static str {
411    match code {
412        "missing_report" | "output_inside_source" | "source_inside_output" | BUDGET_FAILED => {
413            "warning"
414        }
415        code if code.starts_with("framework_") => "warning",
416        _ => "advisory",
417    }
418}
419
420fn source_kind(code: &str, fields: &SuggestionFields, diagnostic_path: &str) -> Option<String> {
421    if fields.output_path.is_some() {
422        return Some("generated".to_string());
423    }
424    if fields.source_path.is_some() {
425        return Some("source".to_string());
426    }
427    if code.contains("manifest") {
428        return Some("manifest".to_string());
429    }
430    if code.starts_with("framework_") {
431        return Some("framework".to_string());
432    }
433    if code.starts_with("oversized") || code == BUDGET_FAILED {
434        return Some("budget".to_string());
435    }
436    if code.contains("source") || diagnostic_path.contains("assets/") {
437        return Some("source".to_string());
438    }
439    if code == "missing_report" {
440        return Some("report".to_string());
441    }
442    Some("project".to_string())
443}
444
445fn suggested_config_patch(
446    code: &str,
447    fields: &SuggestionFields,
448    message: &str,
449) -> Option<SuggestedConfigPatch> {
450    let mut changes = BTreeMap::new();
451    let (target, hint) = match code {
452        QUALITY_LOW_LOSSY => {
453            if let Some(minimum) = suggested_min_quality_from_message(message) {
454                changes.insert("quality".to_string(), json!(minimum));
455            } else {
456                changes.insert("quality".to_string(), json!("raise"));
457            }
458            (
459                "preset",
460                "Raise the preset quality for detail-sensitive lossy output, or use png when crisp text or graphics matter.",
461            )
462        }
463        QUALITY_COVER_CROP => {
464            changes.insert("fit".to_string(), json!("contain"));
465            (
466                "preset",
467                "Consider fit = \"contain\" when the full composition must remain visible, or choose a crop anchor after visual review.",
468            )
469        }
470        QUALITY_SKIPPED_UPSCALE => {
471            changes.insert("widths".to_string(), json!("reduce to source dimensions"));
472            (
473                "preset",
474                "Prefer a larger source image or reduce configured widths. Set allow_upscale = true only after accepting softness.",
475            )
476        }
477        QUALITY_ALLOWED_UPSCALE | QUALITY_GENERATED_UPSCALE => {
478            changes.insert("widths".to_string(), json!("reduce"));
479            (
480                "preset",
481                "Prefer a larger source image or reduce configured widths so generated output is not upscaled.",
482            )
483        }
484        QUALITY_OUTPUT_LARGER_THAN_SOURCE => {
485            changes.insert("quality".to_string(), json!("review lower value"));
486            changes.insert("formats".to_string(), json!("review output formats"));
487            (
488                "preset",
489                "Review quality and output formats; small optimized sources or graphic assets can produce larger generated files.",
490            )
491        }
492        PLAN_NO_VARIANTS => {
493            changes.insert(
494                "widths".to_string(),
495                json!("add a generatable width or reduce configured widths"),
496            );
497            (
498                "preset",
499                "Adjust widths or provide a larger source so the source has at least one generated variant.",
500            )
501        }
502        "missing_source_dir" | "invalid_source_dir" | "empty_sources" => {
503            changes.insert(
504                "input".to_string(),
505                json!("point to a directory with source images"),
506            );
507            changes.insert("include".to_string(), json!("review include/exclude globs"));
508            (
509                "source",
510                "Update the affected [[sources]] entry or add source images before regenerating.",
511            )
512        }
513        "output_inside_source" | "source_inside_output" => {
514            changes.insert("input".to_string(), json!("separate from generated output"));
515            changes.insert("output".to_string(), json!("separate from source input"));
516            (
517                "source",
518                "Keep source and generated output trees separate, or ensure generated paths are excluded from source globs.",
519            )
520        }
521        "oversized_file" | "oversized_total" | BUDGET_FAILED => {
522            changes.insert("max_total_bytes".to_string(), json!("review"));
523            changes.insert("max_file_bytes".to_string(), json!("review"));
524            (
525                "budget",
526                "Reduce generated image bytes, tune presets, or update budgets only when the higher budget is intentional.",
527            )
528        }
529        code if code.starts_with("framework_") => {
530            changes.insert(
531                "manifest_export".to_string(),
532                json!("verify checked helper paths"),
533            );
534            (
535                "project",
536                "Regenerate or verify manifest helper files with the same export options used by the project.",
537            )
538        }
539        _ => return None,
540    };
541
542    Some(SuggestedConfigPatch {
543        target: target.to_string(),
544        source_path: fields.source_path.clone(),
545        preset: fields.preset.clone(),
546        changes,
547        toml_hint: hint.to_string(),
548    })
549}
550
551fn commands_for_diagnostic(
552    config: &Config,
553    diagnostic: &DoctorDiagnostic,
554    fields: &SuggestionFields,
555) -> Vec<String> {
556    let config_path = path_to_string(&config.path);
557    let mut commands = Vec::new();
558    match diagnostic.code.as_str() {
559        QUALITY_COVER_CROP
560        | QUALITY_ALLOWED_UPSCALE
561        | QUALITY_GENERATED_UPSCALE
562        | QUALITY_OUTPUT_LARGER_THAN_SOURCE => {
563            commands.push(review_command(config));
564            commands.push(optimize_command(&config_path));
565            commands.push(doctor_command(&config_path));
566        }
567        QUALITY_LOW_LOSSY | QUALITY_SKIPPED_UPSCALE | PLAN_NO_VARIANTS => {
568            commands.push(optimize_command(&config_path));
569            commands.push(doctor_command(&config_path));
570        }
571        "missing_manifest" | "missing" | "modified" | "stale" | "outdated_config" => {
572            commands.push(optimize_command(&config_path));
573            commands.push(doctor_command(&config_path));
574        }
575        "invalid_output" => {
576            if let Some(path) = fields.output_path.as_ref().or(fields.source_path.as_ref()) {
577                commands.push(format!("devimg inspect {}", shell_arg(path)));
578            }
579            commands.push(optimize_command(&config_path));
580            commands.push(doctor_command(&config_path));
581        }
582        "missing_report" => {
583            commands.push(check_command(&config_path));
584            commands.push(doctor_command(&config_path));
585        }
586        "manifest_export_missing" | "manifest_export_stale" | "manifest_export_unavailable" => {
587            commands
588                .push("devimg manifest export --manifest <manifest> --output <file>".to_string());
589            commands.push(doctor_command(&config_path));
590        }
591        _ => {
592            commands.push(doctor_command(&config_path));
593        }
594    }
595    dedup_commands(commands)
596}
597
598fn compare_suggestions(left: &SuggestionItem, right: &SuggestionItem) -> std::cmp::Ordering {
599    severity_rank(&left.severity)
600        .cmp(&severity_rank(&right.severity))
601        .then_with(|| left.warning_code.cmp(&right.warning_code))
602        .then_with(|| optional_cmp(&left.source_path, &right.source_path))
603        .then_with(|| optional_cmp(&left.output_path, &right.output_path))
604        .then_with(|| optional_cmp(&left.preset, &right.preset))
605        .then_with(|| {
606            left.width
607                .unwrap_or_default()
608                .cmp(&right.width.unwrap_or_default())
609        })
610        .then_with(|| optional_cmp(&left.format, &right.format))
611        .then_with(|| left.id.cmp(&right.id))
612}
613
614fn optional_cmp(left: &Option<String>, right: &Option<String>) -> std::cmp::Ordering {
615    left.as_deref()
616        .unwrap_or("")
617        .cmp(right.as_deref().unwrap_or(""))
618}
619
620fn severity_rank(severity: &str) -> u8 {
621    match severity {
622        "error" => 0,
623        "warning" => 1,
624        _ => 2,
625    }
626}
627
628fn suggestion_id(
629    diagnostic: &DoctorDiagnostic,
630    fields: &SuggestionFields,
631    severity: &str,
632    acknowledged: bool,
633) -> String {
634    [
635        severity.to_string(),
636        diagnostic.code.clone(),
637        fields.source_path.clone().unwrap_or_default(),
638        fields.output_path.clone().unwrap_or_default(),
639        fields.preset.clone().unwrap_or_default(),
640        fields
641            .width
642            .map(|width| width.to_string())
643            .unwrap_or_default(),
644        fields.format.clone().unwrap_or_default(),
645        acknowledged.to_string(),
646    ]
647    .join(":")
648}
649
650fn output_like_code(code: &str) -> bool {
651    matches!(
652        code,
653        "missing" | "modified" | "stale" | "invalid_output" | "oversized_file"
654    )
655}
656
657fn lossy_format_from_message(message: &str) -> Option<String> {
658    for format in ["avif", "jpeg", "webp"] {
659        if message.contains(&format!("uses {format} quality")) {
660            return Some(format.to_string());
661        }
662    }
663    None
664}
665
666fn suggested_min_quality_from_message(message: &str) -> Option<u8> {
667    let raw = message.split_once("suggested minimum ")?.1;
668    let digits = raw
669        .chars()
670        .take_while(|ch| ch.is_ascii_digit())
671        .collect::<String>();
672    digits.parse().ok()
673}
674
675fn optimize_command(config_path: &str) -> String {
676    format!(
677        "devimg optimize{} --allow-overwrite",
678        config_option(config_path)
679    )
680}
681
682fn doctor_command(config_path: &str) -> String {
683    format!("devimg doctor{}", config_option(config_path))
684}
685
686fn check_command(config_path: &str) -> String {
687    format!("devimg check{}", config_option(config_path))
688}
689
690fn review_command(config: &Config) -> String {
691    let manifest = resolve_project_path_checked(config, &config.project.manifest, "manifest path")
692        .map(|path| path_to_string(&project_relative(config, &path)))
693        .unwrap_or_else(|_| path_to_string(&config.project.manifest));
694    format!(
695        "devimg review --manifest {} --output .devimg/review.html",
696        shell_arg(&manifest)
697    )
698}
699
700fn config_option(config_path: &str) -> String {
701    if config_path == DEFAULT_CONFIG_PATH {
702        String::new()
703    } else {
704        format!(" --config {}", shell_arg(config_path))
705    }
706}
707
708fn shell_arg(value: &str) -> String {
709    if !value.is_empty()
710        && value
711            .chars()
712            .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '/' | '.' | '_' | '-' | ':' | '@'))
713    {
714        value.to_string()
715    } else {
716        format!("'{}'", value.replace('\'', "'\\''"))
717    }
718}
719
720fn dedup_commands(commands: Vec<String>) -> Vec<String> {
721    let mut seen = BTreeSet::new();
722    let mut deduped = Vec::new();
723    for command in commands {
724        if seen.insert(command.clone()) {
725            deduped.push(command);
726        }
727    }
728    deduped
729}
730
731#[cfg(test)]
732mod tests {
733    use super::suggested_min_quality_from_message;
734
735    #[test]
736    fn parses_suggested_quality_from_lossy_warning() {
737        assert_eq!(
738            suggested_min_quality_from_message(
739                "asset.png preset hero uses webp quality 74 below the suggested minimum 82 for screenshot assets"
740            ),
741            Some(82)
742        );
743    }
744}