homeboy 0.76.0

CLI for multi-component deployment and development workflow automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use crate::code_audit::conventions::{AuditFinding, Language};
use crate::core::refactor::plan::generate::extract_signatures_from_items;
use crate::core::refactor::shared::detect_language;
use crate::refactor::auto::apply::apply_insertions_to_content;
use crate::refactor::auto::policy::blocked_reason_from_preflight;
use crate::refactor::auto::{
    Fix, FixSafetyTier, Insertion, InsertionKind, NewFile, PreflightCheck, PreflightContext,
    PreflightReport, PreflightStatus,
};

pub fn run_insertion_preflight(
    file: &str,
    insertion: &Insertion,
    context: &PreflightContext<'_>,
) -> Option<PreflightReport> {
    match insertion.finding {
        AuditFinding::MissingMethod
        | AuditFinding::MissingRegistration
        | AuditFinding::MissingInterface
        | AuditFinding::NamespaceMismatch => {
            let abs_path = context.root.join(file);
            let content = std::fs::read_to_string(&abs_path).ok()?;
            let language = detect_language(&abs_path);
            let simulated =
                apply_insertions_to_content(&content, std::slice::from_ref(insertion), &language);

            let checks = vec![
                collision_check(&content, insertion),
                syntax_shape_check(&simulated, insertion, &language),
            ];
            Some(finalize_report(checks))
        }
        AuditFinding::UnreferencedExport => {
            let abs_path = context.root.join(file);
            let content = std::fs::read_to_string(&abs_path).ok()?;
            let language = detect_language(&abs_path);
            let simulated =
                apply_insertions_to_content(&content, std::slice::from_ref(insertion), &language);

            let changed = simulated != content;
            let checks = vec![PreflightCheck {
                name: "visibility_changed".to_string(),
                passed: changed,
                detail: if changed {
                    "visibility qualifier was narrowed successfully".to_string()
                } else {
                    "visibility qualifier was not found or already narrowed".to_string()
                },
            }];
            Some(finalize_report(checks))
        }
        AuditFinding::DuplicateFunction => {
            let abs_path = context.root.join(file);
            let content = std::fs::read_to_string(&abs_path).ok()?;
            let language = detect_language(&abs_path);

            let mut checks = Vec::new();

            if matches!(insertion.kind, InsertionKind::TraitUse) {
                let has_class = content.contains("class ");
                checks.push(PreflightCheck {
                    name: "class_exists".to_string(),
                    passed: has_class,
                    detail: if has_class {
                        "target file contains a class definition".to_string()
                    } else {
                        "target file does not contain a class definition".to_string()
                    },
                });

                let trait_code = insertion.code.trim();
                let already_present = content.lines().any(|line| line.trim() == trait_code);
                checks.push(PreflightCheck {
                    name: "trait_use_absent".to_string(),
                    passed: !already_present,
                    detail: if already_present {
                        format!("trait use `{}` already exists in file", trait_code)
                    } else {
                        format!("trait use `{}` is not yet present", trait_code)
                    },
                });

                let simulated = apply_insertions_to_content(
                    &content,
                    std::slice::from_ref(insertion),
                    &language,
                );
                checks.push(syntax_shape_check(&simulated, insertion, &language));

                return Some(finalize_report(checks));
            }

            if let InsertionKind::FunctionRemoval {
                start_line,
                end_line,
            } = &insertion.kind
            {
                let line_count = content.lines().count();
                let range_valid = *start_line >= 1 && *end_line <= line_count;
                checks.push(PreflightCheck {
                    name: "function_boundaries".to_string(),
                    passed: range_valid,
                    detail: if range_valid {
                        format!(
                            "Function found at lines {}–{} (file has {} lines)",
                            start_line, end_line, line_count
                        )
                    } else {
                        format!(
                            "Line range {}–{} is out of bounds (file has {} lines)",
                            start_line, end_line, line_count
                        )
                    },
                });

                if range_valid {
                    let simulated = apply_insertions_to_content(
                        &content,
                        std::slice::from_ref(insertion),
                        &language,
                    );
                    let still_valid = simulated != content;
                    checks.push(PreflightCheck {
                        name: "removal_applied".to_string(),
                        passed: still_valid,
                        detail: if still_valid {
                            "Function removal modifies the file as expected".to_string()
                        } else {
                            "Removal produced no change — function may have already been removed"
                                .to_string()
                        },
                    });
                }
            }

            if checks.is_empty() {
                None
            } else {
                Some(finalize_report(checks))
            }
        }
        AuditFinding::OrphanedTest => {
            let abs_path = context.root.join(file);
            let content = std::fs::read_to_string(&abs_path).ok()?;
            let language = detect_language(&abs_path);

            if let InsertionKind::FunctionRemoval {
                start_line,
                end_line,
            } = &insertion.kind
            {
                let line_count = content.lines().count();
                let range_valid = *start_line >= 1 && *end_line <= line_count;
                let mut checks = vec![PreflightCheck {
                    name: "function_boundaries".to_string(),
                    passed: range_valid,
                    detail: if range_valid {
                        format!(
                            "Orphaned test found at lines {}–{} (file has {} lines)",
                            start_line, end_line, line_count
                        )
                    } else {
                        format!(
                            "Line range {}–{} is out of bounds (file has {} lines)",
                            start_line, end_line, line_count
                        )
                    },
                }];

                if range_valid {
                    let simulated = apply_insertions_to_content(
                        &content,
                        std::slice::from_ref(insertion),
                        &language,
                    );
                    let still_valid = simulated != content;
                    checks.push(PreflightCheck {
                        name: "removal_applied".to_string(),
                        passed: still_valid,
                        detail: if still_valid {
                            "Orphaned test removal modifies the file as expected".to_string()
                        } else {
                            "Removal produced no change — test may have already been removed"
                                .to_string()
                        },
                    });
                }

                Some(finalize_report(checks))
            } else {
                None
            }
        }
        _ => None,
    }
}

