package cli import ( "context" "encoding/json" "fmt" "os" "path/filepath" "strings" "sync" "testing" "time" "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd" "go.maximumdirect.net/promptkit" ) type sharedReferenceClient struct { mu sync.Mutex requests []promptkit.GenerateRequest spellResponse string } func (client *sharedReferenceClient) Generate(_ context.Context, request promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) { client.mu.Lock() defer client.mu.Unlock() client.requests = append(client.requests, request) switch { case productionSchemaHasProperty(request, "status"): return &promptkit.GenerateResponse{Content: `{"status":"ok"}`}, nil case productionSchemaHasProperty(request, "spell_casts"): if client.spellResponse != "" { return &promptkit.GenerateResponse{Content: client.spellResponse}, nil } return &promptkit.GenerateResponse{Content: `{"spell_casts":[]}`}, nil default: return nil, fmt.Errorf("unexpected provider request") } } func TestSharedSpellSelectionDrivesValidationAndNormalization(t *testing.T) { party := writeSharedReference(t, "party.yml", validPartyYAML) glossary := writeSharedReference(t, "glossary.json", validSharedGlossary) configPath := sharedReferenceConfig(t, party, glossary, glossary) client := &sharedReferenceClient{spellResponse: productionSpellResponse("Emberfall Aegis")} var stdout, stderr strings.Builder code := RunWithOptions([]string{"run", "dnd-session", "--config", configPath, "--input-file", repositoryPath("examples", "dnd-minimal", "transcript.json"), "--output-dir", filepath.Join(t.TempDir(), "output"), "--cache", "bypass", "--format", "json"}, &stdout, &stderr, productionRunOptions(t, client)) if code != 0 { t.Fatalf("status=%d stdout=%s stderr=%s", code, stdout.String(), stderr.String()) } var report runResult if err := json.Unmarshal([]byte(stdout.String()), &report); err != nil { t.Fatal(err) } result := readProductionJSON[dnd.SpellList](t, filepath.Join(report.OutputDirectory, "lanes", "spells.json")) if len(result.SpellCasts) != 1 || result.SpellCasts[0].Spell != "Aegis of Emberfall" { t.Fatalf("normalized shared spell = %#v", result) } } func TestInvalidSharedReferencesFailBeforeCachedReuse(t *testing.T) { party := writeSharedReference(t, "party.yml", validPartyYAML) glossary := writeSharedReference(t, "glossary.json", validSharedGlossary) configPath := sharedReferenceConfig(t, party, glossary, glossary) configBytes, err := os.ReadFile(configPath) if err != nil { t.Fatal(err) } cacheDir := filepath.Join(t.TempDir(), "cache") configBytes = []byte(strings.Replace(string(configBytes), "version: 6\n", fmt.Sprintf("version: 6\ncache_directory: %q\n", cacheDir), 1)) if err := os.WriteFile(configPath, configBytes, 0o600); err != nil { t.Fatal(err) } client := &sharedReferenceClient{} options := productionRunOptions(t, client) runNumber := 0 options.RunIDGenerator = func(_ time.Time) (string, error) { runNumber++ return fmt.Sprintf("run-1700000000000000000-%032x", runNumber), nil } args := []string{"run", "dnd-session", "--config", configPath, "--input-file", repositoryPath("examples", "dnd-minimal", "transcript.json"), "--output-dir", filepath.Join(t.TempDir(), "output"), "--cache", "auto", "--format", "json"} for i := 0; i < 2; i++ { var stdout, stderr strings.Builder if code := RunWithOptions(args, &stdout, &stderr, options); code != 0 { t.Fatalf("warm run %d status=%d stdout=%s stderr=%s", i, code, stdout.String(), stderr.String()) } if i == 1 && len(client.snapshot()) != 1 { t.Fatalf("expected accepted-result reuse, provider calls=%d", len(client.snapshot())) } } if err := os.WriteFile(party, []byte("{}"), 0o600); err != nil { t.Fatal(err) } var stdout, stderr strings.Builder code := RunWithOptions(args, &stdout, &stderr, options) if code == 0 || len(client.snapshot()) != 1 || !strings.Contains(stderr.String(), "party") { t.Fatalf("invalid cached invocation status=%d calls=%d stderr=%s", code, len(client.snapshot()), stderr.String()) } } func (client *sharedReferenceClient) snapshot() []promptkit.GenerateRequest { client.mu.Lock() defer client.mu.Unlock() return append([]promptkit.GenerateRequest(nil), client.requests...) } func sharedReferenceConfig(t *testing.T, partyPath, glossaryPath, spellPath string) string { t.Helper() return writeProductionContractConfig(t, fmt.Sprintf(`version: 6 pipelines: dnd-session: input: {module: seriatim} references: party: {path: %q} glossary: {path: %q, collections: [setting]} artifacts: spells: extract: module: dnd/spells references: spell_catalog: {path: %q, collections: [custom]} normalize: module: dnd/spells references: spell_catalog: {path: %q, collections: [custom]} `+productionProviderConfiguration, partyPath, glossaryPath, spellPath, spellPath)) } func writeSharedReference(t *testing.T, name, value string) string { t.Helper() path := filepath.Join(t.TempDir(), name) if err := os.WriteFile(path, []byte(value), 0o600); err != nil { t.Fatal(err) } return path } const validPartyYAML = `schema_version: maximumdirect.rpg.party.v1 characters: aria: character: {name: Aria, aliases: [Star]} player: {name: Alice} ` const validSharedGlossary = `{"schema_version":"maximumdirect.glossary.v1","collections":{"setting":{"entries":[{"id":"v","name":"Verdant Tower","category":"place","aliases":["Green Spire"]}]},"custom":{"entries":[{"id":"a","name":"Aegis of Emberfall","category":"spell","aliases":["Emberfall Aegis"]}]},"ignored":{"entries":[{"id":"x","name":"Not In Prompt","category":"term"}]}}}` func TestSharedReferencesReachRunAndPreflight(t *testing.T) { party := writeSharedReference(t, "party.yml", validPartyYAML) glossary := writeSharedReference(t, "glossary.json", validSharedGlossary) configPath := sharedReferenceConfig(t, party, glossary, glossary) client := &sharedReferenceClient{} outputDir := filepath.Join(t.TempDir(), "output") common := []string{"dnd-session", "--config", configPath, "--input-file", repositoryPath("examples", "dnd-minimal", "transcript.json"), "--reference", "party=" + party, "--reference", "glossary=" + glossary, "--reference", "spell_catalog=" + glossary, "--output-dir", outputDir, "--cache", "bypass", "--format", "json"} for _, command := range []string{"preflight", "run"} { var stdout, stderr strings.Builder code := RunWithOptions(append([]string{command}, common...), &stdout, &stderr, productionRunOptions(t, client)) if code != 0 { t.Fatalf("%s status=%d stdout=%s stderr=%s", command, code, stdout.String(), stderr.String()) } if command == "preflight" { var report preflightReport if err := json.Unmarshal([]byte(stdout.String()), &report); err != nil || !report.Ready || len(client.snapshot()) != 1 { t.Fatalf("preflight = %#v, %v, calls=%d", report, err, len(client.snapshot())) } } else { var report runResult if err := json.Unmarshal([]byte(stdout.String()), &report); err != nil { t.Fatal(err) } output := readProductionJSON[dnd.SpellList](t, filepath.Join(report.OutputDirectory, "lanes", "spells.json")) if len(output.SpellCasts) != 0 { t.Fatalf("references synthesized events: %#v", output) } } } requests := client.snapshot() if len(requests) != 2 || !productionSchemaHasProperty(requests[0], "status") { t.Fatalf("expected one preflight probe and one run request, got %d", len(requests)) } var found bool for _, request := range requests { if !productionSchemaHasProperty(request, "spell_casts") { continue } found = true var prompt strings.Builder for _, message := range request.Prompt.Messages { prompt.WriteString(message.Content) } for _, want := range []string{"Star", "Alice", "Verdant Tower", "Green Spire", "Aegis of Emberfall", "Emberfall Aegis"} { if !strings.Contains(prompt.String(), want) { t.Errorf("prompt missing %q", want) } } if strings.Contains(prompt.String(), "Not In Prompt") { t.Fatal("unselected collection reached model") } } if !found { t.Fatal("no domain extraction request observed") } } func TestSharedReferencesFailBeforeProviderInRunAndPreflight(t *testing.T) { for _, test := range []struct{ name, party, glossary, spell, want string }{ {"bad party", "{}", validSharedGlossary, validSharedGlossary, "party"}, {"malformed party", "characters: [", validSharedGlossary, validSharedGlossary, "party"}, {"bad glossary", validPartyYAML, "{}", validSharedGlossary, "glossary"}, {"duplicate IDs", validPartyYAML, `{"schema_version":"maximumdirect.glossary.v1","collections":{"setting":{"entries":[{"id":"x","name":"A","category":"x"},{"id":"x","name":"B","category":"x"}]}}}`, validSharedGlossary, "duplicate"}, {"missing selection", validPartyYAML, `{"schema_version":"maximumdirect.glossary.v1","collections":{}}`, validSharedGlossary, "setting"}, {"spell collision", validPartyYAML, validSharedGlossary, `{"schema_version":"maximumdirect.glossary.v1","collections":{"custom":{"entries":[{"id":"a","name":"Alpha","category":"spell","aliases":["Shared"]},{"id":"b","name":"Beta","category":"spell","aliases":["Shared"]}]}}}`, "maps to spells"}, } { t.Run(test.name, func(t *testing.T) { party := writeSharedReference(t, "party.yml", test.party) glossary := writeSharedReference(t, "glossary.json", test.glossary) spell := writeSharedReference(t, "spell.json", test.spell) configPath := sharedReferenceConfig(t, party, glossary, spell) client := &sharedReferenceClient{} for _, command := range []string{"run", "preflight"} { var stdout, stderr strings.Builder code := RunWithOptions([]string{command, "dnd-session", "--config", configPath, "--input-file", repositoryPath("examples", "dnd-minimal", "transcript.json"), "--output-dir", filepath.Join(t.TempDir(), "output"), "--cache", "bypass", "--format", "json"}, &stdout, &stderr, productionRunOptions(t, client)) if code == 0 || len(client.snapshot()) != 0 || !strings.Contains(strings.ToLower(stdout.String()+stderr.String()), test.want) { t.Fatalf("%s code=%d calls=%d stdout=%s stderr=%s", command, code, len(client.snapshot()), stdout.String(), stderr.String()) } } }) } } func TestOfflineValidationDoesNotReadSharedReferences(t *testing.T) { missing := filepath.Join(t.TempDir(), "missing.json") configPath := sharedReferenceConfig(t, missing, missing, missing) client := &sharedReferenceClient{} var stdout, stderr strings.Builder code := RunWithOptions([]string{"pipeline", "validate", "dnd-session", "--config", configPath}, &stdout, &stderr, productionRunOptions(t, client)) if code != 0 || len(client.snapshot()) != 0 { t.Fatalf("offline validation status=%d stdout=%s stderr=%s", code, stdout.String(), stderr.String()) } }