package cli import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "path/filepath" "strings" "sync/atomic" "testing" "time" "go.maximumdirect.net/commandkit" "go.maximumdirect.net/promptkit" ) func TestNativeProviderAccountingAndSmokeUseTheConfiguredConvention(t *testing.T) { for _, zero := range []bool{false, true} { t.Run(fmt.Sprintf("known-zero=%t", zero), func(t *testing.T) { prompt, completion, reasoning, total, cached, written, cost := 8, 4, 1, 12, 2, 1, 0.125 if zero { prompt, completion, reasoning, total, cached, written, cost = 0, 0, 0, 0, 0, 0, 0 } var calls atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { calls.Add(1) if request.Method != http.MethodPost || request.URL.Path != "/v1/chat/completions" { t.Errorf("unexpected local provider request: %s %s", request.Method, request.URL.Path) } if request.Header.Get("Authorization") != "" { t.Error("credential-free fixture received authentication") } writer.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(writer).Encode(map[string]any{ "choices": []any{map[string]any{"message": map[string]any{"role": "assistant", "content": `{"spell_casts":[]}`}, "finish_reason": "stop"}}, "usage": map[string]any{ "prompt_tokens": prompt, "completion_tokens": completion, "total_tokens": total, "cost": cost, "prompt_tokens_details": map[string]any{"cached_tokens": cached, "cache_write_tokens": written}, "completion_tokens_details": map[string]any{"reasoning_tokens": reasoning}, }, }) })) defer server.Close() file := writeProductionContractConfig(t, fmt.Sprintf(`version: 6 output: {directory: output} debug: {directory: debug} pipelines: demo: input: {module: seriatim} chunk: {module: generic} llm_profile: accounting-profile artifacts: spells: extract: {module: dnd/spells} promptkit: backends: - id: arbitrary-transport provider: openrouter endpoint: %q profiles: - id: accounting-profile backend: arbitrary-transport model: accounting-model api_key_required: false `, server.URL+"/v1")) input := filepath.Join(filepath.Dir(file), "input.json") writeConfigKitFile(t, input, `{"metadata":{"id":"wire-source"},"segments":[{"id":1,"start":0,"end":1,"speaker":"GM","text":"The party rests."}]}`) app, err := NewApplication("development", Options{ LookupEnv: emptyLookup, Now: func() time.Time { return time.Unix(42, 0) }, RunIDGenerator: func(time.Time) (string, error) { return "wire-run", nil }, }) if err != nil { t.Fatal(err) } var stdout, diagnostics bytes.Buffer outcome := app.Execute(context.Background(), []string{"run", "demo", "--config", file, "--input-file", input, "--cache=bypass", "--debug", "--progress=false", "--show-tokens", "--format=json"}, commandkit.Streams{Out: &stdout, Err: &diagnostics}) if outcome.Status != 0 || calls.Load() != 1 { t.Fatalf("HTTP pipeline: %#v calls=%d stderr=%s", outcome, calls.Load(), diagnostics.String()) } report := decodeCompletionReport(t, commandkit.FormatJSON, stdout.Bytes()) if len(report) != 4 || report["artifact_count"] != float64(1) { t.Fatalf("usage changed completion output: %#v", report) } artifact := readProductionJSON[map[string]any](t, filepath.Join(report["output_directory"].(string), "lanes", "spells.json")) if len(artifact["spell_casts"].([]any)) != 0 { t.Fatalf("unexpected domain output: %#v", artifact) } summary := readProductionJSON[promptkit.ExecutionGroupSummary](t, filepath.Join(report["debug_directory"].(string), "executions.json")) if len(summary.Members) != 1 || !summary.TerminalCoverageComplete || summary.Attempts != 1 || summary.Usage.TotalTokens.Value != total || !summary.Usage.TotalTokens.Known || !summary.Usage.TotalTokens.Complete || summary.Usage.ReasoningTokens.Value != reasoning || !summary.Usage.ReasoningTokens.Known || summary.Usage.CachedTokens.Value != cached || summary.Usage.CacheWriteTokens.Value != written || !summary.CostUSD.Known || !summary.CostUSD.Complete || summary.CostUSD.Value != cost || summary.CostUSD.Source != "provider" { t.Fatalf("provider accounting lost at debug boundary: %#v", summary) } results := 0 for name, content := range readTree(t, report["debug_directory"].(string)) { if !strings.HasSuffix(name, "/result.json") { continue } results++ var result promptkit.RunResult if err := json.Unmarshal(content, &result); err != nil || result.Usage.TotalTokens != total || result.Usage.ReasoningTokens != reasoning || result.Usage.CacheWriteTokens != written || !result.CostUSD.Known || result.CostUSD.Value != cost { t.Fatalf("native result accounting: %#v %v", result, err) } } if results != 1 { t.Fatalf("native results=%d", results) } for _, fragment := range []string{"Prompts: 1", fmt.Sprintf("Total tokens: %d", total), fmt.Sprintf("Reasoning tokens: %d", reasoning), fmt.Sprintf("Cost: USD %g", cost)} { if !strings.Contains(diagnostics.String(), fragment) { t.Fatalf("missing %q: %s", fragment, diagnostics.String()) } } // Native smoke selects a target, not the prompt's body or required inputs. smoke := []string{"promptkit", "test", "text_inference", "--config", file, "--llm-prompt=notarius/dnd.spells", "--llm-profile=accounting-profile", "--show-tokens"} stdout.Reset() diagnostics.Reset() outcome = app.Execute(context.Background(), append(smoke, "--format=json"), commandkit.Streams{Out: &stdout, Err: &diagnostics}) if outcome.Status != 0 || calls.Load() != 2 { t.Fatalf("native smoke: %#v calls=%d stderr=%s", outcome, calls.Load(), diagnostics.String()) } smokeReport := decodeCompletionReport(t, commandkit.FormatJSON, stdout.Bytes()) usage := smokeReport["usage"].(map[string]any) count := usage["reasoning_tokens"].(map[string]any) if smokeReport["kind"] != "text_inference" || smokeReport["completed"] != true || count["value"] != float64(reasoning) || count["known"] != true || count["complete"] != true { t.Fatalf("smoke reasoning: %#v", smokeReport) } if zero && usage["cache_hit_ratio"] != nil || !zero && usage["cache_hit_ratio"] != 0.25 { t.Fatalf("smoke nullable ratio: %#v", usage) } if _, exists := smokeReport["cost_usd"]; exists { t.Fatal("smoke acquired a cost field") } if !strings.Contains(diagnostics.String(), "Prompts: 0") || !strings.Contains(diagnostics.String(), "Total tokens: 0") { t.Fatalf("smoke usage duplicated ordinary execution accounting: %s", diagnostics.String()) } stdout.Reset() diagnostics.Reset() outcome = app.Execute(context.Background(), smoke, commandkit.Streams{Out: &stdout, Err: &diagnostics}) if outcome.Status != 0 || calls.Load() != 3 || json.Valid(stdout.Bytes()) || !strings.Contains(stdout.String(), "text_inference") || !zero && !strings.Contains(stdout.String(), "25.0%") { t.Fatalf("native default smoke text: %#v stdout=%s stderr=%s", outcome, stdout.String(), diagnostics.String()) } }) } } func TestCompleteExampleInheritsNativeOpenRouterProvider(t *testing.T) { app, err := NewApplication("development", Options{LookupEnv: emptyLookup}) if err != nil { t.Fatal(err) } var stdout, diagnostics bytes.Buffer outcome := app.Execute(context.Background(), []string{"promptkit", "show", "backend", "limited-openrouter", "--config", repositoryPath("examples", "dnd-complete", "config.yml"), "--format=json"}, commandkit.Streams{Out: &stdout, Err: &diagnostics}) if outcome.Status != 0 { t.Fatalf("backend inspection: %#v %s", outcome, diagnostics.String()) } backend := decodeCompletionReport(t, commandkit.FormatJSON, stdout.Bytes()) if backend["provider"] != "openrouter" || backend["zero_cost"] != nil { t.Fatalf("native inheritance changed: %#v", backend) } }