pub fn run_fix_preflight(fix: &mut Fix, context: &PreflightContext<'_>, write: bool) {
    if fix.insertions.is_empty() {
        return;
    }

    let abs_path = context.root.join(&fix.file);
    let Ok(content) = std::fs::read_to_string(&abs_path) else {
        return;
    };
    let language = detect_language(&abs_path);
    let simulated = apply_insertions_to_content(&content, &fix.insertions, &language);

    let mut extra_checks = Vec::new();
    if !fix.required_methods.is_empty() {
        extra_checks.push(required_methods_check(
            &simulated,
            &language,
            &fix.required_methods,
        ));
    }
    if !fix.required_registrations.is_empty() {
        extra_checks.push(required_registrations_check(
            &simulated,
            &fix.required_registrations,
        ));
    }

    for insertion in &mut fix.insertions {
        if insertion.safety_tier != FixSafetyTier::SafeWithChecks {
            continue;
        }

        if let Some(report) = &mut insertion.preflight {
            report.checks.extend(extra_checks.clone());
            *report = finalize_report(report.checks.clone());
        }

        insertion.auto_apply = if !write {
            true
        } else {
            insertion.preflight.as_ref().is_some_and(|report| {
                matches!(
                    report.status,
                    PreflightStatus::Passed | PreflightStatus::NotApplicable
                )
            })
        };

        insertion.blocked_reason = if insertion.auto_apply {
            None
        } else {
            Some(
                insertion
                    .preflight
                    .as_ref()
                    .and_then(blocked_reason_from_preflight)
                    .unwrap_or_else(|| {
                        "Blocked: requires preflight validation before auto-write".to_string()
                    }),
            )
        };
    }
}

pub fn run_new_file_preflight(
    new_file: &NewFile,
    context: &PreflightContext<'_>,
) -> Option<PreflightReport> {
    match new_file.finding {
        AuditFinding::DuplicateFunction => {
            let abs = context.root.join(&new_file.file);
            let parent_exists = abs
                .parent()
                .map(|p| p.exists() || p == context.root)
                .unwrap_or(false);

            Some(finalize_report(vec![
                PreflightCheck {
                    name: "file_absent".to_string(),
                    passed: !abs.exists(),
                    detail: if abs.exists() {
                        format!("{} already exists — will not overwrite", new_file.file)
                    } else {
                        format!("{} does not already exist", new_file.file)
                    },
                },
                PreflightCheck {
                    name: "content_nonempty".to_string(),
                    passed: !new_file.content.trim().is_empty(),
                    detail: if new_file.content.trim().is_empty() {
                        "generated trait content is empty".to_string()
                    } else {
                        "generated trait content is non-empty".to_string()
                    },
                },
                PreflightCheck {
                    name: "parent_exists".to_string(),
                    passed: parent_exists,
                    detail: if parent_exists {
                        "parent directory exists or is project root".to_string()
                    } else {
                        format!(
                            "parent directory {} does not exist",
                            abs.parent()
                                .map(|p| p.display().to_string())
                                .unwrap_or_default()
                        )
                    },
                },
            ]))
        }
        _ => None,
    }
}

