Skip to main content

tpt_telos_agent/
lib.rs

1//! The agentic transpiler core for tpt-telos (Phase 2).
2//!
3//! This crate implements the *Generate -> Verify -> Counter-example -> Rewrite*
4//! loop described in the design document:
5//!
6//! 1. An LLM-style [`CodeAgent`] produces a candidate implementation (a body of
7//!    `mutate state` / assignment statements) from a function's intent
8//!    (`requires` / `ensures` and `@boundary` routing).
9//! 2. The formal verifier checks the candidate against the mathematical
10//!    contract.
11//! 3. On failure, the solver extracts a concrete counter-example (a variable
12//!    assignment where the contract is violated).
13//! 4. The agent rewrites the candidate using that counter-example, and the loop
14//!    repeats until the contract is provably satisfied.
15//!
16//! The default [`StaticAgent`] is a fully offline, deterministic synthesizer:
17//! it translates the developer's stated body when present, and otherwise
18//! derives an implementation directly from the `ensures` clauses. Real LLM
19//! backends can be plugged in behind the [`CodeAgent`] trait (see
20//! [`llm_agent`] behind the `llm` feature).
21
22pub mod static_agent;
23
24#[cfg(feature = "llm")]
25pub mod llm_agent;
26
27pub use static_agent::{synthesize_from_ensures, StaticAgent};
28
29use tpt_telos_ir::{extract, VerificationProblem};
30use tpt_telos_parser::ast::*;
31use tpt_telos_verifier::{counterexample, verify, Model, VerificationResult};
32
33/// An owned view of a single function's verification intent, detached from the
34/// surrounding module so agents can be reasoned about in isolation.
35///
36/// # Examples
37///
38/// ```
39/// use tpt_telos_parser::parse;
40/// use tpt_telos_agent::FuncSpec;
41///
42/// let modules = parse("module M { func f(x: T) ; }").unwrap();
43/// let m = &modules[0];
44/// if let tpt_telos_parser::ast::Item::Func(func) = &m.items[0] {
45///     let spec = FuncSpec::new(m.attributes.clone(), func.clone());
46///     assert_eq!(spec.func.name, "f");
47/// }
48/// ```
49#[derive(Clone)]
50pub struct FuncSpec {
51    pub module_attrs: Vec<Attribute>,
52    pub func: Func,
53}
54
55impl FuncSpec {
56    pub fn new(module_attrs: Vec<Attribute>, func: Func) -> Self {
57        FuncSpec { module_attrs, func }
58    }
59}
60
61/// A candidate implementation produced by an agent: the statements that form
62/// the function body.
63///
64/// # Examples
65///
66/// ```
67/// use tpt_telos_agent::Candidate;
68///
69/// let empty = Candidate { stmts: vec![] };
70/// assert!(empty.stmts.is_empty());
71/// ```
72#[derive(Clone, PartialEq, Eq)]
73pub struct Candidate {
74    pub stmts: Vec<Stmt>,
75}
76
77/// A code-generation agent. Implementations may be deterministic (offline) or
78/// backed by an external LLM; both speak the same structured `Stmt` language so
79/// the output is guaranteed to lower into compilable Rust/Go.
80pub trait CodeAgent {
81    /// Human-readable agent name (for logs).
82    fn name(&self) -> &str;
83
84    /// Produce an initial candidate implementation for `spec`.
85    fn generate(&self, spec: &FuncSpec) -> Result<Candidate, String>;
86
87    /// Rewrite a previous candidate using a concrete counter-example where the
88    /// contract failed. `ce` maps variable names (pre-state `"base.field"` and
89    /// post-state `"base.field'"`) to integer values.
90    fn rewrite(&self, spec: &FuncSpec, prev: &Candidate, ce: &Model) -> Result<Candidate, String>;
91}
92
93/// One iteration of the agentic loop, for transparent reporting.
94#[derive(Clone)]
95pub struct LoopStep {
96    pub iteration: usize,
97    pub action: String,
98    pub candidate: Candidate,
99    pub passed: bool,
100    pub counterexample: Option<Model>,
101}
102
103/// The full outcome of transpiling one function through the agentic loop.
104#[derive(Clone)]
105pub struct FuncOutcome {
106    pub func_name: String,
107    pub target: tpt_telos_router::Target,
108    pub agent: String,
109    pub iterations: Vec<LoopStep>,
110    pub final_candidate: Candidate,
111    pub problem: VerificationProblem,
112    pub result: VerificationResult,
113    pub verified: bool,
114}
115
116const MAX_ITERS: usize = 8;
117
118/// Build the verification problem for a candidate body by substituting it into
119/// the module (preserving the module's invariants and routing metadata).
120fn problem_for(
121    module: &Module,
122    func_idx: usize,
123    stmts: &[Stmt],
124) -> Result<VerificationProblem, String> {
125    let mut module = module.clone();
126    module.items[func_idx] = match &module.items[func_idx] {
127        Item::Func(f) => {
128            let mut f = f.clone();
129            f.body = stmts.to_vec();
130            f.elided = false;
131            Item::Func(f)
132        }
133        other => other.clone(),
134    };
135    let problems = extract(&[module.clone()])?;
136    problems
137        .into_iter()
138        .find(|p| p.func_name == module.items[func_idx].func_name())
139        .ok_or_else(|| {
140            format!(
141                "internal error: no verification problem extracted for function '{}'",
142                module.items[func_idx].func_name()
143            )
144        })
145}
146
147fn find_counterexample(
148    problem: &VerificationProblem,
149    result: &VerificationResult,
150) -> Option<Model> {
151    for (concl, check) in problem.conclusions.iter().zip(result.checks.iter()) {
152        if !check.passed {
153            if let Some(m) = counterexample(&problem.premises, &concl.constraint) {
154                return Some(m);
155            }
156        }
157    }
158    None
159}
160
161/// Run the agentic transpilation loop for a single function.
162///
163/// # Examples
164///
165/// ```
166/// use tpt_telos_parser::parse;
167/// use tpt_telos_agent::{transpile_func, StaticAgent};
168///
169/// let src = r#"
170///     module Bank {
171///         invariant Wallet { balance >= 0 }
172///         func deposit(w: Wallet, amount: PositiveInt)
173///             ensures w.balance == old(w.balance) + amount
174///         ;
175///     }
176/// "#;
177///
178/// let modules = parse(src).unwrap();
179/// let agent = StaticAgent::new();
180/// // index 0 is the invariant; index 1 is the `deposit` function
181/// let outcome = transpile_func(&modules[0], 1, &agent).unwrap();
182///
183/// assert_eq!(outcome.func_name, "deposit");
184/// assert!(outcome.verified);
185/// ```
186pub fn transpile_func(
187    module: &Module,
188    func_idx: usize,
189    agent: &dyn CodeAgent,
190) -> Result<FuncOutcome, String> {
191    let func = match &module.items[func_idx] {
192        Item::Func(f) => f.clone(),
193        _ => return Err("transpile_func requires a function item".into()),
194    };
195    let spec = FuncSpec::new(module.attributes.clone(), func.clone());
196    let target = tpt_telos_router::route(&module.attributes).target;
197
198    let mut candidate = if func.elided || func.body.is_empty() {
199        agent.generate(&spec)?
200    } else {
201        // Start from the developer's stated body; verify it before trusting it.
202        Candidate {
203            stmts: func.body.clone(),
204        }
205    };
206
207    let mut iterations = Vec::new();
208
209    for iter in 0..MAX_ITERS {
210        let problem = problem_for(module, func_idx, &candidate.stmts)?;
211        let result = verify(&problem);
212        let passed = result.all_passed;
213
214        iterations.push(LoopStep {
215            iteration: iter,
216            action: if iter == 0 {
217                "generate".to_string()
218            } else {
219                "rewrite".to_string()
220            },
221            candidate: candidate.clone(),
222            passed,
223            counterexample: if passed {
224                None
225            } else {
226                find_counterexample(&problem, &result)
227            },
228        });
229
230        if passed {
231            return Ok(FuncOutcome {
232                func_name: func.name.clone(),
233                target,
234                agent: agent.name().to_string(),
235                iterations,
236                final_candidate: candidate,
237                problem,
238                result,
239                verified: true,
240            });
241        }
242
243        let ce = find_counterexample(&problem, &result).unwrap_or_default();
244        let repaired = agent.rewrite(&spec, &candidate, &ce)?;
245        if repaired.stmts == candidate.stmts {
246            // Agent could not improve further; synthesize from the contract as a
247            // correct-by-construction fallback so the loop terminates.
248            let syn = static_agent::synthesize_from_ensures(&spec);
249            let syn_problem = problem_for(module, func_idx, &syn.stmts)?;
250            let syn_result = verify(&syn_problem);
251            iterations.push(LoopStep {
252                iteration: iter + 1,
253                action: "synthesize-from-ensures".to_string(),
254                candidate: syn.clone(),
255                passed: syn_result.all_passed,
256                counterexample: None,
257            });
258            return Ok(FuncOutcome {
259                func_name: func.name.clone(),
260                target,
261                agent: agent.name().to_string(),
262                iterations,
263                final_candidate: syn,
264                problem: syn_problem,
265                result: syn_result.clone(),
266                verified: syn_result.all_passed,
267            });
268        }
269        candidate = repaired;
270    }
271
272    // Loop exhausted without a proof; return the last candidate for diagnostics.
273    let problem = problem_for(module, func_idx, &candidate.stmts)?;
274    let result = verify(&problem);
275    Ok(FuncOutcome {
276        func_name: func.name.clone(),
277        target,
278        agent: agent.name().to_string(),
279        iterations,
280        final_candidate: candidate,
281        problem,
282        result,
283        verified: false,
284    })
285}
286
287/// Convenience: transpile every function in a module and collect outcomes.
288///
289/// # Examples
290///
291/// ```
292/// use tpt_telos_parser::parse;
293/// use tpt_telos_agent::{transpile_module, StaticAgent};
294///
295/// let src = r#"
296///     module Bank {
297///         invariant Wallet { balance >= 0 }
298///         func deposit(w: Wallet, amount: PositiveInt)
299///             ensures w.balance == old(w.balance) + amount
300///         ;
301///     }
302/// "#;
303///
304/// let modules = parse(src).unwrap();
305/// let outcomes = transpile_module(&modules[0], &StaticAgent::new()).unwrap();
306///
307/// assert_eq!(outcomes.len(), 1);
308/// assert!(outcomes[0].verified);
309/// ```
310pub fn transpile_module(
311    module: &Module,
312    agent: &dyn CodeAgent,
313) -> Result<Vec<FuncOutcome>, String> {
314    let mut out = Vec::new();
315    for (idx, item) in module.items.iter().enumerate() {
316        if let Item::Func(_) = item {
317            out.push(transpile_func(module, idx, agent)?);
318        }
319    }
320    Ok(out)
321}
322
323/// Convenience helper used by codegen: render a [`Candidate`] body back into
324/// source text via the parser's pretty-printer.
325///
326/// # Examples
327///
328/// ```
329/// use tpt_telos_parser::parse;
330/// use tpt_telos_agent::{StaticAgent, transpile_module, render_candidate};
331///
332/// let src = r#"
333///     module M {
334///         func noop(w: Wallet, amount: PositiveInt)
335///             ensures w.balance == old(w.balance) + amount
336///         ;
337///     }
338/// "#;
339///
340/// let modules = parse(src).unwrap();
341/// let outcomes = transpile_module(&modules[0], &StaticAgent::new()).unwrap();
342/// let text = render_candidate(&outcomes[0].final_candidate);
343/// assert!(text.contains("w.balance"));
344/// ```
345pub fn render_candidate(c: &Candidate) -> String {
346    let mut s = String::new();
347    for stmt in &c.stmts {
348        s.push_str(&render_stmt(stmt));
349        s.push('\n');
350    }
351    s
352}
353
354fn render_stmt(s: &Stmt) -> String {
355    match s {
356        Stmt::MutateState(assigns) => {
357            let inner = assigns
358                .iter()
359                .map(render_assign)
360                .collect::<Vec<_>>()
361                .join("\n");
362            format!("mutate state {{\n{}\n}}", indent(&inner))
363        }
364        Stmt::Assign(a) => render_assign(a),
365        Stmt::Let(lb) => {
366            let ty = lb
367                .ty
368                .as_ref()
369                .map(|t| format!(": {}", render_type(t)))
370                .unwrap_or_default();
371            format!("let {}{} = {};", lb.name, ty, pretty(&lb.value))
372        }
373        Stmt::If(is) => {
374            let mut out = format!("if {} {{\n", pretty(&is.condition));
375            for s in &is.then_body {
376                out.push_str(&indent(&render_stmt(s)));
377                out.push('\n');
378            }
379            out.push('}');
380            if let Some(else_body) = &is.else_body {
381                out.push_str(" else {\n");
382                for s in else_body {
383                    out.push_str(&indent(&render_stmt(s)));
384                    out.push('\n');
385                }
386                out.push('}');
387            }
388            out
389        }
390        Stmt::Match(ms) => {
391            let mut out = format!("match {} {{\n", pretty(&ms.scrutinee));
392            for arm in &ms.arms {
393                out.push_str(&format!("    {} => {{\n", render_pattern(&arm.pattern)));
394                for s in &arm.body {
395                    out.push_str(&indent(&render_stmt(s)));
396                    out.push('\n');
397                }
398                out.push_str("    }\n");
399            }
400            out.push('}');
401            out
402        }
403        Stmt::Return(e) => match e {
404            Some(expr) => format!("return {};", pretty(expr)),
405            None => "return;".to_string(),
406        },
407    }
408}
409
410fn render_assign(a: &Assign) -> String {
411    let op = match a.op {
412        AssignOp::Set => "=",
413        AssignOp::Add => "+=",
414        AssignOp::Sub => "-=",
415    };
416    format!("{} {} {};", pretty(&a.target), op, pretty(&a.value))
417}
418
419fn pretty(e: &Expr) -> String {
420    match e {
421        Expr::Int(n) => n.to_string(),
422        Expr::Var(v) => v.clone(),
423        Expr::Field { base, field } => format!("{}.{}", base, field),
424        Expr::Old(inner) => format!("old({})", pretty(inner)),
425        Expr::Unary { op, expr } => match op {
426            UnOp::Neg => format!("-{}", pretty(expr)),
427        },
428        Expr::Bin { op, lhs, rhs } => {
429            let s = match op {
430                BinOp::Add => "+",
431                BinOp::Sub => "-",
432                BinOp::Mul => "*",
433                BinOp::Div => "/",
434                BinOp::Eq => "==",
435                BinOp::Ne => "!=",
436                BinOp::Lt => "<",
437                BinOp::Le => "<=",
438                BinOp::Gt => ">",
439                BinOp::Ge => ">=",
440                BinOp::And => "&&",
441                BinOp::Or => "||",
442            };
443            format!("{} {} {}", pretty(lhs), s, pretty(rhs))
444        }
445        Expr::Call(c) => {
446            let args: Vec<_> = c.args.iter().map(pretty).collect();
447            format!("{}({})", c.func, args.join(", "))
448        }
449        Expr::MethodCall(m) => {
450            let args: Vec<_> = m.args.iter().map(pretty).collect();
451            format!("{}.{}({})", pretty(&m.receiver), m.method, args.join(", "))
452        }
453        Expr::Index(i) => format!("{}[{}]", pretty(&i.receiver), pretty(&i.index)),
454        Expr::If(i) => format!(
455            "if {} {{ {} }} else {{ {} }}",
456            pretty(&i.condition),
457            pretty(&i.then_expr),
458            pretty(&i.else_expr)
459        ),
460        Expr::Match(m) => {
461            let arms: Vec<_> = m
462                .arms
463                .iter()
464                .map(|a| format!("... => {}", pretty(&a.expr)))
465                .collect();
466            format!("match {} {{ {} }}", pretty(&m.scrutinee), arms.join(", "))
467        }
468        Expr::Try(e) => format!("{}?", pretty(e)),
469        Expr::Forall(f) => format!(
470            "forall {}: {} {{ {} }}",
471            f.var,
472            f.var_ty.name(),
473            pretty(&f.body)
474        ),
475        Expr::Aggregate(a) => {
476            let args: Vec<_> = a.args.iter().map(pretty).collect();
477            let op = match a.op {
478                AggregateOp::Sum => "sum",
479                AggregateOp::Min => "min",
480                AggregateOp::Max => "max",
481                AggregateOp::Count => "count",
482            };
483            format!("{}({})", op, args.join(", "))
484        }
485        Expr::Range { lo, hi } => format!("{}..{}", pretty(lo), pretty(hi)),
486    }
487}
488
489fn render_type(t: &Type) -> String {
490    match t {
491        Type::Named(s) => match s.as_str() {
492            "Float32" => "f32".to_string(),
493            "Float64" => "f64".to_string(),
494            "Int" => "i64".to_string(),
495            "PositiveInt" => "i64".to_string(),
496            other => other.to_string(),
497        },
498        Type::Generic(name, args) => {
499            let args: Vec<_> = args.iter().map(render_type).collect();
500            format!("{}<{}>", name, args.join(", "))
501        }
502        Type::Tuple(elems) => {
503            let elems: Vec<_> = elems.iter().map(render_type).collect();
504            format!("({})", elems.join(", "))
505        }
506        Type::Array(elem, len) => format!("[{}; {}]", render_type(elem), len),
507        Type::Slice(elem) => format!("[{}]", render_type(elem)),
508    }
509}
510
511fn render_pattern(p: &Pattern) -> String {
512    match p {
513        Pattern::Literal(n) => n.to_string(),
514        Pattern::Var(v) => v.clone(),
515        Pattern::Constructor(name, fields) => {
516            if fields.is_empty() {
517                name.clone()
518            } else {
519                let fields: Vec<_> = fields.iter().map(render_pattern).collect();
520                format!("{}({})", name, fields.join(", "))
521            }
522        }
523        Pattern::Wildcard => "_".to_string(),
524    }
525}
526
527fn indent(s: &str) -> String {
528    s.lines()
529        .map(|line| {
530            if line.is_empty() {
531                line.to_string()
532            } else {
533                format!("    {}", line)
534            }
535        })
536        .collect::<Vec<_>>()
537        .join("\n")
538}