formal-ai 0.75.0

Formal symbolic AI implementation with OpenAI-compatible APIs
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
//! Specialized handlers extracted from the universal solver in `solver.rs` to
//! keep that module under the 1000-line cap enforced by
//! `scripts/check-file-size.rs`. These handlers are free functions: every one
//! takes the prompt (and pre-lowercased `normalized` view) plus a mutable
//! event log, and returns `Some(SymbolicAnswer)` when it claims the impulse.

mod benchmark_prompts;
mod definition_merge;
mod software_project;
mod software_project_code;
mod user_intent;
mod web_requests;

pub use benchmark_prompts::{
    try_brainstorming_request, try_coreference_request, try_fact_lookup, try_roleplay_request,
    try_summarization_request,
};
pub use definition_merge::{try_definition_merge, try_definition_merge_by_default};
pub use software_project::try_software_project_request;
pub use user_intent::{
    try_capabilities, try_clarification, try_ill_formed, try_opinion_question,
    try_punctuation_only_prompt, try_shell_refusal, try_who_is_question,
};
pub use web_requests::{try_http_fetch, try_url_navigate, try_web_search};

use std::fmt::Write as _;

use crate::calculation::{calculation_expression_candidates, evaluate_calculation};
use crate::concepts::{
    extract_concept_query, lookup_concept_query, resolve_context_label, ConceptRecord,
};
use crate::engine::{
    answer_links_notation, hello_world_program_by_alias, knowledge_links_notation, stable_id,
    ExecutionStatus, SymbolicAnswer,
};
use crate::event_log::{build_evidence_links, EventLog};
use crate::language::detect as detect_language;
use crate::seed::response_for;
use crate::solver_helpers::{
    build_sorting_algorithm_answer, detect_algorithm_language, detect_program_languages,
    detect_source_language, detect_target_language, extract_backticked, extract_concept_from_query,
    extract_introduced_name, extract_javascript_program, extract_quoted_phrase,
    format_write_script_execution, humanize_url, infer_program_languages_from_code,
    infer_source_from_prompt, is_write_script_request, last_user_turn, normalize_code_meaning,
    normalize_meaning, recall_name_from_history, translate_program, translate_surface,
};

pub fn try_conversation_memory(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    if let Some(answer) = try_recall_name(prompt, normalized, log) {
        return Some(answer);
    }
    if let Some(answer) = try_recall_last_question(prompt, normalized, log) {
        return Some(answer);
    }
    if let Some(answer) = try_summarize_conversation(prompt, normalized, log) {
        return Some(answer);
    }
    None
}

fn try_recall_name(prompt: &str, normalized: &str, log: &mut EventLog) -> Option<SymbolicAnswer> {
    let asks_name = normalized.contains("what is my name")
        || normalized.contains("what's my name")
        || normalized.contains("do you know my name")
        || normalized.contains("who am i");
    if !asks_name {
        return None;
    }
    let name = recall_name_from_history(log, prompt).or_else(|| extract_introduced_name(prompt))?;
    log.append("filter:user", format!("name={name}"));
    let body = format!("Your name is {name}.");
    Some(finalize_simple(
        prompt,
        log,
        "recall_name",
        "response:recall_name",
        &body,
        0.9,
    ))
}

fn try_recall_last_question(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    let asks = normalized.contains("what did i ask")
        || normalized.contains("what was my last question")
        || normalized.contains("what was my previous question")
        || normalized.contains("repeat my last message");
    if !asks {
        return None;
    }
    let previous = last_user_turn(log)?;
    let body = format!("Your previous message was: \"{previous}\"");
    log.append("filter:user", "previous_turn".to_owned());
    Some(finalize_simple(
        prompt,
        log,
        "recall_last_question",
        "response:recall_last_question",
        &body,
        0.9,
    ))
}

