Report preflight provider verification and usage

This commit is contained in:
2026-11-27 01:22:58 +00:00
parent a0292a3ba0
commit a9ab8e59b3
3 changed files with 191 additions and 2 deletions

View File

@@ -281,6 +281,8 @@ upstream-owned. The domain preflight package contains no provider types.
## Stage 7: Finish preflight reporting and provider orchestration
**Completed.**
Work:
1. After all shared local checks and destination probes succeed, call verification

View File

@@ -1,22 +1,97 @@
package cli
import (
"fmt"
"io"
"strings"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm"
commandkit "go.maximumdirect.net/commandkit"
pk "go.maximumdirect.net/promptkit"
)
func runPreflight(inv commandkit.Invocation, input processInput) commandkit.Outcome {
reporter := inv.Reporter()
_ = reporter.Progress("Checking local processing readiness.")
loaded, err := loadProcessInputs(inv.Context, input, inv.ReportingMode())
if err != nil {
return acquisitionOutcome(inv, err)
}
prepared, err := prepareLocal(inv.Context, input, loaded, inv.Reporter().Output())
prepared, err := prepareLocal(inv.Context, input, loaded, reporter.Output())
if err != nil {
return preparationOutcome(inv, err)
}
if err := diagnostics.ProbeOutput(inv.Context, prepared.Destinations); err != nil {
return commandkit.Failure(err.Error()).WithCause(err)
}
_ = inv.Reporter().AtEnd().Info("Local preflight checks passed.")
if !input.Smoke.Value {
_ = reporter.AtEnd().Info("Local preflight checks passed; provider verification was skipped.")
return commandkit.Success()
}
if len(prepared.Plan.Profiles) == 0 {
_ = reporter.AtEnd().Info("Local preflight checks passed; no profiles were selected for provider verification.")
return commandkit.Success()
}
_ = reporter.Progress("Checking structured output for selected profiles.")
results, err := llm.VerifyStructuredOutput(inv.Context, loaded.Runtime.Engine, prepared.Plan.Profiles)
if err != nil {
details := make([]commandkit.Detail, 0, len(results))
for _, result := range results {
line := verificationLine(result)
details = append(details, func(w io.Writer) error { _, err := io.WriteString(w, line+"\n"); return err })
}
return commandkit.Failure("Structured-output verification failed.", details...).WithCause(err)
}
for _, result := range results {
_ = reporter.Info(verificationLine(result))
}
_ = reporter.AtEnd().Info("Local and structured-output preflight checks passed.")
return commandkit.Success()
}
func verificationLine(result llm.ProfileVerification) string {
line := fmt.Sprintf("Profile %q: %s", result.ProfileID, result.Status)
if result.Report == nil {
return line + "; smoke usage: unknown"
}
report := result.Report
if result.Status != llm.VerificationSuccess {
line += fmt.Sprintf(" (completed=%t, generation=%s, JSON=%s, schema=%s", report.Completed, boolObservation(report.Facts.GenerationCompleted), boolObservation(report.Facts.ValidJSON), boolObservation(report.Facts.SchemaMatched))
if report.Failure != pk.ExecutionFailureNone {
line += ", failure=" + string(report.Failure)
}
if report.Reason != pk.SmokeTestReasonNone {
line += ", reason=" + string(report.Reason)
}
line += ")"
}
usage := report.Usage
counts := []struct {
name string
count pk.ObservedTokenCount
}{
{"prompt", usage.PromptTokens}, {"completion", usage.CompletionTokens}, {"reasoning", usage.ReasoningTokens}, {"total", usage.TotalTokens}, {"cached", usage.CachedTokens}, {"cache-write", usage.CacheWriteTokens},
}
parts := make([]string, 0, len(counts))
for _, count := range counts {
value := "unknown"
if count.count.Known {
value = fmt.Sprintf("%d", count.count.Value)
if !count.count.Complete {
value += " (partial)"
}
}
parts = append(parts, count.name+"="+value)
}
return line + "; smoke usage: " + strings.Join(parts, ", ")
}
func boolObservation(value *bool) string {
if value == nil {
return "unknown"
}
if *value {
return "true"
}
return "false"
}

View File

@@ -3,8 +3,15 @@ package cli
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"testing"
@@ -69,3 +76,108 @@ func TestPreflightBindingsAndRunAlias(t *testing.T) {
t.Fatalf("process accepted smoke flag: %d", status)
}
}
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())
}
}