fn finalize_report(checks: Vec<PreflightCheck>) -> PreflightReport {
    let status = if checks.iter().all(|check| check.passed) {
        PreflightStatus::Passed
    } else {
        PreflightStatus::Failed
    };

    PreflightReport { status, checks }
}

fn collision_check(content: &str, insertion: &Insertion) -> PreflightCheck {
    let collision_free = !content.contains(&insertion.code);
    PreflightCheck {
        name: "collision".to_string(),
        passed: collision_free,
        detail: if collision_free {
            "target file does not already contain this generated code".to_string()
        } else {
            "target file already contains identical generated code".to_string()
        },
    }
}

fn syntax_shape_check(content: &str, insertion: &Insertion, language: &Language) -> PreflightCheck {
    let detail_prefix = match insertion.finding {
        AuditFinding::MissingMethod => "generated method stub",
        AuditFinding::MissingRegistration => "generated registration/constructor",
        AuditFinding::MissingInterface => "generated type conformance",
        AuditFinding::NamespaceMismatch => "generated namespace declaration",
        _ => "generated content",
    };

    let parsed_ok = match language {
        Language::Php => {
            !extract_signatures_from_items(content, language).is_empty()
                || content.contains("class ")
        }
        Language::Rust => {
            !extract_signatures_from_items(content, language).is_empty() || content.contains("fn ")
        }
        Language::JavaScript | Language::TypeScript => {
            !extract_signatures_from_items(content, language).is_empty()
                || content.contains("function ")
        }
        Language::Unknown => true,
    };

    PreflightCheck {
        name: "syntax_shape".to_string(),
        passed: parsed_ok,
        detail: if parsed_ok {
            format!(
                "{} preserves parseable structural signatures",
                detail_prefix
            )
        } else {
            format!(
                "{} produced content that no longer matches expected signature shapes",
                detail_prefix
            )
        },
    }
}

fn required_methods_check(
    content: &str,
    language: &Language,
    required_methods: &[String],
) -> PreflightCheck {
    let missing: Vec<String> = required_methods
        .iter()
        .filter(|method| !method_present(content, language, method))
        .cloned()
        .collect();

    PreflightCheck {
        name: "required_methods".to_string(),
        passed: missing.is_empty(),
        detail: if missing.is_empty() {
            format!(
                "required methods preserved: {}",
                required_methods.join(", ")
            )
        } else {
            format!(
                "missing required methods after simulation: {}",
                missing.join(", ")
            )
        },
    }
}

fn method_present(content: &str, language: &Language, method: &str) -> bool {
    let escaped = regex::escape(method);
    let pattern = match language {
        Language::Php => format!(r"\bfunction\s+{}\b", escaped),
        Language::Rust => format!(r"\bfn\s+{}\b", escaped),
        Language::JavaScript | Language::TypeScript => {
            format!(r"\b(function\s+{}\b|{}\s*\()", escaped, escaped)
        }
        Language::Unknown => return content.contains(method),
    };

    regex::Regex::new(&pattern)
        .map(|re| re.is_match(content))
        .unwrap_or_else(|_| content.contains(method))
}

fn required_registrations_check(
    content: &str,
    required_registrations: &[String],
) -> PreflightCheck {
    let missing: Vec<String> = required_registrations
        .iter()
        .filter(|registration| !content.contains(registration.as_str()))
        .cloned()
        .collect();

    PreflightCheck {
        name: "required_registrations".to_string(),
        passed: missing.is_empty(),
        detail: if missing.is_empty() {
            format!(
                "required registrations preserved: {}",
                required_registrations.join(", ")
            )
        } else {
            format!(
                "missing required registrations after simulation: {}",
                missing.join(", ")
            )
        },
    }
}