fn try_summarize_conversation(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    let asks = normalized.contains("summarize the conversation")
        || normalized.contains("summarize our conversation")
        || normalized.contains("summarize this conversation")
        || normalized.contains("summary of our chat")
        || normalized.contains("what have we talked about")
        || normalized == "summarize"
        // Russian
        || normalized.contains("о чём мы разговаривали")
        || normalized.contains("о чем мы разговаривали")
        || normalized.contains("о чём мы говорили")
        || normalized.contains("о чем мы говорили")
        || normalized.contains("резюме беседы")
        || normalized.contains("резюме разговора")
        || normalized.contains("резюмируй разговор")
        || normalized.contains("резюмируй беседу")
        || normalized == "резюме"
        // Chinese
        || normalized.contains("总结");
    if !asks {
        return None;
    }
    let user_turns: Vec<&str> = log
        .events()
        .iter()
        .filter(|event| event.kind == "prior_turn:user")
        .map(|event| event.payload.as_str())
        .collect();
    if user_turns.is_empty() {
        return None;
    }
    let mut body = String::from("Conversation summary (user turns recorded so far):\n");
    for (index, turn) in user_turns.iter().enumerate() {
        writeln!(body, "  {}. {turn}", index + 1).expect("string write is infallible");
    }
    log.append("filter:user", "conversation_summary".to_owned());
    Some(finalize_simple(
        prompt,
        log,
        "summarize_conversation",
        "response:summarize_conversation",
        body.trim_end(),
        0.9,
    ))
}

pub fn try_arithmetic(prompt: &str, log: &mut EventLog) -> Option<SymbolicAnswer> {
    let candidates = calculation_expression_candidates(prompt);
    let mut first_explicit_error: Option<(String, String)> = None;
    for candidate in candidates {
        let expression = candidate.expression;
        log.append("calculation:request", expression.clone());
        match evaluate_calculation(&expression) {
            Ok(evaluation) => {
                let formatted = evaluation.formatted;
                log.append("calculation:engine", evaluation.engine.slug());
                if let Some(lino) = evaluation.lino {
                    log.append("calculation:lino", lino);
                }
                if !evaluation.steps.is_empty() {
                    log.append("calculation:steps", evaluation.steps.len().to_string());
                }
                let body = if expression.contains('=') && formatted.contains(" = ") {
                    format!("{expression} => {formatted}")
                } else {
                    format!("{expression} = {formatted}")
                };
                log.append("calculation", body.clone());
                return Some(finalize_simple(
                    prompt,
                    log,
                    "calculation",
                    "response:calculation",
                    &body,
                    1.0,
                ));
            }
            Err(error) => {
                let error = error.to_string();
                log.append("calculation:error", error.clone());
                if candidate.explicit && first_explicit_error.is_none() {
                    first_explicit_error = Some((expression, error));
                }
            }
        }
    }
    let (expression, error) = first_explicit_error?;
    let body = format!(
        "I parsed '{expression}' as an arithmetic request but could not evaluate it: {error}."
    );
    Some(finalize_simple(
        prompt,
        log,
        "calculation_error",
        "response:calculation_error",
        &body,
        0.3,
    ))
}

pub fn try_concept_lookup(prompt: &str, log: &mut EventLog) -> Option<SymbolicAnswer> {
    let query = extract_concept_query(prompt)?;
    log.append("concept_lookup:request", query.term.clone());
    if let Some(context) = query.context.as_deref() {
        log.append("concept_lookup:context", context.to_owned());
    }
    let Some(lookup) = lookup_concept_query(&query) else {
        log.append("concept_lookup:miss", query.term);
        return None;
    };
    let record: &'static ConceptRecord = lookup.record;
    log.append("concept_lookup:hit", record.slug.clone());
    let language = detect_language(prompt).slug();
    let localized = record.localized_for(language);
    let source_for_log = localized
        .map(|loc| loc.source.as_str())
        .filter(|s| !s.is_empty())
        .unwrap_or(record.source.as_str());
    // Issue #21: log the percent-decoded IRI form so diagnostic chips stay
    // readable. Rendering uses humanize_url too (see render_concept_*).
    log.append("source", humanize_url(source_for_log));
    if !record.wikidata.is_empty() {
        log.append("wikidata", record.wikidata.clone());
    }
    if lookup.context_match {
        if let Some(context) = lookup.context.as_deref() {
            log.append("concept_lookup:context-match", context.to_owned());
            let body = render_concept_in_context(language, context, record);
            return Some(finalize_simple(
                prompt,
                log,
                "concept_lookup_in_context",
                "response:concept_lookup_in_context",
                &body,
                0.9,
            ));
        }
    } else if let Some(context) = lookup.context.as_deref() {
        log.append("concept_lookup:context-mismatch", context.to_owned());
    }
    let body = render_concept_plain(language, record);
    Some(finalize_simple(
        prompt,
        log,
        "concept_lookup",
        "response:concept_lookup",
        &body,
        0.9,
    ))
}

