Prepare shared glossary envelopes and combined input

This commit is contained in:
2026-11-30 00:39:39 +00:00
parent 4e94b2157b
commit f05e711328
22 changed files with 304 additions and 475 deletions

View File

@@ -143,11 +143,11 @@ inputs:
}
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"))
upstream, err := os.ReadFile(filepath.Join(catalog, "schemas", "glossary", "v0.2.0", "schema.json"))
if err != nil {
t.Fatal(err)
}
pinned, err := os.ReadFile(filepath.Join("..", "glossary", "glossary-v1.schema.json"))
pinned, err := os.ReadFile(filepath.Join("..", "domaininput", "resources", "glossary", "v0.2.0", "schema.json"))
if err != nil {
t.Fatal(err)
}

View File

@@ -20,6 +20,7 @@ const (
SourceInputGlossaryCampaign = "narratio.input.glossary.campaign"
SourceInputGlossarySetting = "narratio.input.glossary.setting"
SourceInputGlossarySpells = "narratio.input.glossary.spells"
SourceInputGlossaryCombined = "narratio.input.glossary.combined"
SourceInputSpellCatalog = "narratio.input.spell_catalog"
configuredSourcePrefix = "narratio.artifact."
@@ -216,6 +217,7 @@ var preparedInputSources = map[string]PreparedInputSourceDescriptor{
SourceInputGlossaryCampaign: {SourceID: SourceInputGlossaryCampaign, ManifestKind: "glossary_campaign", Filename: "glossaries/campaign.yml"},
SourceInputGlossarySetting: {SourceID: SourceInputGlossarySetting, ManifestKind: "glossary_setting", Filename: "glossaries/setting.yml"},
SourceInputGlossarySpells: {SourceID: SourceInputGlossarySpells, ManifestKind: "glossary_spells", Filename: "glossaries/spells.yml"},
SourceInputGlossaryCombined: {SourceID: SourceInputGlossaryCombined, ManifestKind: "glossary_combined", Filename: "glossaries/combined.yml"},
}
// GlossaryInputSources returns the four shared glossary descriptors in consumer order.

View File

@@ -224,6 +224,7 @@ func TestDescribePreparedInputSource(t *testing.T) {
{source: SourceInputGlossaryCampaign, manifestKind: "glossary_campaign", filename: "glossaries/campaign.yml"},
{source: SourceInputGlossarySetting, manifestKind: "glossary_setting", filename: "glossaries/setting.yml"},
{source: SourceInputGlossarySpells, manifestKind: "glossary_spells", filename: "glossaries/spells.yml"},
{source: SourceInputGlossaryCombined, manifestKind: "glossary_combined", filename: "glossaries/combined.yml"},
}
for _, tt := range tests {

View File

@@ -13,31 +13,34 @@ func TestResolveGlossariesThroughNativeAcquisition(t *testing.T) {
- path: catalog/catalog.yml
`)
writePipelineFixture(t, dir, "catalog/catalog.yml", `reference_catalog:
settings: {coast: setting.yml}
systems: {magic: spells.yml}
settings: {coast: setting.yml, unused: missing-setting.yml}
systems: {magic: spells.yml, unused: missing-spells.yml}
`)
writePipelineFixture(t, dir, "catalog/setting.yml", "setting: {entries: [{id: coast, name: Coast, category: place}]}\n")
writePipelineFixture(t, dir, "catalog/spells.yml", "spells: {entries: [{id: glow, name: Glow, category: spell}]}\n")
campaign := writePipelineFixture(t, dir, "campaign.yml", `campaign_id: campaign
inputs:
speakers_file: speakers.yml
autocorrect_file: autocorrect.yml
party_file: party.yml
setting: coast
system: magic
glossary_file: vocab.yml
glossary:
entries: [{id: watch, name: Silver Watch, category: organization}]
writePipelineFixture(t, dir, "catalog/setting.yml", "schema_version: maximumdirect.glossary.v1\ncollections:\n setting: {entries: [{id: coast, name: Coast, category: place}]}\n")
writePipelineFixture(t, dir, "catalog/spells.yml", "schema_version: maximumdirect.glossary.v1\ncollections:\n spells: {entries: [{id: glow, name: Glow, category: spell}]}\n")
campaign := writePipelineFixture(t, dir, "campaign.yml", `schema_version: maximumdirect.rpg.campaign.v1
id: campaign
references: {party: party.yml}
setting: coast
system: magic
narratio:
inputs:
speakers_file: speakers.yml
glossary_file: vocab.yml
glossary:
entries: [{id: watch, name: Silver Watch, category: organization}]
`)
writePipelineFixture(t, dir, "party.yml", canonicalPartyFixture)
writePipelineFixture(t, dir, "vocab.yml", `config:
imports:
- path: vocabulary/shared.yml
campaign:
instruction: Keep names.
entries: [{id: watch, name: Old Watch, category: organization, aliases: [Old]}]
schema_version: maximumdirect.glossary.v1
collections:
campaign:
instruction: Keep names.
entries: [{id: watch, name: Old Watch, category: organization, aliases: [Old]}]
`)
writePipelineFixture(t, dir, "vocabulary/shared.yml", "campaign:\n entries: [{id: harbor, name: Harbor, category: place}]\n")
writePipelineFixture(t, dir, "vocabulary/shared.yml", "collections:\n campaign:\n entries: [{id: harbor, name: Harbor, category: place}]\n")
session := writePipelineFixture(t, dir, "session.yml", "session_id: session\ninputs: {audio_dir: audio}\n")
cfg, err := LoadWithSessionOptions(pipeline, campaign, session, SessionLoadOptions{})
if err != nil {
@@ -72,7 +75,7 @@ campaign:
t.Fatalf("nondeterministic %s", k)
}
}
writePipelineFixture(t, dir, "replacement.yml", "campaign: {entries: [{id: watch, name: Alternate, category: organization}, {id: inn, name: Inn, category: place}]}\n")
writePipelineFixture(t, dir, "replacement.yml", "schema_version: maximumdirect.glossary.v1\ncollections:\n campaign: {entries: [{id: watch, name: Alternate, category: organization}, {id: inn, name: Inn, category: place}]}\n")
for _, tc := range []struct{ name, body, want, absent string }{
{"inline override", "glossary: {instruction: Session context.}", "Old Watch", "Silver Watch"},
{"file override", "glossary_file: replacement.yml", "Silver Watch", "Old Watch"},
@@ -92,7 +95,7 @@ campaign:
}
})
}
writePipelineFixture(t, dir, "vocab.yml", "config:\n sequences:\n - destination: [campaign, entries]\n mode: replace\ncampaign:\n instruction: Keep names.\n entries: [{id: watch, name: Old Watch, category: organization}]\n")
writePipelineFixture(t, dir, "vocab.yml", "config:\n sequences:\n - destination: [collections, campaign, entries]\n mode: replace\nschema_version: maximumdirect.glossary.v1\ncollections:\n campaign:\n instruction: Keep names.\n entries: [{id: watch, name: Old Watch, category: organization}]\n")
clearedSession := writePipelineFixture(t, dir, "session.yml", "session_id: session\ninputs:\n audio_dir: audio\n glossary: {entries: []}\n")
cleared, err := LoadWithSessionOptions(pipeline, campaign, clearedSession, SessionLoadOptions{})
if err != nil {

View File

@@ -1,85 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://forge.maximumdirect.net/eric/narratio-reference-catalog/schemas/glossary-v1.schema.json",
"title": "Glossary named collections v1",
"$ref": "#/$defs/document",
"$defs": {
"entry": {
"type": "object",
"required": [
"id",
"name",
"category"
],
"properties": {
"id": {
"type": "string",
"minLength": 1
},
"name": {
"type": "string",
"minLength": 1
},
"category": {
"type": "string",
"minLength": 1
},
"description": {
"type": "string"
},
"aliases": {
"type": ["array", "null"],
"items": {
"type": "string",
"minLength": 1
}
},
"plural": {
"anyOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "null"
}
]
}
},
"additionalProperties": true
},
"partialCollection": {
"type": "object",
"properties": {
"instruction": {
"type": "string"
},
"entries": {
"type": "array",
"items": {
"$ref": "#/$defs/entry"
}
}
},
"additionalProperties": false
},
"collection": {
"allOf": [
{
"$ref": "#/$defs/partialCollection"
},
{
"required": [
"entries"
]
}
]
},
"document": {
"type": "object",
"additionalProperties": {
"$ref": "#/$defs/collection"
}
}
}
}

