use std::sync::OnceLock;
use crate::self_healing::{canonical_case, RepairCase};
pub const SELF_HEAL_PATH: &str = "self-healing-case.lino";
fn cached_case() -> &'static RepairCase {
static CASE: OnceLock<RepairCase> = OnceLock::new();
CASE.get_or_init(canonical_case)
}
pub const SELF_HEAL_TASK: &str =
"When you cannot answer an input, run your self-healing loop: reason about the \
failure, map it onto the source that would change with a source-to-links \
round-trip, learn a benchmark-gated lesson, and record the repair case in \
Links Notation for human approval.";
const SELF_HEAL_KEYWORDS: [&str; 6] = [
"self-healing",
"self-heal",
"auto-learning",
"auto learning",
"repair case",
"repair loop",
];
const SELF_REPAIR_PHRASES: [&str; 16] = [
"fix it yourself",
"fix yourself",
"fix your self",
"fix your own",
"fix them yourself",
"fix this yourself",
"solve it yourself",
"solve this yourself",
"debug yourself",
"debug it yourself",
"heal yourself",
"repair yourself",
"correct yourself",
"fix on your own",
"fix it on your own",
"learn from your mistake",
];
#[must_use]
pub fn is_self_heal_task(prompt: &str) -> bool {
let lower = prompt.to_lowercase();
SELF_HEAL_KEYWORDS
.iter()
.any(|keyword| lower.contains(keyword))
|| SELF_REPAIR_PHRASES
.iter()
.any(|phrase| lower.contains(phrase))
|| ((lower.contains("cannot answer")
|| lower.contains("can't answer")
|| lower.contains("failure"))
&& (lower.contains("heal") || lower.contains("learn a")))
}
#[must_use]
pub fn render_document() -> String {
format!("{}\n", cached_case().links_notation().trim_end())
}
#[must_use]
pub fn case() -> RepairCase {
cached_case().clone()
}
#[must_use]
pub fn final_answer(document: &str) -> String {
let case = cached_case();
format!(
"Ran the self-healing loop on an input the system could not answer directly: reasoned about \
the failure trace, mapped it onto {module} with a verified source-to-links round-trip, \
learned a benchmark-gated lesson, and recorded an auditable repair case ({outcome}). \
Nothing was applied — adoption stays a human-approved review step.\n\n\
Generated document ({SELF_HEAL_PATH}):\n\n{document}",
module = case.source_round_trip.module_path,
outcome = case.outcome.slug(),
document = document.trim_end(),
)
}