/// Render a plain `concept_lookup` body using the localized variant when
/// available (so `что такое IIR` in Russian returns the ru.wikipedia.org
/// summary, not the English one).
fn render_concept_plain(language: &str, record: &ConceptRecord) -> String {
    let localized = record.localized_for(language);
    let term = localized
        .map(|loc| loc.term.as_str())
        .filter(|s| !s.is_empty())
        .unwrap_or(record.term.as_str());
    let summary = localized
        .map(|loc| loc.summary.as_str())
        .filter(|s| !s.is_empty())
        .unwrap_or(record.summary.as_str());
    let source = localized
        .map(|loc| loc.source.as_str())
        .filter(|s| !s.is_empty())
        .unwrap_or(record.source.as_str());
    let source_kind = localized
        .map(|loc| loc.source_kind.as_str())
        .filter(|s| !s.is_empty())
        .unwrap_or(record.source_kind.as_str());
    let source_markup = render_source_link(source);
    format!(
        "{term} ({category}): {summary}\n\nSource: {source_markup} ({source_kind}).",
        category = record.category,
    )
}

/// Issue #21: render a URL as a readable IRI while keeping the canonical
/// percent-encoded form as the link target. Returns the bare URL when the
/// humanized and encoded forms match (no link wrapping needed).
fn render_source_link(source: &str) -> String {
    let human = humanize_url(source);
    if human == source {
        source.to_owned()
    } else {
        format!("[{human}]({source})")
    }
}

/// Render a `concept_lookup_in_context` body, preferring the language-specific
/// template loaded from `data/seed/multilingual-responses.lino`. Falls back
/// to the English template (and, if that is missing, a hardcoded one) so the
/// solver still works when seed loading fails.
///
/// Maintainer requirement R8 (issue #20): use the full disambiguated context
/// name, e.g. `В контексте «ml» (Машинное обучение)`. The raw user-typed
/// context is shown verbatim and the resolved registry label is appended in
/// parentheses; when the two collide (user already typed the localized
/// label) the `no_alias` template is used to avoid `«ml» (ml)`.
///
/// Maintainer requirement R9: the term and summary use the localized variant
/// (e.g. `Фильтр с бесконечной импульсной характеристикой… или IIR-фильтр`)
/// when the user's prevailing language has a `localized` block.
#[allow(clippy::literal_string_with_formatting_args)]
fn render_concept_in_context(language: &str, context: &str, record: &ConceptRecord) -> String {
    let context_record = resolve_context_label(context);
    let context_label =
        context_record.map_or_else(|| context.to_owned(), |c| c.label_for(language).to_owned());
    let use_no_alias = context_label.trim().to_lowercase() == context.trim().to_lowercase();
    let intent_variant = if use_no_alias {
        "concept_lookup_in_context_no_alias"
    } else {
        "concept_lookup_in_context"
    };
    let template = response_for(intent_variant, language)
        .or_else(|| response_for(intent_variant, "en"))
        .or_else(|| response_for("concept_lookup_in_context", language))
        .or_else(|| response_for("concept_lookup_in_context", "en"))
        .unwrap_or_else(|| {
            String::from(
                "In the context of {context} ({context_label}), {term} ({category}) means: \
                 {summary}\n\nSource: {source} ({source_kind}).",
            )
        });
    let localized = record.localized_for(language);
    let term = localized
        .map(|loc| loc.term.as_str())
        .filter(|s| !s.is_empty())
        .unwrap_or(record.term.as_str());
    let summary = localized
        .map(|loc| loc.summary.as_str())
        .filter(|s| !s.is_empty())
        .unwrap_or(record.summary.as_str());
    let source = localized
        .map(|loc| loc.source.as_str())
        .filter(|s| !s.is_empty())
        .unwrap_or(record.source.as_str());
    let source_kind = localized
        .map(|loc| loc.source_kind.as_str())
        .filter(|s| !s.is_empty())
        .unwrap_or(record.source_kind.as_str());
    let source_markup = render_source_link(source);
    template
        .replace("{context_label}", &context_label)
        .replace("{context}", context)
        .replace("{term}", term)
        .replace("{category}", &record.category)
        .replace("{summary}", summary)
        .replace("{source}", &source_markup)
        .replace("{source_kind}", source_kind)
}

