package cli import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "sync/atomic" "testing" "time" "go.maximumdirect.net/commandkit" ) func TestPreflightAndRunWithMaintainedPipeline(t *testing.T) { t.Setenv("OPENROUTER_API_KEY", "fixture-key") var gets, smoke, runCalls atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet { gets.Add(1) fmt.Fprint(w, `{"data":{"label":"fixture","is_free_tier":false,"usage":0}}`) return } var body map[string]any if err := json.NewDecoder(r.Body).Decode(&body); err != nil { t.Errorf("request: %v", err) w.WriteHeader(400) return } if temperature, ok := body["temperature"].(float64); !ok || temperature != 0 { t.Errorf("explicit zero temperature missing: %v", body["temperature"]) } encoded, _ := json.Marshal(body["response_format"]) schema := string(encoded) content := "" switch { case strings.Contains(schema, `"status"`): smoke.Add(1) content = `{"status":"ok"}` case strings.Contains(schema, `"classification"`): runCalls.Add(1) content = `{"classification":"non_combat","explanation":"No combat."}` case strings.Contains(schema, `"start_unit_id"`): runCalls.Add(1) content = `{"scenes":[{"start_unit_id":1,"end_unit_id":2}]}` case strings.Contains(schema, `"kind"`): runCalls.Add(1) content = `{"kind":"narrative","title":"Camp","summary":"The party rests."}` default: t.Errorf("unexpected request schema: %s", schema) w.WriteHeader(400) return } _ = json.NewEncoder(w).Encode(map[string]any{"choices": []any{map[string]any{"message": map[string]any{"role": "assistant", "content": content}, "finish_reason": "stop"}}}) })) defer server.Close() root := t.TempDir() input := filepath.Join(root, "transcript.json") party, glossary := filepath.Join(root, "party.txt"), filepath.Join(root, "glossary.txt") for name, data := range map[string][]byte{input: readRepositoryFile(t, "examples", "dnd-minimal", "transcript.json"), party: []byte("The party travels together."), glossary: []byte("Campaign glossary.")} { if err := os.WriteFile(name, data, 0o600); err != nil { t.Fatal(err) } } output := filepath.Join(root, "output") app, err := NewApplication("test", Options{RunIDGenerator: func(_ time.Time) (string, error) { return "run", nil }}) if err != nil { t.Fatal(err) } common := []string{"dnd-session", "--config", repositoryPath("examples", "dnd-complete", "config.yml"), "--input-file", input, "--set", `/pipelines/dnd-session/steps=[{"id":"describe-session","artifacts":{"scene-descriptions":{"extract":{"module":"dnd/scene-descriptions","validators":[{"module":"extract/dnd/scene-descriptions/combat_semantics"}]},"merge":{"module":"appendorder"},"normalize":{"module":"dnd/scene-descriptions"}}}}]`, "--set", `/pipelines/dnd-session/output/options/evidence_context/lanes=["scene-descriptions"]`, "--reference", "party=" + party, "--reference", "glossary=" + glossary, "--output-dir", output, "--cache", "bypass", "--llm-endpoint", server.URL + "/v1", "--llm-temperature=0", "--llm-transient-retries=0", "--format", "json"} var out, stderr bytes.Buffer args := append([]string{"preflight"}, common...) outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr}) var report preflightReport if err := json.Unmarshal(out.Bytes(), &report); err != nil || outcome.Status != 0 || !report.Ready { t.Fatalf("preflight outcome=%+v report=%+v err=%v stdout=%s stderr=%s", outcome, report, err, out.String(), stderr.String()) } if gets.Load() != 2 || smoke.Load() != 1 || runCalls.Load() != 0 { t.Fatalf("preflight calls: gets=%d smoke=%d run=%d", gets.Load(), smoke.Load(), runCalls.Load()) } if entries, err := os.ReadDir(output); err != nil || len(entries) != 0 { t.Fatalf("preflight output=%v err=%v", entries, err) } var validator bool for _, check := range report.Checks { for _, binding := range check.Scope.Bindings { if strings.Contains(binding.Validator, "combat_semantics") { validator = true } } } if !validator { t.Fatalf("semantic validator missing from report: %+v", report.Checks) } out.Reset() stderr.Reset() outcome = app.Execute(context.Background(), append([]string{"run"}, common...), commandkit.Streams{Out: &out, Err: &stderr}) if outcome.Status != 0 { t.Fatalf("run outcome=%+v stdout=%s stderr=%s", outcome, out.String(), stderr.String()) } if runCalls.Load() < 3 { t.Fatalf("run calls=%d", runCalls.Load()) } if err := os.WriteFile(input, []byte(`{"segments":`), 0o600); err != nil { t.Fatal(err) } before := runCalls.Load() out.Reset() stderr.Reset() outcome = app.Execute(context.Background(), append([]string{"run"}, common...), commandkit.Streams{Out: &out, Err: &stderr}) if outcome.Status == 0 || runCalls.Load() != before { t.Fatalf("invalid input outcome=%+v calls=%d stdout=%s stderr=%s", outcome, runCalls.Load(), out.String(), stderr.String()) } }