2026-11-27 01:19:17 +00:00
package cli
import (
"bytes"
"context"
2026-11-27 01:22:58 +00:00
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
2026-11-27 01:19:17 +00:00
"os"
"path/filepath"
2026-11-27 01:22:58 +00:00
"slices"
2026-11-27 01:19:17 +00:00
"strings"
"testing"
2026-11-27 01:26:07 +00:00
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm"
2026-11-27 01:19:17 +00:00
commandkit "go.maximumdirect.net/commandkit"
2026-11-27 01:26:07 +00:00
pk "go.maximumdirect.net/promptkit"
2026-11-27 01:19:17 +00:00
)
func TestPreflightBindingsAndRunAlias ( t * testing . T ) {
dir := t . TempDir ( )
for name , contents := range map [ string ] string {
"config.yml" : "version: 3\npipeline: {stages: []}\nreporting: {enabled: false}\n" ,
"transcript.json" : ` [ { "speaker":"Alice","start":0,"end":1,"text":"hello"}] ` ,
"glossary.yml" : "party: {entries: [{id: alice, name: Alice, category: person}]}\n" ,
"overlays/local.yml" : "context: {description: Local example}\n" ,
} {
path := filepath . Join ( dir , name )
if err := os . MkdirAll ( filepath . Dir ( path ) , 0755 ) ; err != nil {
t . Fatal ( err )
}
if err := os . WriteFile ( path , [ ] byte ( contents ) , 0600 ) ; err != nil {
t . Fatal ( err )
}
}
app , err := buildApplication ( )
if err != nil {
t . Fatal ( err )
}
cfg , transcript , output := filepath . Join ( dir , "config.yml" ) , filepath . Join ( dir , "transcript.json" ) , filepath . Join ( dir , "out.json" )
if err := os . WriteFile ( output , [ ] byte ( "existing" ) , 0600 ) ; err != nil {
t . Fatal ( err )
}
common := [ ] string { "--config" , cfg , "--overlay" , "local" , "--glossary-file" , filepath . Join ( dir , "glossary.yml" ) , "--glossaries" , ` ["party"] ` , "--output" , output , transcript }
var out , stderr bytes . Buffer
invoke := func ( args ... string ) int {
out . Reset ( )
stderr . Reset ( )
return app . Execute ( context . Background ( ) , args , commandkit . Streams { Out : & out , Err : & stderr } ) . Status
}
args := append ( [ ] string { "preflight" , "--smoke=false" } , common ... )
if status := invoke ( args ... ) ; status != 0 {
t . Fatalf ( "preflight %d: %s" , status , stderr . String ( ) )
}
if data , err := os . ReadFile ( output ) ; err != nil || string ( data ) != "existing" {
t . Fatalf ( "destination changed: %q %v" , data , err )
}
if status := invoke ( "preflight" , "--help" ) ; status != 0 || ! strings . Contains ( out . String ( ) , "--smoke" ) {
t . Fatalf ( "help %d: %s %s" , status , out . String ( ) , stderr . String ( ) )
}
if status := invoke ( "preflight" , "--quiet" , "--config" , filepath . Join ( dir , "missing" ) , transcript ) ; status != 2 || ! strings . Contains ( stderr . String ( ) , "quiet" ) {
t . Fatalf ( "quiet %d: %s" , status , stderr . String ( ) )
}
if status := invoke ( "preflight" , "--quiet" , "--smoke=false" , "--config" , cfg , "--output" , os . DevNull , transcript ) ; status != 0 {
t . Fatalf ( "null %d: %s" , status , stderr . String ( ) )
}
args = append ( [ ] string { "run" } , common ... )
if status := invoke ( args ... ) ; status != 0 {
t . Fatalf ( "alias %d: %s" , status , stderr . String ( ) )
}
if data , err := os . ReadFile ( output ) ; err != nil || string ( data ) == "existing" || ! strings . Contains ( string ( data ) , "hello" ) {
t . Fatalf ( "alias output: %q %v" , data , err )
}
if status := invoke ( "process" , "--smoke=false" , transcript ) ; status != 2 {
t . Fatalf ( "process accepted smoke flag: %d" , status )
}
}
2026-11-27 01:22:58 +00:00
func TestPreflightVerifiesDistinctProfilesAfterLocalChecks ( t * testing . T ) {
dir := t . TempDir ( )
var models [ ] string
var negative bool
server := httptest . NewServer ( http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
var body struct {
Model string ` json:"model" `
}
if err := json . NewDecoder ( r . Body ) . Decode ( & body ) ; err != nil {
t . Error ( err )
return
}
models = append ( models , body . Model )
content := ` { "status":"ok"} `
if negative && body . Model == "review-model" {
content = ` { "bad":true} `
}
_ = json . NewEncoder ( w ) . Encode ( map [ string ] any { "model" : body . Model , "choices" : [ ] any { map [ string ] any { "message" : map [ string ] any { "role" : "assistant" , "content" : content } } } , "usage" : map [ string ] int { "prompt_tokens" : 7 , "completion_tokens" : 3 , "total_tokens" : 10 } } )
} ) )
defer server . Close ( )
for name , contents := range map [ string ] string {
"config.yml" : "version: 3\nllm: {proposal_profile: proposal, validation_profile: review, correction_repair_profile: unused, correction_repair_attempts: 0}\npipeline: {stages: [{module: grammar}]}\n" ,
"prompts.yml" : fmt . Sprintf ( "backends:\n - id: shared\n endpoint: %s/v1\nprofiles:\n - {id: proposal, backend: shared, model: proposal-model}\n - {id: review, backend: shared, model: review-model}\n - {id: unused, backend: shared, model: unused-model}\n" , server . URL ) ,
"transcript.json" : ` [ { "speaker":"Alice","start":0,"end":1,"text":"private transcript"}] ` ,
"output.json" : "existing output" ,
} {
if err := os . WriteFile ( filepath . Join ( dir , name ) , [ ] byte ( contents ) , 0600 ) ; err != nil {
t . Fatal ( err )
}
}
app , err := buildApplication ( )
if err != nil {
t . Fatal ( err )
}
var out , stderr bytes . Buffer
args := [ ] string { "preflight" , "--config" , filepath . Join ( dir , "config.yml" ) , "--output" , filepath . Join ( dir , "output.json" ) , "--work-dir" , filepath . Join ( dir , "debug" ) , "--debug" , filepath . Join ( dir , "transcript.json" ) }
invoke := func ( args [ ] string ) int {
out . Reset ( )
stderr . Reset ( )
models = nil
return app . Execute ( context . Background ( ) , args , commandkit . Streams { Out : & out , Err : & stderr } ) . Status
}
if status := invoke ( args ) ; status != 0 || ! slices . Equal ( models , [ ] string { "proposal-model" , "review-model" } ) || ! strings . Contains ( stderr . String ( ) , "smoke usage" ) || ! strings . Contains ( stderr . String ( ) , "total=10" ) {
t . Fatalf ( "success %d models=%v stdout=%s stderr=%s" , status , models , out . String ( ) , stderr . String ( ) )
}
local := append ( [ ] string { } , args ... )
local = append ( local [ : 1 ] , append ( [ ] string { "--smoke=false" } , local [ 1 : ] ... ) ... )
if status := invoke ( local ) ; status != 0 || len ( models ) != 0 {
t . Fatalf ( "local %d models=%v err=%s" , status , models , stderr . String ( ) )
}
invalid := append ( [ ] string { } , args ... )
invalid = append ( invalid [ : 1 ] , append ( [ ] string { "--target-sections=2" } , invalid [ 1 : ] ... ) ... )
if status := invoke ( invalid ) ; status != 2 || len ( models ) != 0 {
t . Fatalf ( "invalid %d models=%v err=%s" , status , models , stderr . String ( ) )
}
negative = true
quiet := append ( [ ] string { } , args ... )
quiet = append ( quiet [ : 1 ] , append ( [ ] string { "--quiet" } , quiet [ 1 : ] ... ) ... )
if status := invoke ( quiet ) ; status != 1 || len ( models ) != 2 || ! strings . Contains ( stderr . String ( ) , ` Profile "review": negative ` ) || strings . Contains ( stderr . String ( ) , "private transcript" ) || strings . Contains ( stderr . String ( ) , ` "bad" ` ) {
t . Fatalf ( "negative %d models=%v err=%s" , status , models , stderr . String ( ) )
}
if data , err := os . ReadFile ( filepath . Join ( dir , "output.json" ) ) ; err != nil || string ( data ) != "existing output" {
t . Fatalf ( "output changed: %q %v" , data , err )
}
for _ , name := range [ ] string { "errors.yml" , "recoveries.yml" , "report.md" , "debug" } {
if _ , err := os . Stat ( filepath . Join ( dir , name ) ) ; ! os . IsNotExist ( err ) {
t . Fatalf ( "artifact %s exists: %v" , name , err )
}
}
}
func TestPreflightCancellationRetainsPartialProfileDiagnostics ( t * testing . T ) {
dir := t . TempDir ( )
ctx , cancel := context . WithCancel ( context . Background ( ) )
defer cancel ( )
calls := 0
server := httptest . NewServer ( http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
calls ++
if calls == 2 {
cancel ( )
return
}
_ , _ = io . WriteString ( w , ` { "model":"fixture","choices":[ { "message": { "role":"assistant","content":" { \"status\":\"ok\"}"}}],"usage": { "prompt_tokens":7,"completion_tokens":3,"total_tokens":10}} ` )
} ) )
defer server . Close ( )
for name , contents := range map [ string ] string {
"config.yml" : "version: 3\nllm: {proposal_profile: one, validation_profile: two}\npipeline: {stages: [{module: grammar}]}\nreporting: {enabled: false}\n" ,
"prompts.yml" : fmt . Sprintf ( "profiles:\n - {id: one, endpoint: %s/v1, model: one}\n - {id: two, endpoint: %s/v1, model: two}\n" , server . URL , server . URL ) ,
"transcript.json" : ` [ { "speaker":"Alice","start":0,"end":1,"text":"hello"}] ` ,
} {
if err := os . WriteFile ( filepath . Join ( dir , name ) , [ ] byte ( contents ) , 0600 ) ; err != nil {
t . Fatal ( err )
}
}
app , err := buildApplication ( )
if err != nil {
t . Fatal ( err )
}
var out , stderr bytes . Buffer
result := app . Execute ( ctx , [ ] string { "preflight" , "--quiet" , "--config" , filepath . Join ( dir , "config.yml" ) , "--output" , filepath . Join ( dir , "out" ) , filepath . Join ( dir , "transcript.json" ) } , commandkit . Streams { Out : & out , Err : & stderr } )
if result . Status != 1 || calls != 2 || ! errors . Is ( result . Cause , context . Canceled ) || ! strings . Contains ( stderr . String ( ) , ` Profile "one": success ` ) || ! strings . Contains ( stderr . String ( ) , ` Profile "two": inconclusive ` ) {
t . Fatalf ( "status=%d calls=%d cause=%v stderr=%q" , result . Status , calls , result . Cause , stderr . String ( ) )
}
}
2026-11-27 01:26:07 +00:00
func TestPreflightUsagePreservesUnknownAndCompleteness ( t * testing . T ) {
report := & pk . SmokeTestReport { Usage : pk . ObservedTokenUsage {
PromptTokens : pk . ObservedTokenCount { Known : true , Complete : false , Value : 4 } ,
CompletionTokens : pk . ObservedTokenCount { Known : true , Complete : true , Value : 0 } ,
TotalTokens : pk . ObservedTokenCount { Known : false , Complete : true } ,
} }
line := verificationLine ( llm . ProfileVerification { ProfileID : "fixture" , Status : llm . VerificationSuccess , Report : report } )
for _ , want := range [ ] string { "prompt=4 (incomplete)" , "completion=0 (complete)" , "total=unknown (complete)" , "reasoning=unknown (incomplete)" } {
if ! strings . Contains ( line , want ) {
t . Fatalf ( "missing %q in %q" , want , line )
}
}
}
2026-11-27 04:03:24 +00:00
func TestPreflightExplainsNativePreparationError ( t * testing . T ) {
dir := t . TempDir ( )
for name , body := range map [ string ] string {
"config.yml" : "version: 3\nllm: {proposal_profile: selected}\npipeline: {stages: [{module: grammar}]}\nreporting: {enabled: false}\n" ,
"prompts.yml" : "profiles: [{id: selected, endpoint: 'http://example.invalid/v1'}]\n" ,
"transcript.json" : ` [ { "speaker":"A","start":0,"end":1,"text":"hello"}] ` ,
} {
if err := os . WriteFile ( filepath . Join ( dir , name ) , [ ] byte ( body ) , 0600 ) ; err != nil {
t . Fatal ( err )
}
}
app , err := buildApplication ( )
if err != nil {
t . Fatal ( err )
}
for _ , flags := range [ ] [ ] string { nil , { "--quiet" } , { "--debug" } } {
var out , diagnostic bytes . Buffer
args := append ( [ ] string { "preflight" } , flags ... )
args = append ( args , "--config" , filepath . Join ( dir , "config.yml" ) , "--output" , filepath . Join ( dir , "out.json" ) , filepath . Join ( dir , "transcript.json" ) )
result := app . Execute ( context . Background ( ) , args , commandkit . Streams { Out : & out , Err : & diagnostic } )
if result . Status != 1 || result . Cause == nil || ! strings . Contains ( diagnostic . String ( ) , ` Profile "selected" ` ) || ! strings . Contains ( diagnostic . String ( ) , "model is required" ) {
t . Fatalf ( "status=%d cause=%v diagnostic=%s" , result . Status , result . Cause , diagnostic . String ( ) )
}
}
}