From f05d2e593e03ba3d86a8251ade54f14ae0059af7 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Sun, 29 Nov 2026 18:18:25 +0000 Subject: [PATCH] Verify shared references in run and preflight --- docs/roadmap/implementation.md | 4 + internal/cli/preflight_assembled_test.go | 4 +- internal/cli/production_contract_test.go | 4 +- .../cli/shared_reference_workflow_test.go | 239 ++++++++++++++++++ 4 files changed, 248 insertions(+), 3 deletions(-) create mode 100644 internal/cli/shared_reference_workflow_test.go diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 7f908bc8..0e7eeda3 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -383,6 +383,10 @@ validation simply because no chunks execute or accepted artifacts are cached. ## Stage 9 — Verify Assembled Run And Preflight Behavior +**Status:** Complete. Focused assembled checks pass; the broader CLI suite still +has failures in tests using the old maintained example files, whose migration is +assigned below. The preflight and framework pipeline suites pass. + **Goal:** Prove the public workflow through real internal collaborators and fake provider boundaries. diff --git a/internal/cli/preflight_assembled_test.go b/internal/cli/preflight_assembled_test.go index a595e079..1743dbc2 100644 --- a/internal/cli/preflight_assembled_test.go +++ b/internal/cli/preflight_assembled_test.go @@ -61,8 +61,8 @@ func TestPreflightAndRunWithMaintainedPipeline(t *testing.T) { 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.")} { + party, glossary := filepath.Join(root, "party.yml"), filepath.Join(root, "glossary.json") + for name, data := range map[string][]byte{input: readRepositoryFile(t, "examples", "dnd-minimal", "transcript.json"), party: []byte(validPartyYAML), glossary: []byte(validSharedGlossary)} { if err := os.WriteFile(name, data, 0o600); err != nil { t.Fatal(err) } diff --git a/internal/cli/production_contract_test.go b/internal/cli/production_contract_test.go index 46377998..2753fb9e 100644 --- a/internal/cli/production_contract_test.go +++ b/internal/cli/production_contract_test.go @@ -622,6 +622,8 @@ func maintainedExampleFiles(t *testing.T) []maintainedExample { func productionSpellCatalogContractConfig(t *testing.T) string { t.Helper() + partyPath := writeSharedReference(t, "party.yml", validPartyYAML) + glossaryPath := writeSharedReference(t, "glossary.json", validSharedGlossary) catalogPath := filepath.Join(t.TempDir(), "spell-catalog.json") if err := os.WriteFile(catalogPath, []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{"spells":{"entries":[{"id":"aegis","name":"Aegis of Emberfall","category":"spell","aliases":["Emberfall Aegis"]}]}}}`), 0o600); err != nil { t.Fatal(err) @@ -648,7 +650,7 @@ pipelines: references: spell_catalog: path: %q -`, repositoryPath("examples", "dnd-complete", "party.txt"), repositoryPath("examples", "dnd-complete", "glossary.txt"), catalogPath, catalogPath) +`, partyPath, glossaryPath, catalogPath, catalogPath) } func writeProductionSpellCatalogContractConfig(t *testing.T) string { diff --git a/internal/cli/shared_reference_workflow_test.go b/internal/cli/shared_reference_workflow_test.go new file mode 100644 index 00000000..bed3e6af --- /dev/null +++ b/internal/cli/shared_reference_workflow_test.go @@ -0,0 +1,239 @@ +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()) + } +}