View File

@@ -1,159 +1,20 @@
// Package glossary owns the shared native glossary representation and validation.
// Package glossary composes and projects shared glossary documents.
package glossary
import (
"bytes"
_ "embed"
"encoding/json"
"fmt"
"sort"
"sync"
"github.com/santhosh-tekuri/jsonschema/v6"
"gitea.maximumdirect.net/eric/narratio/internal/domaininput"
)
// Collection preserves an explicitly supplied empty instruction.
type Collection struct {
Instruction *string `yaml:"instruction,omitempty" json:"instruction,omitempty"`
Entries []Entry `yaml:"entries" json:"entries"`
}
// CatalogRevision identifies the selected synthetic catalog revision.
const CatalogRevision = "02dd53c6ea026347452d497350c40249c949f8ce"
// Entry retains native fields and any additional vocabulary metadata.
type Entry struct {
ID string `yaml:"id" json:"id"`
Name string `yaml:"name" json:"name"`
Category string `yaml:"category" json:"category"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Aliases []string `yaml:"aliases,omitempty" json:"aliases,omitempty"`
Plural *string `yaml:"plural,omitempty" json:"plural,omitempty"`
Extra map[string]any `yaml:",inline" json:"-"`
}
// MarshalJSON retains extension fields when validating or serializing typed entries.
func (entry Entry) MarshalJSON() ([]byte, error) {
type fields Entry
b, err := json.Marshal(fields(entry))
if err != nil {
return nil, err
}
var result map[string]any
if err := json.Unmarshal(b, &result); err != nil {
return nil, err
}
for key, value := range entry.Extra {
if _, known := result[key]; !known {
result[key] = value
}
}
return json.Marshal(result)
}
// CatalogRevision identifies the upstream source of the embedded schema.
const CatalogRevision = "a1a87edafd59a1de545a1c0b4efe5feeb80348e0"
//go:embed glossary-v1.schema.json
var schemaData []byte
const schemaURL = "https://forge.maximumdirect.net/eric/narratio-reference-catalog/schemas/glossary-v1.schema.json"
var compiled struct {
sync.Once
document, partial *jsonschema.Schema
err error
}
type offlineLoader struct{}
func (offlineLoader) Load(url string) (any, error) {
return nil, fmt.Errorf("schema resource unavailable: %s", url)
}
func schemas() (*jsonschema.Schema, *jsonschema.Schema, error) {
compiled.Do(func() {
var doc any
if compiled.err = json.Unmarshal(schemaData, &doc); compiled.err != nil {
return
}
c := jsonschema.NewCompiler()
c.UseLoader(offlineLoader{})
if compiled.err = c.AddResource(schemaURL, doc); compiled.err != nil {
return
}
if compiled.document, compiled.err = c.Compile(schemaURL); compiled.err != nil {
return
}
compiled.partial, compiled.err = c.Compile(schemaURL + "#/$defs/partialCollection")
})
return compiled.document, compiled.partial, compiled.err
}
// ValidatePartial validates a decoded collection contribution without requiring entries.
func ValidatePartial(value any) error {
_, schema, err := schemas()
if err != nil {
return fmt.Errorf("compile glossary schema: %w", err)
}
v, err := jsonValue(value)
if err != nil {
return err
}
if err := schema.Validate(v); err != nil {
return fmt.Errorf("glossary contribution: %w", err)
}
return nil
}
// ValidateDocument validates decoded complete named collections and their IDs.
// ValidateDocument validates a completed shared glossary mapping.
func ValidateDocument(value any) error {
schema, _, err := schemas()
if err != nil {
return fmt.Errorf("compile glossary schema: %w", err)
document, ok := value.(map[string]any)
if !ok {
return fmt.Errorf("glossary document must be a mapping")
}
v, err := jsonValue(value)
if err != nil {
return err
}
if err := schema.Validate(v); err != nil {
return fmt.Errorf("glossary document: %w", err)
}
doc := v.(map[string]any)
names := make([]string, 0, len(doc))
for name := range doc {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
if err := uniqueIDs("collection "+name, doc[name]); err != nil {
return err
}
}
return nil
}
func jsonValue(value any) (any, error) {
data, err := json.Marshal(value)
if err != nil {
return nil, fmt.Errorf("encode glossary data: %w", err)
}
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.UseNumber()
var result any
if err := decoder.Decode(&result); err != nil {
return nil, fmt.Errorf("decode glossary data: %w", err)
}
return result, nil
}
func uniqueIDs(context string, value any) error {
collection := value.(map[string]any)
entries, _ := collection["entries"].([]any)
seen := make(map[string]bool, len(entries))
for _, raw := range entries {
id := raw.(map[string]any)["id"].(string)
if seen[id] {
return fmt.Errorf("%s: duplicate entry id %q", context, id)
}
seen[id] = true
}
return nil
return domaininput.ValidateGlossary(document)
}

View File

@@ -1,68 +1,13 @@
package glossary
import (
"encoding/json"
"strings"
"testing"
import "testing"
"gopkg.in/yaml.v3"
)
func TestValidation(t *testing.T) {
for _, tc := range []struct {
name, input string
partial, valid bool
}{
{"empty", "party: {entries: []}", false, true},
{"null aliases", "party: {entries: [{id: a, name: A, category: person, aliases: null}]}", false, true},
{"invalid aliases", "party: {entries: [{id: a, name: A, category: person, aliases: wrong}]}", false, false},
{"invalid alias item", "party: {entries: [{id: a, name: A, category: person, aliases: [null]}]}", false, false},
{"null description", "party: {entries: [{id: a, name: A, category: person, description: null}]}", false, false},
{"null instruction", "party: {instruction: null, entries: []}", false, false},
{"missing entries", "party: {instruction: hi}", false, false},
{"instruction only", "instruction: hi", true, true},
{"optional and extensions", "party: {entries: [{id: a, name: A, category: person, aliases: [Alias], plural: People, description: text, extra: {rank: 2}}]}", false, true},
{"missing category", "party: {entries: [{id: a, name: A}]}", false, false},
{"duplicate within collection", "party: {entries: [{id: a, name: A, category: person}, {id: a, name: B, category: person}]}", false, false},
{"same id across collections", "party: {entries: [{id: a, name: A, category: person}]}\nother: {entries: [{id: a, name: B, category: person}]}", false, true},
} {
t.Run(tc.name, func(t *testing.T) {
var value any
if err := yaml.Unmarshal([]byte(tc.input), &value); err != nil {
t.Fatal(err)
}
var err error
if tc.partial {
err = ValidatePartial(value)
} else {
err = ValidateDocument(value)
}
if (err == nil) != tc.valid {
t.Fatalf("valid=%v: %v", tc.valid, err)
}
if tc.name == "duplicate within collection" && !strings.Contains(err.Error(), "party") {
t.Fatal(err)
}
})
}
}
func TestTypedCollectionRetainsExtensionsAndEmptyInstruction(t *testing.T) {
var collection Collection
if err := yaml.Unmarshal([]byte("instruction: ''\nentries: [{id: a, name: A, category: person, source_note: test}]\n"), &collection); err != nil {
t.Fatal(err)
}
if collection.Instruction == nil || *collection.Instruction != "" || collection.Entries[0].Extra["source_note"] != "test" {
t.Fatalf("lost data: %+v", collection)
}
b, err := json.Marshal(map[string]Collection{"party": collection})
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(b), `"source_note":"test"`) || !strings.Contains(string(b), `"instruction":""`) {
t.Fatalf("lost data: %s", b)
}
if err := ValidateDocument(map[string]Collection{"party": collection}); err != nil {
t.Fatal(err)
func TestValidateDocumentUsesSharedEnvelope(t *testing.T) {
valid := map[string]any{"schema_version": glossaryMarker, "collections": map[string]any{"party": map[string]any{"entries": []any{}}}}
if err := ValidateDocument(valid); err != nil {
t.Fatal(err)
}
if err := ValidateDocument(map[string]any{"party": map[string]any{"entries": []any{}}}); err == nil {
t.Fatal("wrapperless glossary accepted")
}
}

View File

@@ -5,6 +5,7 @@ import (
"path/filepath"
"sort"
"gitea.maximumdirect.net/eric/narratio/internal/domaininput"
configkit "go.maximumdirect.net/configkit"
"gopkg.in/yaml.v3"
)
@@ -19,97 +20,113 @@ type Sources struct {
// Character contains the roster fields needed for a party vocabulary entry.
type Character struct {
ID string
Name string
Aliases []string
ID, Name string
Aliases []string
}
// Documents holds the four completed standalone named collections.
// Documents holds individual and combined standalone shared envelopes.
type Documents map[string][]byte
// Resolve builds independent, validated vocabulary snapshots using native composition.
const glossaryMarker = "maximumdirect.glossary.v1"
func envelope(collections map[string]any) map[string]any {
return map[string]any{"schema_version": glossaryMarker, "collections": collections}
}
// Resolve builds and validates individual collections and their combined projection.
func Resolve(sources Sources, characters []Character) (Documents, error) {
party := make([]any, 0, len(characters))
ordered := append([]Character(nil), characters...)
sort.Slice(ordered, func(i, j int) bool { return ordered[i].ID < ordered[j].ID })
entries := make([]any, 0, len(ordered))
for _, c := range ordered {
entry := map[string]any{"id": c.ID, "name": c.Name, "category": "person"}
if len(c.Aliases) > 0 {
entry["aliases"] = c.Aliases
aliases := make([]any, len(c.Aliases))
for i, alias := range c.Aliases {
aliases[i] = alias
}
entry["aliases"] = aliases
}
party = append(party, entry)
entries = append(entries, entry)
}
collections := map[string]any{"party": map[string]any{"entries": party}}
selected := map[string]map[string]any{"party": envelope(map[string]any{"party": map[string]any{"entries": entries}})}
for _, item := range []struct {
name, path string
inline map[string]any
}{
{"campaign", sources.CampaignFile, sources.CampaignInline},
{"setting", sources.SettingFile, nil},
{"spells", sources.SpellsFile, nil},
} {
value, err := resolveCollection(item.name, item.path, item.inline)
}{{"campaign", sources.CampaignFile, sources.CampaignInline}, {"setting", sources.SettingFile, nil}, {"spells", sources.SpellsFile, nil}} {
doc, err := resolveCollection(item.name, item.path, item.inline)
if err != nil {
return nil, err
}
collections[item.name] = value
selected[item.name] = doc
}
result := make(Documents, len(collections))
combined := make(map[string]any, len(selected))
result := make(Documents, 5)
for _, name := range []string{"party", "campaign", "setting", "spells"} {
doc := map[string]any{name: collections[name]}
if err := ValidateDocument(doc); err != nil {
doc := selected[name]
if err := domaininput.ValidateGlossary(doc); err != nil {
return nil, fmt.Errorf("%s vocabulary: %w", name, err)
}
combined[name] = doc["collections"].(map[string]any)[name]
data, err := yaml.Marshal(doc)
if err != nil {
return nil, fmt.Errorf("serialize %s vocabulary: %w", name, err)
}
result[name] = data
}
doc := envelope(combined)
if err := domaininput.ValidateGlossary(doc); err != nil {
return nil, fmt.Errorf("combined vocabulary: %w", err)
}
data, err := yaml.Marshal(doc)
if err != nil {
return nil, err
}
result["combined"] = data
return result, nil
}
func resolveCollection(name, path string, inline map[string]any) (any, error) {
if path == "" && inline == nil {
return map[string]any{"entries": []any{}}, nil
}
definition := configkit.Definition[map[string]any]{SequenceIdentities: []configkit.SequenceIdentity{
configkit.SequenceIdentityMatching(configkit.SequenceSelector{configkit.SequenceAnyMappingKey(), configkit.SequenceLiteralKey("entries")}, "id"),
}}
var underlays []configkit.Underlay
if path == "" && inline != nil {
empty := configkit.Mapping("empty vocabulary", map[string]any{name: map[string]any{"entries": []any{}}})
underlays = append(underlays, configkit.Underlay{Inputs: []configkit.Input{{Source: empty}}})
}
if path != "" {
func resolveCollection(name, path string, inline map[string]any) (map[string]any, error) {
selector := configkit.SequenceSelector{configkit.SequenceLiteralKey("collections"), configkit.SequenceAnyMappingKey(), configkit.SequenceLiteralKey("entries")}
definition := configkit.Definition[map[string]any]{SequenceIdentities: []configkit.SequenceIdentity{configkit.SequenceIdentityMatching(selector, "id")}}
var base configkit.Input
if path == "" {
base = configkit.Input{Source: configkit.Mapping("empty vocabulary", envelope(map[string]any{name: map[string]any{"entries": []any{}}}))}
} else {
absolute, err := filepath.Abs(path)
if err != nil {
return nil, fmt.Errorf("resolve %s vocabulary path %q: %w", name, path, err)
return nil, fmt.Errorf("resolve %s vocabulary: %w", name, 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})
base = configkit.Input{Source: configkit.File(absolute), Imports: true, Filesystem: &configkit.FilesystemContext{Root: root}}
}
var doc map[string]any
if inline == nil {
loaded, err := configkit.LoadLayered(base, configkit.LayeredOptions[map[string]any]{Definition: definition})
if err != nil {
return nil, fmt.Errorf("load %s vocabulary %q: %w", name, path, err)
return nil, fmt.Errorf("load %s vocabulary: %w", name, err)
}
if _, ok := loaded.Config[name]; !ok {
return nil, fmt.Errorf("%s vocabulary %q does not define collection %q", name, path, name)
doc = loaded.Config
} else {
main := configkit.Input{Source: configkit.Mapping("inline vocabulary", inline), Destination: configkit.Keys("collections", name)}
loaded, err := configkit.LoadLayered(main, configkit.LayeredOptions[map[string]any]{Definition: definition, Underlays: []configkit.Underlay{{Inputs: []configkit.Input{base}}}})
if err != nil {
return nil, fmt.Errorf("compose %s vocabulary: %w", name, err)
}
if inline == nil {
return loaded.Config[name], nil
}
underlays = []configkit.Underlay{{Inputs: []configkit.Input{file}}}
doc = loaded.Config
}
main := configkit.Input{Source: configkit.Mapping("inline vocabulary", inline), Destination: configkit.Keys(name)}
loaded, err := configkit.LoadLayered(main, configkit.LayeredOptions[map[string]any]{Definition: definition, Underlays: underlays})
if err != nil {
return nil, fmt.Errorf("compose %s vocabulary: %w", name, err)
if err := domaininput.ValidateGlossary(doc); err != nil {
return nil, fmt.Errorf("%s vocabulary: %w", name, err)
}
value, ok := loaded.Config[name]
collections := doc["collections"].(map[string]any)
collection, ok := collections[name]
if !ok {
return nil, fmt.Errorf("%s vocabulary is missing", name)
return nil, fmt.Errorf("%s vocabulary does not define collection %q", name, name)
}
return value, nil
projection := make(map[string]any, len(doc))
for key, value := range doc {
projection[key] = value
}
projection["collections"] = map[string]any{name: collection}
return projection, nil
}

View File

@@ -9,98 +9,81 @@ import (
"gopkg.in/yaml.v3"
)
func TestResolveComposesAndProjectsVocabulary(t *testing.T) {
func TestResolveComposesSharedVocabulary(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "campaign.yml")
data := `campaign:
instruction: Use established names.
entries:
- {id: watch, name: Old Watch, category: organization, aliases: [Old]}
- {id: harbor, name: North Harbor, category: place, source_note: synthetic}
campaign := filepath.Join(dir, "campaign.yml")
data := `schema_version: maximumdirect.glossary.v1
custom_root: synthetic
collections:
campaign:
provenance: {id: synthetic, title: Synthetic}
instruction: inert extension
entries:
- {id: watch, name: Old Watch, category: organization, aliases: [Old]}
- {id: harbor, name: North Harbor, category: place, source_note: synthetic}
`
if err := os.WriteFile(path, []byte(data), 0600); err != nil {
if err := os.WriteFile(campaign, []byte(data), 0o600); err != nil {
t.Fatal(err)
}
inline := map[string]any{"entries": []any{map[string]any{"id": "watch", "name": "Silver Watch", "category": "organization"}}}
docs, err := Resolve(Sources{CampaignFile: path, CampaignInline: inline}, []Character{{ID: "z", Name: "Zed"}, {ID: "a", Name: "Ada", Aliases: []string{"A"}}})
docs, err := Resolve(Sources{CampaignFile: campaign, CampaignInline: inline}, []Character{{ID: "z", Name: "Zed"}, {ID: "a", Name: "Ada", Aliases: []string{"A"}}})
if err != nil {
t.Fatal(err)
}
var campaign map[string]map[string]any
if err := yaml.Unmarshal(docs["campaign"], &campaign); err != nil {
t.Fatal(err)
if len(docs) != 5 {
t.Fatalf("documents: %v", docs)
}
entries := campaign["campaign"]["entries"].([]any)
first := entries[0].(map[string]any)
if first["name"] != "Silver Watch" || first["aliases"] != nil || !strings.Contains(string(docs["campaign"]), "source_note: synthetic") {
t.Fatalf("campaign: %s", docs["campaign"])
for _, name := range []string{"party", "campaign", "setting", "spells", "combined"} {
var value map[string]any
if err := yaml.Unmarshal(docs[name], &value); err != nil {
t.Fatal(err)
}
if err := ValidateDocument(value); err != nil {
t.Fatalf("%s: %v", name, err)
}
collections := value["collections"].(map[string]any)
if name == "combined" {
if len(collections) != 4 {
t.Fatalf("combined collections: %v", collections)
}
} else if _, ok := collections[name]; !ok || len(collections) != 1 {
t.Fatalf("%s collections: %v", name, collections)
}
}
if !strings.Contains(string(docs["campaign"]), "instruction: Use established names.") {
t.Fatalf("instruction: %s", docs["campaign"])
if strings.Contains(string(docs["campaign"]), "Old Watch") || !strings.Contains(string(docs["campaign"]), "Silver Watch") || !strings.Contains(string(docs["campaign"]), "source_note: synthetic") || !strings.Contains(string(docs["campaign"]), "custom_root: synthetic") || !strings.Contains(string(docs["combined"]), "provenance:") {
t.Fatalf("composition lost data: %s\n%s", docs["campaign"], docs["combined"])
}
if strings.Index(string(docs["party"]), "id: a") > strings.Index(string(docs["party"]), "id: z") {
t.Fatalf("party order: %s", docs["party"])
}
for _, name := range []string{"setting", "spells"} {
if !strings.Contains(string(docs[name]), "entries: []") {
t.Fatalf("empty %s: %s", name, docs[name])
}
}
if err := os.WriteFile(path, []byte("config:\n sequences:\n - destination: [campaign, entries]\n mode: replace\n"+data), 0600); err != nil {
t.Fatal(err)
}
docs, err = Resolve(Sources{CampaignFile: path, CampaignInline: map[string]any{"entries": []any{}}}, nil)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(docs["campaign"]), "entries: []") || !strings.Contains(string(docs["campaign"]), "instruction:") {
t.Fatalf("replacement: %s", docs["campaign"])
t.Fatalf("party ordering: %s", docs["party"])
}
}
func TestResolveHandlesInheritancePartialAndFailures(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "setting.yml")
if err := os.WriteFile(path, []byte("common:\n entries: [{id: tower, name: Tower, category: place}]\nsetting:\n extends: common\n instruction: ''\n"), 0600); err != nil {
t.Fatal(err)
}
docs, err := Resolve(Sources{SettingFile: path, CampaignInline: map[string]any{"instruction": "Only instruction"}}, nil)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(docs["setting"]), "Tower") || !strings.Contains(string(docs["setting"]), "instruction: \"\"") {
t.Fatalf("inherited: %s", docs["setting"])
}
if !strings.Contains(string(docs["campaign"]), "entries: []") {
t.Fatalf("partial: %s", docs["campaign"])
}
if _, err := Resolve(Sources{SpellsFile: path}, nil); err == nil || !strings.Contains(err.Error(), "spells") {
t.Fatalf("missing selection: %v", err)
}
if _, err := Resolve(Sources{CampaignFile: filepath.Join(dir, "missing.yml")}, nil); err == nil {
t.Fatal("missing file accepted")
}
}
func TestResolveImportsSiblingVocabularyFragments(t *testing.T) {
func TestResolveSelectedImportsAndFailures(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",
"settings/coast.yml": "config:\n imports: [{path: ../fragments/places.yml}]\nschema_version: maximumdirect.glossary.v1\ncollections:\n setting: {entries: [{id: coast, name: Coast, category: place}]}\n",
"fragments/places.yml": "collections:\n setting: {entries: [{id: harbor, name: Harbor, category: place}]}\n",
} {
path := filepath.Join(dir, name)
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0600); err != nil {
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
}
docs, err := Resolve(Sources{SettingFile: filepath.Join(dir, "settings", "coast.yml")}, nil)
path := filepath.Join(dir, "settings", "coast.yml")
docs, err := Resolve(Sources{SettingFile: path, CampaignInline: map[string]any{"provenance": map[string]any{"id": "synthetic"}}}, 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"])
if !strings.Contains(string(docs["setting"]), "Harbor") || !strings.Contains(string(docs["setting"]), "Coast") || !strings.Contains(string(docs["campaign"]), "entries: []") {
t.Fatalf("documents: %s / %s", docs["setting"], docs["campaign"])
}
if _, err := Resolve(Sources{SpellsFile: path}, nil); err == nil {
t.Fatal("wrong collection accepted")
}
if _, err := Resolve(Sources{CampaignFile: filepath.Join(dir, "missing.yml")}, nil); err == nil {
t.Fatal("missing selected file accepted")
}
}

View File

@@ -22,17 +22,18 @@ type ErrorRecord struct {
// InputRecord captures one resolved input and optional checksum.
type InputRecord struct {
Kind string `json:"kind"`
Path string `json:"path"`
Checksum string `json:"checksum,omitempty"`
Size int64 `json:"size,omitempty"`
Source string `json:"source,omitempty"`
S3Bucket string `json:"s3_bucket,omitempty"`
S3Key string `json:"s3_key,omitempty"`
S3Size int64 `json:"s3_size,omitempty"`
S3ETag string `json:"s3_etag,omitempty"`
SpoolPath string `json:"spool_path,omitempty"`
CachePath string `json:"cache_path,omitempty"`
Kind string `json:"kind"`
Path string `json:"path"`
Checksum string `json:"checksum,omitempty"`
Size int64 `json:"size,omitempty"`
Source string `json:"source,omitempty"`
S3Bucket string `json:"s3_bucket,omitempty"`
S3Key string `json:"s3_key,omitempty"`
S3Size int64 `json:"s3_size,omitempty"`
S3ETag string `json:"s3_etag,omitempty"`
SpoolPath string `json:"spool_path,omitempty"`
CachePath string `json:"cache_path,omitempty"`
Dependencies []string `json:"dependencies,omitempty"`
}
// ArtifactRecord captures one produced artifact and optional remote metadata.

View File

@@ -168,6 +168,7 @@ func (prepareStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
{"campaign", artifactpolicy.SourceInputGlossaryCampaign},
{"setting", artifactpolicy.SourceInputGlossarySetting},
{"spells", artifactpolicy.SourceInputGlossarySpells},
{"combined", artifactpolicy.SourceInputGlossaryCombined},
} {
descriptor, ok := artifactpolicy.DescribePreparedInputSource(item.source)
if !ok {
@@ -182,7 +183,13 @@ func (prepareStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
if err != nil {
return nil, fmt.Errorf("prepare: materialize %s: %w", descriptor.ManifestKind, err)
}
inputs = append(inputs, manifest.InputRecord{Kind: descriptor.ManifestKind, Path: dst, Checksum: checksum, Size: int64(len(data)), Source: "derived_from_configuration"})
record := manifest.InputRecord{Kind: descriptor.ManifestKind, Path: dst, Checksum: checksum, Size: int64(len(data)), Source: "derived_from_configuration"}
if item.source == artifactpolicy.SourceInputGlossaryCombined {
for _, dependency := range artifactpolicy.GlossaryInputSources() {
record.Dependencies = append(record.Dependencies, dependency.SourceID)
}
}
inputs = append(inputs, record)
}
partyInputs, err := materializePreparedPartyInputs(env.ArtifactStore, env.Config, paths.InputsDir)
if err != nil {

View File

@@ -8,6 +8,7 @@ import (
"os"
"path"
"path/filepath"
"slices"
"strings"
"gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy"
@@ -24,6 +25,7 @@ type prepareExpectedInput struct {
destinationName string
checksum string
source string
dependencies []string
configSnapshot bool
s3Bucket string
s3Key string
@@ -53,7 +55,7 @@ func (prepareStage) ValidateResume(ctx context.Context, env *Env, m *manifest.Ma
return NonResumable(prepareResumeChangedReason), nil
}
paths := sessionPathsForEnv(env, m.SessionID)
for _, source := range []string{artifactpolicy.SourceInputGlossaryParty, artifactpolicy.SourceInputGlossaryCampaign, artifactpolicy.SourceInputGlossarySetting, artifactpolicy.SourceInputGlossarySpells} {
for _, source := range []string{artifactpolicy.SourceInputGlossaryParty, artifactpolicy.SourceInputGlossaryCampaign, artifactpolicy.SourceInputGlossarySetting, artifactpolicy.SourceInputGlossarySpells, artifactpolicy.SourceInputGlossaryCombined} {
if _, err := artifacts.ResolvePreparedInput(paths, m, source); err != nil {
return NonResumable(prepareResumeChangedReason), nil
}
@@ -128,12 +130,19 @@ func currentPrepareSourceInputs(ctx context.Context, env *Env, m *manifest.Manif
for _, item := range []struct{ name, source string }{
{"party", artifactpolicy.SourceInputGlossaryParty}, {"campaign", artifactpolicy.SourceInputGlossaryCampaign},
{"setting", artifactpolicy.SourceInputGlossarySetting}, {"spells", artifactpolicy.SourceInputGlossarySpells},
{"combined", artifactpolicy.SourceInputGlossaryCombined},
} {
descriptor, ok := artifactpolicy.DescribePreparedInputSource(item.source)
if !ok {
return nil, fmt.Errorf("glossary descriptor %q unavailable", item.source)
}
expected = append(expected, prepareExpectedInput{kind: descriptor.ManifestKind, checksum: checksumPrepareBytes(documents[item.name])})
entry := prepareExpectedInput{kind: descriptor.ManifestKind, checksum: checksumPrepareBytes(documents[item.name])}
if item.source == artifactpolicy.SourceInputGlossaryCombined {
for _, dependency := range artifactpolicy.GlossaryInputSources() {
entry.dependencies = append(entry.dependencies, dependency.SourceID)
}
}
expected = append(expected, entry)
}
partyInputs, err := currentPreparePartySourceInputs(env)
if err != nil {
@@ -225,7 +234,7 @@ func prepareSourceInputsMatch(paths artifacts.SessionPaths, expected []prepareEx
managedKinds := map[string]struct{}{
"campaign_config": {}, "session_config": {},
"audio": {}, "speakers": {}, "autocorrect": {}, "glossary": {},
"glossary_party": {}, "glossary_campaign": {}, "glossary_setting": {}, "glossary_spells": {},
"glossary_party": {}, "glossary_campaign": {}, "glossary_setting": {}, "glossary_spells": {}, "glossary_combined": {},
"players": {}, "party": {},
}
expectedCounts := make(map[string]int, len(managedKinds))
@@ -277,6 +286,9 @@ func prepareInputRecordMatches(paths artifacts.SessionPaths, expected prepareExp
if expected.source != "" && record.Source != expected.source {
return false
}
if !slices.Equal(expected.dependencies, record.Dependencies) {
return false
}
if expected.destinationName != "" && filepath.Base(record.Path) != expected.destinationName {
return false
}

View File

@@ -5,9 +5,11 @@ import (
"fmt"
"os"
"path/filepath"
"reflect"
"testing"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"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/manifest"
@@ -174,6 +176,79 @@ func TestPrepareAutocorrectionEvidenceAndReuse(t *testing.T) {
assertPrepareResume(t, env, m, true)
}
func TestCombinedGlossarySharesVerifiedReferenceAcrossRoles(t *testing.T) {
env, m, _ := prepareResumeLocalFixture(t)
record := findManifestInput(t, m.Inputs, "glossary_combined")
var want []string
for _, descriptor := range artifactpolicy.GlossaryInputSources() {
want = append(want, descriptor.SourceID)
}
if !reflect.DeepEqual(record.Dependencies, want) {
t.Fatalf("dependencies = %v, want %v", record.Dependencies, want)
}
for i := range m.Inputs {
if m.Inputs[i].Kind == "glossary_combined" {
m.Inputs[i].Dependencies = nil
assertPrepareResume(t, env, m, false)
m.Inputs[i].Dependencies = append([]string(nil), want...)
}
}
manifestPath := filepath.Join(t.TempDir(), "manifest.json")
store := &manifest.LocalStore{}
if err := store.Save(context.Background(), manifestPath, m); err != nil {
t.Fatal(err)
}
loaded, err := store.Load(context.Background(), manifestPath)
if err != nil {
t.Fatal(err)
}
if got := findManifestInput(t, loaded.Inputs, "glossary_combined").Dependencies; !reflect.DeepEqual(got, want) {
t.Fatalf("persisted dependencies = %v", got)
}
paths := sessionPathsForEnv(env, m.SessionID)
configured := &config.NotariusConfig{References: map[string]string{"glossary": artifactpolicy.SourceInputGlossaryCombined, "spell_catalog": artifactpolicy.SourceInputGlossaryCombined}}
references, err := resolveExtractReferences(paths, m, configured, m.SessionID)
if err != nil {
t.Fatal(err)
}
bindings, err := materializeExtractReferenceSnapshots(paths, references)
if err != nil {
t.Fatal(err)
}
if len(bindings) != 2 || bindings[0].Path != bindings[1].Path {
t.Fatalf("bindings = %+v", bindings)
}
if err := verifyExtractReferenceSnapshots(paths, references); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(bindings[0].Path, []byte("corrupt"), 0o644); err != nil {
t.Fatal(err)
}
if err := verifyExtractReferenceSnapshots(paths, references); err == nil {
t.Fatal("corrupt snapshot accepted")
}
if err := os.Remove(bindings[0].Path); err != nil {
t.Fatal(err)
}
if err := verifyExtractReferenceSnapshots(paths, references); err == nil {
t.Fatal("missing snapshot accepted")
}
}
func TestCombinedGlossaryChangesWhenAnyCollectionChanges(t *testing.T) {
env, m, _ := prepareResumeLocalFixture(t)
before := findManifestInput(t, m.Inputs, "glossary_combined").Checksum
env.Config.Session.Inputs.Glossary = map[string]any{"entries": []any{map[string]any{"id": "harbor", "name": "Harbor", "category": "place"}}}
assertPrepareResume(t, env, m, false)
if _, err := (prepareStage{}).Run(context.Background(), env, m); err != nil {
t.Fatal(err)
}
after := findManifestInput(t, m.Inputs, "glossary_combined").Checksum
if before == after {
t.Fatal("combined glossary did not change")
}
}
func TestPrepareSnapshotComparisonIgnoresRelocatedSourcePaths(t *testing.T) {
first := []byte("schema_version: maximumdirect.rpg.campaign.v1\nid: campaign\nreferences: {party: /old/party.yml}\nnarratio:\n inputs: {speakers_file: /old/speakers.yml, glossary_file: /old/glossary.yml}\n")
second := []byte("schema_version: maximumdirect.rpg.campaign.v1\nid: campaign\nreferences: {party: /new/party.yml}\nnarratio:\n inputs: {speakers_file: /new/speakers.yml, glossary_file: /new/glossary.yml}\n")
@@ -309,19 +384,19 @@ func TestPrepareResumeTracksEffectiveGlossaryVocabulary(t *testing.T) {
writeFile(t, filepath.Join(root, "audio", "one.flac"), "audio")
source := filepath.Join(root, "vocabulary.yml")
fragment := filepath.Join(root, "fragment.yml")
writeFile(t, source, "config:\n imports:\n - path: fragment.yml\ncampaign: {instruction: Names}\n")
writeFile(t, fragment, "campaign: {entries: [{id: watch, name: Watch, category: organization}]}\n")
writeFile(t, source, "config:\n imports:\n - path: fragment.yml\nschema_version: maximumdirect.glossary.v1\ncollections:\n campaign: {instruction: Names}\n")
writeFile(t, fragment, "collections:\n campaign: {entries: [{id: watch, name: Watch, category: organization}]}\n")
env.Config.Session.Inputs.GlossaryFile = &source
if _, err := (prepareStage{}).Run(context.Background(), env, m); err != nil {
t.Fatal(err)
}
assertPrepareResume(t, env, m, true)
relocated := filepath.Join(root, "relocated.yml")
writeFile(t, relocated, "campaign:\n instruction: Names\n entries:\n - {name: Watch, id: watch, category: organization}\n")
writeFile(t, relocated, "schema_version: maximumdirect.glossary.v1\ncollections:\n campaign:\n instruction: Names\n entries:\n - {name: Watch, id: watch, category: organization}\n")
env.Config.Session.Inputs.GlossaryFile = &relocated
assertPrepareResume(t, env, m, true)
env.Config.Session.Inputs.GlossaryFile = &source
writeFile(t, fragment, "campaign: {entries: [{id: watch, name: Changed, category: organization}]}\n")
writeFile(t, fragment, "collections:\n campaign: {entries: [{id: watch, name: Changed, category: organization}]}\n")
assertPrepareResume(t, env, m, false)
}
@@ -342,8 +417,8 @@ func TestPrepareResumeChecksSelectedCatalogContent(t *testing.T) {
root := filepath.Dir(env.Config.SessionPath)
writeFile(t, filepath.Join(root, "audio", "one.flac"), "audio")
one, two := filepath.Join(root, "one.yml"), filepath.Join(root, "two.yml")
writeFile(t, one, "setting: {entries: [{id: place, name: One, category: place}]}\n")
writeFile(t, two, "setting: {entries: [{id: place, name: Two, category: place}]}\n")
writeFile(t, one, "schema_version: maximumdirect.glossary.v1\ncollections:\n setting: {entries: [{id: place, name: One, category: place}]}\n")
writeFile(t, two, "schema_version: maximumdirect.glossary.v1\ncollections:\n setting: {entries: [{id: place, name: Two, category: place}]}\n")
env.Config.Pipeline.ReferenceCatalog.Settings = map[string]string{"one": one, "two": two}
env.Config.Session.Inputs.Setting = new("one")
if _, err := (prepareStage{}).Run(context.Background(), env, m); err != nil {

View File

@@ -45,6 +45,7 @@ func TestPrepareStageExplicitAudioFiles(t *testing.T) {
filepath.Join(paths.InputsDir, "glossaries", "campaign.yml"),
filepath.Join(paths.InputsDir, "glossaries", "setting.yml"),
filepath.Join(paths.InputsDir, "glossaries", "spells.yml"),
filepath.Join(paths.InputsDir, "glossaries", "combined.yml"),
filepath.Join(paths.InputsDir, "players.yml"),
filepath.Join(paths.InputsDir, "party.yml"),
filepath.Join(paths.AudioDir, "alice.flac"),
@@ -55,8 +56,8 @@ func TestPrepareStageExplicitAudioFiles(t *testing.T) {
}
}
if len(m.Inputs) != 13 {
t.Fatalf("manifest inputs len = %d, want 13", len(m.Inputs))
if len(m.Inputs) != 14 {
t.Fatalf("manifest inputs len = %d, want 14", len(m.Inputs))
}
for _, in := range m.Inputs {
if in.Checksum == "" {

View File

@@ -14,9 +14,12 @@ func TestPublishPreparedInputsRetainVerifiedBytesAndRejectTampering(t *testing.T
if err != nil {
t.Fatal(err)
}
if len(files) != 7 {
if len(files) != 8 {
t.Fatalf("prepared archive files = %d", len(files))
}
if _, err := os.Stat(filepath.Join(runRoot, "prepare", "inputs", "glossaries", "combined.yml")); err != nil {
t.Fatal(err)
}
for _, file := range files {
path := filepath.Join(runRoot, filepath.FromSlash(file.RelativePath))
checksum, err := env.ArtifactStore.Checksum(path)

View File

@@ -35,6 +35,9 @@ func collectPublishPreparedInputs(store artifacts.Store, paths artifacts.Session
filenames[descriptor.ManifestKind] = descriptor.Filename
glossaries[descriptor.ManifestKind] = descriptor
}
combined, _ := artifactpolicy.DescribePreparedInputSource(artifactpolicy.SourceInputGlossaryCombined)
filenames[combined.ManifestKind] = combined.Filename
glossaries[combined.ManifestKind] = combined
var result []publishUploadFile
for _, record := range records {
name, ok := filenames[record.Kind]

View File

@@ -154,6 +154,7 @@ func prepareStableInputSemantics(cfg *config.Config) []prepareStableInputSelecti
{Kind: "autocorrect", Present: true},
{Kind: "glossary_party", Present: true}, {Kind: "glossary_campaign", Present: true},
{Kind: "glossary_setting", Present: true}, {Kind: "glossary_spells", Present: true},
{Kind: "glossary_combined", Present: true},
prepareStableInput("party", stable.PartyFile, ""),
}
}

View File

@@ -426,7 +426,7 @@ func setupTranscribeEnv(t *testing.T, audioFiles []string) (*Env, *manifest.Mani
writeFile(t, campaignPath, "campaign_id: sample-campaign\ninputs:\n speakers_file: ./speakers.yml\n autocorrect_file: ./autocorrect.yml\n glossary_file: ./glossary.yml\n party_file: ./party.yml\n")
writeFile(t, filepath.Join(cfgDir, "speakers.yml"), "alice: alice.flac\n")
writeFile(t, filepath.Join(cfgDir, "autocorrect.yml"), "[]\n")
writeFile(t, filepath.Join(cfgDir, "glossary.yml"), "campaign: {entries: []}\n")
writeFile(t, filepath.Join(cfgDir, "glossary.yml"), "schema_version: maximumdirect.glossary.v1\ncollections:\n campaign: {entries: []}\n")
partyBytes := []byte("schema_version: maximumdirect.rpg.party.v1\ncharacters:\n arannis:\n player: {name: Eric}\n character:\n name: Arannis\n classes: [{name: wizard}]\n")
writeFile(t, filepath.Join(cfgDir, "party.yml"), string(partyBytes))
party, err := config.ParseParty(partyBytes)