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