diff --git a/cmd/audita/correction_repair_integration_test.go b/cmd/audita/correction_repair_integration_test.go index 60c7ba1..ec23650 100644 --- a/cmd/audita/correction_repair_integration_test.go +++ b/cmd/audita/correction_repair_integration_test.go @@ -17,6 +17,7 @@ import ( "time" "gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting" + pk "go.maximumdirect.net/promptkit" ) type repairWireMessage struct { @@ -115,7 +116,7 @@ func (p *correctionProvider) ServeHTTP(w http.ResponseWriter, r *http.Request) { } raw, _ := json.Marshal(content) w.Header().Set("Content-Type", "application/json") - fmt.Fprintf(w, `{"model":"fixture","choices":[{"message":{"content":%s}}]}`, raw) + fmt.Fprintf(w, `{"model":"fixture","choices":[{"message":{"content":%s}}],"usage":{"prompt_tokens":2,"completion_tokens":3,"total_tokens":5}}`, raw) } func TestSubprocessReportsDefectOnOriginatingRepair(t *testing.T) { @@ -190,7 +191,7 @@ func TestSubprocessCorrectionRepairConversation(t *testing.T) { provider.mu.Lock() provider.decimalReferences = tc.decimalReferences provider.mu.Unlock() - args := []string{"--verbose"} + args := []string{"--verbose", "--show-tokens"} if tc.debug { args = append(args, "--debug") } @@ -222,6 +223,9 @@ func TestSubprocessCorrectionRepairConversation(t *testing.T) { provider.mu.Lock() requests := append([]repairWireRequest(nil), provider.requests...) provider.mu.Unlock() + if !strings.Contains(stderr, fmt.Sprintf("Prompts: %d", len(requests))) || !strings.Contains(stderr, "Total tokens:") { + t.Fatalf("native usage did not cover the assembled pipeline: requests=%d stderr=%s", len(requests), stderr) + } var base []repairWireMessage var branches [][]repairWireMessage for _, req := range requests { @@ -271,13 +275,13 @@ func TestSubprocessCorrectionRepairConversation(t *testing.T) { } var execution struct { Summary struct { - ProviderAttempts int `json:"provider_attempts"` + PromptKit pk.ExecutionGroupSummary `json:"promptkit"` } `json:"summary"` } if err := json.Unmarshal(data, &execution); err != nil { t.Fatal(err) } - if got := execution.Summary.ProviderAttempts; got != len(requests) { + if got := execution.Summary.PromptKit.Attempts; got != uint64(len(requests)) { t.Fatalf("execution provider attempts = %d, captured requests = %d", got, len(requests)) } } @@ -336,7 +340,7 @@ func TestSubprocessCancellationDuringCorrectionRepair(t *testing.T) { f, provider := setupCorrectionFixture(t, 2, false, true) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - args := []string{"-test.run=^TestProcessSubprocessHelper$", "--", "process", f.transcript, "--config", f.config, "--output", f.output, "--debug"} + args := []string{"-test.run=^TestProcessSubprocessHelper$", "--", "process", f.transcript, "--config", f.config, "--output", f.output, "--debug", "--show-tokens"} command := exec.CommandContext(ctx, os.Args[0], args...) command.Env = append(os.Environ(), "AUDITA_HELPER_PROCESS=1") var stderr bytes.Buffer @@ -356,6 +360,12 @@ func TestSubprocessCancellationDuringCorrectionRepair(t *testing.T) { if ctx.Err() != nil || err == nil { t.Fatalf("cancellation: %v ctx=%v stderr=%s", err, ctx.Err(), stderr.String()) } + provider.mu.Lock() + count := len(provider.requests) + provider.mu.Unlock() + if !strings.Contains(stderr.String(), fmt.Sprintf("Prompts: %d", count)) { + t.Fatalf("canceled usage missing executions: requests=%d stderr=%s", count, stderr.String()) + } if _, err := os.Stat(f.output); !os.IsNotExist(err) { t.Fatalf("transcript published: %v", err) } diff --git a/cmd/audita/main_integration_test.go b/cmd/audita/main_integration_test.go index 63ce51b..d87b81e 100644 --- a/cmd/audita/main_integration_test.go +++ b/cmd/audita/main_integration_test.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "io" + "io/fs" "net/http" "net/http/httptest" "os" @@ -24,6 +25,8 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/cli" "gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting" "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" + "gitea.maximumdirect.net/eric/audita/v4/internal/prompts" + pk "go.maximumdirect.net/promptkit" "go.yaml.in/yaml/v4" ) @@ -195,7 +198,7 @@ func (p *fixtureProvider) serve(w http.ResponseWriter, r *http.Request) { } encoded, _ := json.Marshal(content) w.Header().Set("Content-Type", "application/json") - _, _ = fmt.Fprintf(w, `{"model":"synthetic","choices":[{"message":{"content":%s}}],"usage":{"prompt_tokens":2,"completion_tokens":3,"total_tokens":5}}`, encoded) + _, _ = fmt.Fprintf(w, `{"model":"synthetic","choices":[{"message":{"content":%s}}],"usage":{"prompt_tokens":2,"completion_tokens":3,"total_tokens":5,"completion_tokens_details":{"reasoning_tokens":1},"cost":0.02}}`, encoded) } // Read the supplied candidate JSON independently of the bundled instruction prose. @@ -261,6 +264,25 @@ func newProcessFixture(t *testing.T, mode, modules string) processFixture { if strings.HasPrefix(mode, "span-") || strings.HasPrefix(mode, "decision-") { repairs = 1 } + if repairs == 0 { + promptDir := filepath.Join(dir, "prompts") + if err := os.Mkdir(promptDir, 0700); err != nil { + t.Fatal(err) + } + for _, meta := range prompts.RegisteredMetadata() { + if strings.HasSuffix(meta.PromptID, ".repair") { + continue + } + data, err := fs.ReadFile(prompts.Filesystem(), meta.EmbeddedPath) + if err != nil { + t.Fatal(err) + } + data = append(data, []byte(" repair_attempts: 0\n")...) + if err := os.WriteFile(filepath.Join(promptDir, filepath.Base(meta.EmbeddedPath)), data, 0600); err != nil { + t.Fatal(err) + } + } + } var stageList []string for _, name := range strings.Split(strings.Trim(modules, "[]"), ",") { if name = strings.TrimSpace(name); name != "" { @@ -271,7 +293,7 @@ func newProcessFixture(t *testing.T, mode, modules string) processFixture { if len(stageList) != 0 { pipeline = " stages:\n" + strings.Join(stageList, "\n") + "\n" } - configText := fmt.Sprintf("version: 3\nllm:\n proposal_profile: proposal\n validation_profile: validation\n transient_retries: 0\n correction_repair_attempts: 0\n repair_attempts: %d\npipeline:\n%sdiagnostics:\n work_dir: %s\n", repairs, pipeline, filepath.Join(dir, "runs")) + configText := fmt.Sprintf("version: 3\nllm:\n proposal_profile: proposal\n validation_profile: validation\n transient_retries: 0\n correction_repair_attempts: 0\npipeline:\n%sdiagnostics:\n work_dir: %s\n", pipeline, filepath.Join(dir, "runs")) if strings.HasPrefix(mode, "span-") || strings.HasPrefix(mode, "decision-") { configText += "validation:\n max_prompt_tokens: 4096\nchunking:\n target_sections: 1\n max_section_tokens: 8192\n min_section_tokens: 1\nnormalization:\n max_segment_gap: 0\n" } @@ -311,6 +333,54 @@ func (f processFixture) run(t *testing.T, includeOutput bool, extra ...string) ( return code, stdout.String(), stderr.String() } +func TestSubprocessNativeUsageReporting(t *testing.T) { + for _, tc := range []struct { + name, mode, modules string + flags []string + fileOutput bool + wantPrompts string + wantUsage bool + }{ + {"normalization", "normal", "[]", []string{"--show-tokens"}, false, "Prompts: 0", true}, + {"failed provider", "all-model-failure", "[grammar]", []string{"--show-tokens"}, false, "Prompts: 1", true}, + {"quiet", "normal", "[grammar]", []string{"--show-tokens", "--quiet"}, true, "", false}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newProcessFixture(t, tc.mode, tc.modules) + code, stdout, stderr := f.run(t, tc.fileOutput, tc.flags...) + if code != 0 || strings.Contains(stdout, "Observed PromptKit execution usage") || strings.Contains(stderr, "Observed PromptKit execution usage") != tc.wantUsage { + t.Fatalf("status=%d stdout=%q stderr=%q", code, stdout, stderr) + } + if tc.wantUsage && !strings.Contains(stderr, tc.wantPrompts) { + t.Fatalf("missing usage count %q: %s", tc.wantPrompts, stderr) + } + if !tc.fileOutput && !json.Valid([]byte(stdout)) { + t.Fatalf("stdout is not transcript JSON: %q", stdout) + } + if _, err := os.Stat(filepath.Join(f.dir, "report.md")); err != nil { + t.Fatalf("ordinary report missing: %v", err) + } + }) + } +} + +func TestSubprocessExplicitProviderUsage(t *testing.T) { + f := newProcessFixture(t, "normal", "[grammar]") + path := filepath.Join(f.dir, "prompts.yml") + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + data = bytes.Replace(data, []byte(" - id: local\n"), []byte(" - id: local\n provider: openrouter\n"), 1) + if err := os.WriteFile(path, data, 0600); err != nil { + t.Fatal(err) + } + code, stdout, stderr := f.run(t, false, "--show-tokens") + if code != 0 || !json.Valid([]byte(stdout)) || f.provider.callCount() != 3 || !strings.Contains(stderr, "Reasoning tokens: 3") || !strings.Contains(stderr, "Cost: USD 0.06") { + t.Fatalf("provider usage: status=%d calls=%d stdout=%q stderr=%q", code, f.provider.callCount(), stdout, stderr) + } +} + func (f processFixture) errors(t *testing.T) reporting.ErrorsDocument { t.Helper() raw, err := os.ReadFile(filepath.Join(f.dir, "errors.yml")) @@ -431,10 +501,7 @@ func (f processFixture) assertNoStructuralRepairs(t *testing.T, wantCalls int) { } var execution struct { Calls []struct { - Summary struct { - ProviderAttempts int `json:"provider_attempts"` - StructuralRepairs int `json:"structural_repairs"` - } `json:"summary"` + PromptKit pk.ExecutionGroupSummary `json:"promptkit"` } `json:"calls"` } if err := json.Unmarshal(raw, &execution); err != nil { @@ -444,7 +511,7 @@ func (f processFixture) assertNoStructuralRepairs(t *testing.T, wantCalls int) { t.Fatalf("unexpected generation counts: calls=%d provider=%d", len(execution.Calls), f.provider.callCount()) } for _, call := range execution.Calls { - if call.Summary.ProviderAttempts != 1 || call.Summary.StructuralRepairs != 0 { + if call.PromptKit.Attempts != 1 || call.PromptKit.RepairCalls != 0 { t.Fatalf("unexpected structural repair: %+v", call) } } @@ -492,10 +559,7 @@ func (f processFixture) assertDecisionRequestsUseOneAttempt(t *testing.T) [][]in } var execution struct { Calls []struct { - Summary struct { - ProviderAttempts int `json:"provider_attempts"` - StructuralRepairs int `json:"structural_repairs"` - } `json:"summary"` + PromptKit pk.ExecutionGroupSummary `json:"promptkit"` } `json:"calls"` } if err := json.Unmarshal(raw, &execution); err != nil { @@ -505,7 +569,7 @@ func (f processFixture) assertDecisionRequestsUseOneAttempt(t *testing.T) [][]in t.Fatalf("logical/provider calls: %d/%d", len(execution.Calls), providerCalls) } for _, call := range execution.Calls { - if call.Summary.ProviderAttempts != 1 || call.Summary.StructuralRepairs != 0 { + if call.PromptKit.Attempts != 1 || call.PromptKit.RepairCalls != 0 { t.Fatalf("extra generation or structural repair: %+v", call) } } @@ -1414,7 +1478,7 @@ func TestSubprocessProfileSources(t *testing.T) { f := newProcessFixture(t, "success", "[]") // PromptKit uses profile IDs, not filename stems. A report-named profile is // still an input and must not be overwritten during report initialization. - if err := os.Mkdir(filepath.Join(f.dir, "prompts"), 0700); err != nil { + if err := os.MkdirAll(filepath.Join(f.dir, "prompts"), 0700); err != nil { t.Fatal(err) } loaded := filepath.Join(f.dir, "prompts", "errors.yml") diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 960f16f..306196f 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -409,6 +409,13 @@ the controlled workload, without copying CommandKit's report template or PromptKit's full retry/cost accounting suite. Keep Audita's ordinary completion message, partial-success behavior, capacity sharing, and output lifecycle. +**Complete.** Assembled command tests exercise native usage reporting through +proposal, validation, correction repair, failure, cancellation, debug and +quiet modes, as well as normalization-only processing. They cover an explicit +OpenRouter provider, prepared contract inspection, transcript stdout isolation, +and ordinary reports. The CLI, subprocess, and LLM package tests pass with +controlled providers and prompt-owned fixture budgets. + ## Stage 8: Update Maintained Examples, Migration Guidance, and Canonical Docs **Outcome:** Documentation explains Audita's changed integration and links to diff --git a/internal/cli/app_wiring_test.go b/internal/cli/app_wiring_test.go index 66e2a88..caf1107 100644 --- a/internal/cli/app_wiring_test.go +++ b/internal/cli/app_wiring_test.go @@ -194,11 +194,15 @@ collections: t.Fatalf("validator status=%d out=%q err=%q", outcome.Status, out, stderr) } validatorPreview := append([]string{"promptkit", "show", "prepared", "audita/validators.editorial_review"}, common...) - validatorPreview = append(validatorPreview, "--llm-var", `PayloadJSON=[{"correction_index":1,"original_segment_text":"teh cat","corrected_segment_text":"the cat"}]`, "--llm-var", "TranscriptDescriptionBlock=") + validatorPreview = append(validatorPreview, "--llm-var", `PayloadJSON=[{"correction_index":1,"original_segment_text":"teh cat","corrected_segment_text":"the cat"}]`, "--llm-var", "TranscriptDescriptionBlock=", "--format=json") outcome, out, stderr = execute(validatorPreview...) if outcome.Status != 0 || !strings.Contains(out, "teh cat") { t.Fatalf("validator preview status=%d out=%q err=%q", outcome.Status, out, stderr) } + var prepared pk.PreparedRun + if err := json.Unmarshal([]byte(out), &prepared); err != nil || prepared.MessageContentHash == "" || prepared.StructuredOutput == nil || prepared.OutputContract.SchemaPath == "" { + t.Fatalf("preview missing prepared contract or hash: %+v, error=%v, output=%s", prepared, err, out) + } if calls != 0 { t.Fatalf("inspection made %d provider calls", calls) }