pub fn try_javascript_execution(prompt: &str, log: &mut EventLog) -> Option<SymbolicAnswer> {
    let program = extract_javascript_program(prompt)?;
    log.append("execution:request", "javascript".to_owned());
    log.append("execution:source", program.clone());
    log.append("execution_status", "javascript:unavailable".to_owned());
    log.append("execution_environment", "no-js-runtime".to_owned());
    let body = format!(
        "I do not embed a JavaScript runtime in this build, so I cannot \
         execute the program for you. The deterministic solver only runs \
         code that has been verified offline; running arbitrary JavaScript \
         would violate that contract. Here is the program you asked me to \
         run, copy-paste reviewable:\n\n```js\n{program}\n```\n\n\
         To execute it yourself, save the snippet as `program.js` and run \
         `node program.js` (or `deno run program.js`)."
    );
    Some(finalize_simple(
        prompt,
        log,
        "javascript_execution_unavailable",
        "response:javascript_execution_unavailable",
        &body,
        0.6,
    ))
}

pub fn try_meta_explanation(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    let is_why_question = normalized.starts_with("why ")
        || normalized.starts_with("why did")
        || normalized.starts_with("why do you")
        || normalized.contains("why did you answer");
    let is_how_you_work = normalized.contains("how do you work")
        || normalized.contains("how does this work")
        || normalized.contains("how does it work")
        || normalized.contains("show me how you work")
        || normalized.contains("explain how you work")
        // Russian
        || normalized.contains("как ты работаешь")
        || normalized.contains("покажи как ты работаешь")
        || normalized.contains("расскажи как ты работаешь")
        || normalized.contains("объясни как ты работаешь")
        || normalized.contains("как ты устроен")
        || normalized.contains("покажи как ты устроен")
        // Hindi
        || normalized.contains("तुम कैसे काम करते हो")
        || normalized.contains("आप कैसे काम करते हैं")
        // Chinese
        || normalized.contains("你是怎么工作的")
        || normalized.contains("你怎么运作");
    if !is_why_question && !is_how_you_work {
        return None;
    }
    let language = detect_language(prompt).slug();
    let body = if is_why_question {
        response_for("meta_explanation", language)
            .or_else(|| response_for("meta_explanation", "en"))
            .unwrap_or_else(|| String::from(
                "I answered that way because the prompt matched a deterministic Links Notation rule. \
                 The evidence and trace events are appended to the log; see the trace link for the \
                 full chain.",
            ))
    } else {
        response_for("meta_explanation", language)
            .or_else(|| response_for("meta_explanation", "en"))
            .unwrap_or_else(|| {
                String::from(
                "I work by matching your prompt against deterministic Links Notation rules stored \
                 in memory. Each rule maps a recognized pattern to a fixed response. When no rule \
                 matches, I report intent: unknown. There is no neural inference — every answer is \
                 fully traceable to a symbolic rule.",
            )
            })
    };
    Some(finalize_simple(
        prompt,
        log,
        "meta_explanation",
        "response:meta_explanation",
        &body,
        1.0,
    ))
}

