File size: 2,578 Bytes
1840039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
:- consult('sovereign_verification.pl').

generate_problems(Intent, MathlibCtx, OperatorSig, OutputFile) :-
    setup_call_cleanup(
        open(OutputFile, write, Stream),
        json_write_dict(Stream, _{
            id:"demo-problem-1",
            statement:Intent,
            context:MathlibCtx,
            tacticHint:"aesop",
            meta:_{
                source:"granite-4.1-verifier",
                timestamp:"2026-07-14T00:00:00Z",
                operatorSig:OperatorSig,
                maxSteps:30,
                allowedTactics:["rw","simp_all","norm_num","linarith","nlinarith","aesop","apply","exact","intro","obtain","cases","induction"]
            }
        }, [width(0)]),
        close(Stream)
    ).

call_granite(InputFile, OutputFile) :-
    setup_call_cleanup(
        open(InputFile, read, In),
        read_string(In, _, Content),
        close(In)
    ),
    setup_call_cleanup(
        open(OutputFile, write, Out),
        format(Out, "{\"problemId\":\"demo-problem-1\",\"status\":\"proposed\",\"proofScript\":\"~w\",\"diagnostics\":[]}~n", [Content]),
        close(Out)
    ).

parse_and_validate(JsonlFile, success(JsonlFile)).

%% Shell out to `lake exe verify -- --parse <file>` and capture exit code.
%% Requires SWI-Prolog shell/2. Lake must be on PATH or LAKE_BIN env set.
execute_verification(JsonlFile, Result) :-
    ( getenv('LAKE_BIN', Lake) -> true ; Lake = 'lake' ),
    atomic_list_concat([Lake, ' exe verify -- --parse ', JsonlFile], Cmd),
    ( shell(Cmd, 0) ->
        Result = result(0, verified)
    ;
        Result = result(1, parse_failed)
    ).

verify_with_retries(Intent, OperatorSig, MaxRetries, FinalResult) :-
    verify_loop(Intent, OperatorSig, 0, MaxRetries, FinalResult).

verify_loop(Intent, OperatorSig, Attempt, MaxRetries, FinalResult) :-
    Attempt < MaxRetries,
    generate_problems(Intent, ["import Mathlib"], OperatorSig, 'input.jsonl'),
    call_granite('input.jsonl', 'granite_response.jsonl'),
    parse_and_validate('granite_response.jsonl', ParseRes),
    ( ParseRes = success(_) ->
        execute_verification('granite_response.jsonl', KernelResult),
        ( KernelResult = result(0, _) ->
            FinalResult = success(KernelResult)
        ; NextAttempt is Attempt + 1,
          verify_loop(Intent, OperatorSig, NextAttempt, MaxRetries, FinalResult)
        )
    ; NextAttempt is Attempt + 1,
      verify_loop(Intent, OperatorSig, NextAttempt, MaxRetries, FinalResult)
    ).

verify_loop(_, _, Attempt, MaxRetries, fail(max_retries_exceeded)) :-
    Attempt >= MaxRetries.