Verify catalog and Audita compatibility offline
This commit is contained in:
253
internal/app/compatibility_test.go
Normal file
253
internal/app/compatibility_test.go
Normal file
@@ -0,0 +1,253 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/glossary"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/stage"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
func externalPath(t *testing.T, name string) string {
|
||||
t.Helper()
|
||||
path := os.Getenv(name)
|
||||
if path == "" {
|
||||
t.Skipf("%s is unset", name)
|
||||
}
|
||||
if !filepath.IsAbs(path) {
|
||||
t.Fatalf("%s must be an absolute path", name)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func copyCatalog(t *testing.T, source, dest string) {
|
||||
t.Helper()
|
||||
err := filepath.WalkDir(source, func(path string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
if entry.IsDir() && entry.Name() == ".git" {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
rel, err := filepath.Rel(source, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
target := filepath.Join(dest, rel)
|
||||
if entry.IsDir() {
|
||||
return os.MkdirAll(target, 0755)
|
||||
}
|
||||
if !entry.Type().IsRegular() {
|
||||
return nil
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(target, data, 0644)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReferenceCatalogCompatibility(t *testing.T) {
|
||||
catalog := externalPath(t, "NARRATIO_TEST_REFERENCE_CATALOG_DIR")
|
||||
dir := t.TempDir()
|
||||
copyCatalog(t, catalog, filepath.Join(dir, "catalog"))
|
||||
workspace := filepath.Join(dir, "workspace")
|
||||
write := func(name, body string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(dir, name)
|
||||
mustWriteTestFile(t, path, body)
|
||||
return path
|
||||
}
|
||||
pipeline := write("pipeline.yml", fmt.Sprintf("config:\n imports:\n - path: catalog/catalog.yml\nworkspace: {root: %q}\nwhisperx: {transcribe_url: 'https://example.invalid/transcribe'}\n", workspace))
|
||||
campaign := write("campaign.yml", `campaign_id: sample-campaign
|
||||
inputs:
|
||||
speakers_file: speakers.yml
|
||||
autocorrect_file: autocorrect.yml
|
||||
party_file: party.yml
|
||||
glossary_file: campaign-glossary.yml
|
||||
setting: lantern_coast_sample
|
||||
system: sample_magic
|
||||
glossary:
|
||||
entries: [{id: watch, name: Silver Watch, category: organization}]
|
||||
`)
|
||||
write("campaign-glossary.yml", "campaign:\n instruction: Preserve campaign names.\n entries: [{id: watch, name: Old Watch, category: organization}, {id: inn, name: Lantern Inn, category: place}]\n")
|
||||
write("speakers.yml", "alice: alice.flac\n")
|
||||
write("autocorrect.yml", "[]\n")
|
||||
write("party.yml", "schema_version: narratio.party.v1\ncharacters:\n alice:\n player: {name: Player}\n character: {name: Alice, classes: [{name: wizard}]}\n")
|
||||
write("audio/alice.flac", "synthetic audio")
|
||||
session := write("session.yml", "session_id: 2026-05-03\ninputs: {audio_dir: audio}\n")
|
||||
cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
docs, err := config.ResolveGlossaries(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for role, wanted := range map[string][]string{"campaign": {"Silver Watch", "Lantern Inn", "Preserve campaign names"}, "setting": {"Lantern Coast", "Harbor Crossing"}, "spells": {"Lantern Glow", "Tide Step"}} {
|
||||
for _, value := range wanted {
|
||||
if !bytes.Contains(docs[role], []byte(value)) {
|
||||
t.Fatalf("%s missing %q: %s", role, value, docs[role])
|
||||
}
|
||||
}
|
||||
}
|
||||
if bytes.Contains(docs["campaign"], []byte("Old Watch")) {
|
||||
t.Fatalf("inline entry did not replace file entry: %s", docs["campaign"])
|
||||
}
|
||||
prepare, err := stage.Select("prepare")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := executeStages(context.Background(), cfg, []stage.Stage{prepare}, RunOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths := artifacts.NewLocalStore(workspace).SessionPathsFor("sample-campaign", "2026-05-03")
|
||||
for _, descriptor := range artifactpolicy.GlossaryInputSources() {
|
||||
data, err := os.ReadFile(filepath.Join(paths.InputsDir, descriptor.Filename))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var value map[string]any
|
||||
if err := yaml.Unmarshal(data, &value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := glossary.ValidateDocument(value); err != nil {
|
||||
t.Fatalf("%s: %v", descriptor.SourceID, err)
|
||||
}
|
||||
role := strings.TrimPrefix(descriptor.SourceID, "narratio.input.glossary.")
|
||||
if !bytes.Equal(data, docs[role]) {
|
||||
t.Fatalf("prepared %s differs from resolved vocabulary", role)
|
||||
}
|
||||
}
|
||||
revision, err := exec.Command("git", "-C", catalog, "rev-parse", "HEAD").Output()
|
||||
if err == nil && strings.TrimSpace(string(revision)) == glossary.CatalogRevision {
|
||||
upstream, err := os.ReadFile(filepath.Join(catalog, "schemas", "glossary-v1.schema.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pinned, err := os.ReadFile(filepath.Join("..", "glossary", "glossary-v1.schema.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(upstream, pinned) {
|
||||
t.Fatal("pinned glossary schema differs from catalog revision")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditaBinaryCompatibility(t *testing.T) {
|
||||
binary := externalPath(t, "NARRATIO_TEST_AUDITA_BINARY")
|
||||
var negative atomic.Bool
|
||||
var calls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer r.Body.Close()
|
||||
var request struct {
|
||||
Model string `json:"model"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Error(err)
|
||||
http.Error(w, "bad request", 400)
|
||||
return
|
||||
}
|
||||
calls.Add(1)
|
||||
content := `{"status":"ok"}`
|
||||
if negative.Load() && request.Model == "review-model" {
|
||||
content = `{"bad":true}`
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"model": request.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()
|
||||
cfg := testConfig(t)
|
||||
mustWriteTestFile(t, *cfg.Session.Inputs.GlossaryFile, "campaign:\n instruction: Preserve campaign names.\n entries: [{id: watch, name: Silver Watch, category: organization}]\n")
|
||||
settingPath := filepath.Join(filepath.Dir(cfg.CampaignPath), "setting.yml")
|
||||
spellsPath := filepath.Join(filepath.Dir(cfg.CampaignPath), "spells.yml")
|
||||
mustWriteTestFile(t, settingPath, "setting: {instruction: Preserve place names., entries: [{id: harbor, name: Harbor, category: place}]}\n")
|
||||
mustWriteTestFile(t, spellsPath, "spells: {instruction: Preserve spell names., entries: [{id: glow, name: Glow, category: spell}]}\n")
|
||||
cfg.Pipeline.ReferenceCatalog = config.ReferenceCatalogConfig{Settings: map[string]string{"coast": settingPath}, Systems: map[string]string{"magic": spellsPath}}
|
||||
cfg.Session.Inputs.Setting = new("coast")
|
||||
cfg.Session.Inputs.System = new("magic")
|
||||
prepare, err := stage.Select("prepare")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := executeStages(context.Background(), cfg, []stage.Stage{prepare}, RunOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
|
||||
m, err := (&manifest.LocalStore{}).Load(context.Background(), paths.ManifestPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
configPath := filepath.Join(dir, "config.yml")
|
||||
mustWriteTestFile(t, configPath, "version: 3\nllm: {proposal_profile: proposal, validation_profile: review, correction_repair_attempts: 0}\npipeline: {stages: [{module: grammar}]}\nreporting: {enabled: false}\n")
|
||||
mustWriteTestFile(t, filepath.Join(dir, "prompts.yml"), fmt.Sprintf("backends:\n - {id: local, endpoint: %q}\nprofiles:\n - {id: proposal, backend: local, model: proposal-model}\n - {id: review, backend: local, model: review-model}\n", server.URL+"/v1"))
|
||||
req, _, err := stage.BuildPolishRequest(paths, m, "", filepath.Join(dir, "out.json"), filepath.Join(dir, "reports"), filepath.Join(dir, "debug"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args := []string{"config", "show", "--config", configPath, "--format", "json"}
|
||||
for _, file := range req.GlossaryFiles {
|
||||
args = append(args, "--glossary-file", file)
|
||||
}
|
||||
output, err := exec.Command(binary, args...).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("inspection: %v: %s", err, output)
|
||||
}
|
||||
var inspected struct {
|
||||
Collections map[string]struct {
|
||||
Instruction *string `json:"instruction"`
|
||||
Entries []any `json:"entries"`
|
||||
} `json:"glossary_collections"`
|
||||
}
|
||||
if err := json.Unmarshal(output, &inspected); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"party", "campaign", "setting", "spells"} {
|
||||
if _, ok := inspected.Collections[name]; !ok {
|
||||
t.Fatalf("missing %s: %s", name, output)
|
||||
}
|
||||
}
|
||||
for name, instruction := range map[string]string{"campaign": "Preserve campaign names.", "setting": "Preserve place names.", "spells": "Preserve spell names."} {
|
||||
collection := inspected.Collections[name]
|
||||
if collection.Instruction == nil || *collection.Instruction != instruction || len(collection.Entries) != 1 {
|
||||
t.Fatalf("%s: %+v", name, collection)
|
||||
}
|
||||
}
|
||||
runner, err := audita.NewSubprocessRunner(audita.SubprocessRunnerConfig{Binary: binary, ConfigPath: configPath, Timeout: 30 * time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := runner.Preflight(context.Background(), req)
|
||||
if err != nil || result.ExitCode != 0 || calls.Load() != 2 {
|
||||
t.Fatalf("preflight: %+v %v calls=%d", result, err, calls.Load())
|
||||
}
|
||||
negative.Store(true)
|
||||
calls.Store(0)
|
||||
result, err = runner.Preflight(context.Background(), req)
|
||||
if err == nil || result.ExitCode != 1 || calls.Load() != 2 {
|
||||
t.Fatalf("negative preflight: %+v %v calls=%d", result, err, calls.Load())
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package glossary
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
@@ -81,7 +82,14 @@ func resolveCollection(name, path string, inline map[string]any) (any, error) {
|
||||
underlays = append(underlays, configkit.Underlay{Inputs: []configkit.Input{{Source: empty}}})
|
||||
}
|
||||
if path != "" {
|
||||
file := configkit.Input{Source: configkit.File(path), Imports: true}
|
||||
absolute, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve %s vocabulary path %q: %w", name, path, err)
|
||||
}
|
||||
// Vocabulary files may import sibling fragments relative to their own
|
||||
// locations; let ConfigKit resolve those imports in the host filesystem.
|
||||
root := filepath.VolumeName(absolute) + string(filepath.Separator)
|
||||
file := configkit.Input{Source: configkit.File(absolute), Imports: true, Filesystem: &configkit.FilesystemContext{Root: root}}
|
||||
loaded, err := configkit.LoadLayered(file, configkit.LayeredOptions[map[string]any]{Definition: definition})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load %s vocabulary %q: %w", name, path, err)
|
||||
|
||||
@@ -81,3 +81,26 @@ func TestResolveHandlesInheritancePartialAndFailures(t *testing.T) {
|
||||
t.Fatal("missing file accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveImportsSiblingVocabularyFragments(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for name, content := range map[string]string{
|
||||
"settings/coast.yml": "config:\n imports: [{path: ../fragments/places.yml}]\nsetting: {entries: [{id: coast, name: Coast, category: place}]}\n",
|
||||
"fragments/places.yml": "setting: {entries: [{id: harbor, name: Harbor, category: place}]}\n",
|
||||
} {
|
||||
path := filepath.Join(dir, name)
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(content), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
docs, err := Resolve(Sources{SettingFile: filepath.Join(dir, "settings", "coast.yml")}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(docs["setting"]), "Harbor") || !strings.Contains(string(docs["setting"]), "Coast") {
|
||||
t.Fatalf("setting: %s", docs["setting"])
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user