pub fn try_network_query(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    if normalized.contains("show me the current network")
        || normalized.contains("show me the network")
        || normalized.contains("export the network")
        || normalized.contains("export network")
    {
        let snapshot = knowledge_links_notation();
        let body = format!(
            "Here is the current link network as a links-notation snapshot:\n\n```links\n{snapshot}\n```"
        );
        return Some(finalize_simple(
            prompt,
            log,
            "network_snapshot",
            "response:network_snapshot",
            &body,
            1.0,
        ));
    }
    if let Some(concept) = extract_concept_from_query(prompt) {
        let body = format!(
            "Here is what I know about '{concept}':\n\nintent: {concept}\nrole: \
             the network records '{concept}' as a concept with rules and example links."
        );
        return Some(finalize_simple(
            prompt,
            log,
            &format!("concept_introspection_{concept}"),
            "response:concept_introspection",
            &body,
            1.0,
        ));
    }
    if normalized.contains("list the facts i have contributed")
        || normalized.contains("list my facts")
        || normalized.starts_with("list facts")
    {
        log.append("filter:user", "self".to_owned());
        let body = String::from(
            "No facts have been recorded under your user filter yet. Submit a 'teach this fact' \
             request to start your personal contribution list.",
        );
        return Some(finalize_simple(
            prompt,
            log,
            "filter_user",
            "response:filter_user",
            &body,
            1.0,
        ));
    }
    None
}

pub fn try_translation(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    let is_translation_request = normalized.starts_with("translate")
        || normalized.starts_with("переведи")
        || normalized.starts_with("опиши")
        || (normalized.starts_with("define ")
            && (extract_quoted_phrase(prompt).is_some() || extract_backticked(prompt).is_some())
            && (normalized.contains(" links notation") || normalized.contains(" в links")));
    if !is_translation_request {
        return None;
    }

    let target = detect_target_language(normalized);
    let mut source = detect_source_language(normalized);
    if source.is_none() {
        source = Some(infer_source_from_prompt(prompt));
    }

    let backticked = extract_backticked(prompt);

    if let Some(code) = &backticked {
        let detected = detect_program_languages(normalized)
            .or_else(|| infer_program_languages_from_code(code, normalized));
        if let Some((source_lang, target_lang)) = detected {
            let translated = translate_program(code, source_lang, target_lang);
            let body = format!(
                "Translated `{code}` from {source_lang} to {target_lang}:\n\n```{target_lang}\n{translated}\n```"
            );
            log.append("language_from", source_lang.to_owned());
            log.append("language_to", target_lang.to_owned());
            let meaning_id = stable_id("meaning", &normalize_code_meaning(code));
            log.append("meaning", meaning_id);
            let intent = format!("translate_{source_lang}_to_{target_lang}");
            return Some(finalize_simple(
                prompt,
                log,
                &intent,
                "response:translate_code",
                &body,
                1.0,
            ));
        }
    }

    if normalized.contains("'тоска'") || normalized.contains("\"тоска\"") {
        log.append("translation_gap", "тоска".to_owned());
        log.append("language_from", "ru".to_owned());
        log.append("language_to", "en".to_owned());
        let body = String::from(
            "The Russian word 'тоска' has no single-word English equivalent. The closest \
             surface forms are 'melancholy', 'yearning' or 'spiritual anguish'. The \
             translation gap is recorded explicitly in the link network.",
        );
        return Some(finalize_simple(
            prompt,
            log,
            "translate_ru_to_en",
            "response:translate",
            &body,
            0.6,
        ));
    }

    let surface = extract_quoted_phrase(prompt).unwrap_or_default();
    let surface_meaning = if surface.is_empty() {
        prompt.to_owned()
    } else {
        surface.clone()
    };
    let meaning_id = stable_id("meaning", &normalize_meaning(&surface_meaning));
    let source_slug = source.unwrap_or("en");
    let target_slug = target.unwrap_or("en");

    log.append("language_from", source_slug.to_owned());
    log.append("language_to", target_slug.to_owned());
    log.append("meaning", meaning_id.clone());

    let translated_surface = translate_surface(&surface, source_slug, target_slug);
    let body = format!(
        "meaning: {meaning_id}\nsurface ({source_slug}): {surface}\nsurface ({target_slug}): {translated_surface}"
    );
    let intent = format!("translate_{source_slug}_to_{target_slug}");
    Some(finalize_simple(
        prompt,
        log,
        &intent,
        "response:translate",
        &body,
        1.0,
    ))
}

pub fn try_write_script(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    if !is_write_script_request(normalized) {
        return None;
    }
    let program = hello_world_program_by_alias(normalized)?;
    let body = format!(
        "Here is a minimal {} script:\n\n```{}\n{}\n```\n\n{}",
        program.language,
        program.code_fence,
        program.code,
        format_write_script_execution(program)
    );
    let intent = format!("write_script_{}", program.slug);
    log.append(
        "execution_status",
        program.execution.status.label().to_owned(),
    );
    log.append(
        "execution_environment",
        program.execution.environment.to_owned(),
    );
    Some(finalize_simple(
        prompt,
        log,
        &intent,
        &format!("response:hello_world:{}", program.slug),
        &body,
        1.0,
    ))
}

pub fn try_algorithm(prompt: &str, normalized: &str, log: &mut EventLog) -> Option<SymbolicAnswer> {
    if !normalized.contains("algorithm") && !normalized.contains("sort") {
        return None;
    }
    let with_tests = normalized.contains("test");
    let lang_slug = detect_algorithm_language(normalized);
    let body = build_sorting_algorithm_answer(lang_slug, with_tests);
    let intent = format!("algorithm_sort_{lang_slug}");
    log.append(
        "execution_status",
        ExecutionStatus::Unavailable.label().to_owned(),
    );
    log.append(
        "execution_environment",
        "no compile/run sandbox configured for this generated snippet".to_owned(),
    );
    Some(finalize_simple(
        prompt,
        log,
        &intent,
        "response:algorithm",
        &body,
        1.0,
    ))
}

pub fn try_execution_failure(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    if !normalized.contains("undefined_function") {
        return None;
    }
    log.append("trace:execution_failure", "undefined_function".to_owned());
    let body = String::from(
        "Execution status: failed in isolated sandbox.\n\
         ```python\nundefined_function()\n```\n\
         Traceback (most recent call last):\n  File 'main.py', line 1, in <module>\n\
         NameError: name 'undefined_function' is not defined.\n\
         The failure trace is appended to the action log; see the trace link.",
    );
    let agent_request = normalized.contains("[agent]");
    if agent_request {
        log.append("agent_mode:opted_in", prompt.to_owned());
        log.append("action_log", prompt.to_owned());
    }
    Some(finalize_simple(
        prompt,
        log,
        "execution_failure",
        "response:execution_failure",
        &body,
        0.4,
    ))
}

pub fn try_source_refresh(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    if !normalized.contains("refresh")
        || !(normalized.contains("cache") || normalized.contains("page"))
    {
        return None;
    }
    let target = stable_id("source", prompt);
    log.append("source_refresh", target.clone());
    let body = format!(
        "Cached source {target} has been queued for refresh against its origin URL. The \
         refresh event is appended to the audit log and a fresh fetched_at timestamp will be \
         recorded once the new copy is verified."
    );
    Some(finalize_simple(
        prompt,
        log,
        "source_refresh",
        "response:source_refresh",
        &body,
        1.0,
    ))
}

pub fn try_source_conflict(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    if !(normalized.contains("conflict")
        || (normalized.contains("born in") && normalized.contains(" or ")))
    {
        return None;
    }
    log.append(
        "conflict:source_disagreement",
        "sources disagree on the answer".to_owned(),
    );
    let body = String::from(
        "Sources disagree on this question. The disagreement is recorded as a \
         conflict:source_disagreement link in the network rather than silently resolved.",
    );
    Some(finalize_simple(
        prompt,
        log,
        "source_conflict",
        "response:source_conflict",
        &body,
        0.3,
    ))
}

pub fn finalize_simple(
    prompt: &str,
    log: &mut EventLog,
    intent: &str,
    response_link: &str,
    body: &str,
    confidence: f32,
) -> SymbolicAnswer {
    log.append("intent", intent.to_owned());
    log.append("response", response_link.to_owned());
    let trace_id = log.append("trace", intent.to_owned());
    let evidence_links = build_evidence_links(prompt, log, response_link);
    let links_notation = answer_links_notation(prompt, intent, body, log, &trace_id);
    SymbolicAnswer {
        intent: intent.to_owned(),
        answer: body.to_owned(),
        confidence,
        evidence_links,
        links_notation,
    }
}