Prepare resolved documents and autocorrection rules

This commit is contained in:
2026-11-30 00:31:36 +00:00
parent 5c4ca20b11
commit 4e94b2157b
22 changed files with 197 additions and 335 deletions

View File

@@ -53,24 +53,19 @@ type remoteLocksCheck struct {
func inspectStableInputs(cfg *config.Config) []stableInputCheck {
items := []struct {
name string
in config.ResolvedInputFile
optional bool
derived bool
name string
in config.ResolvedInputFile
derived string
}{
{name: "speakers", in: cfg.StableInputs.SpeakersFile},
{name: "autocorrect", in: cfg.StableInputs.AutocorrectFile},
{name: "players", derived: true},
{name: "autocorrect", derived: "derived from configuration"},
{name: "players", derived: "derived from canonical party"},
{name: "party", in: cfg.StableInputs.PartyFile},
{name: "spell_catalog", in: cfg.StableInputs.SpellCatalogFile, optional: true},
}
out := make([]stableInputCheck, 0, len(items))
for _, item := range items {
if item.derived {
out = append(out, stableInputCheck{Name: item.name, Path: "derived from canonical party"})
continue
}
if item.optional && strings.TrimSpace(item.in.Path) == "" {
if item.derived != "" {
out = append(out, stableInputCheck{Name: item.name, Path: item.derived})
continue
}
path, err := resolveHelperConfigRelativePath(item.in)

View File

@@ -216,11 +216,6 @@ 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"},
SourceInputSpellCatalog: {
SourceID: SourceInputSpellCatalog,
ManifestKind: "spell_catalog",
Filename: "spell_catalog.json",
},
}
// GlossaryInputSources returns the four shared glossary descriptors in consumer order.

View File

@@ -171,7 +171,6 @@ func TestDescribeScriptoriumInputSource(t *testing.T) {
{name: "prepared party input", source: "narratio.input.party", wantKind: SourceKindStableInput},
{name: "prepared glossary input", source: SourceInputGlossaryCampaign, wantKind: SourceKindStableInput},
{name: "retired glossary input", source: SourceInputGlossary, wantErr: ErrUnsupportedScriptoriumInputSource, wantErrLike: "replace"},
{name: "prepared spell catalog input", source: "narratio.input.spell_catalog", wantKind: SourceKindStableInput},
{name: "configured", source: "narratio.artifact.session_recap", wantKind: SourceKindConfiguredArtifact, wantKey: "session_recap"},
{name: "previous", source: "narratio.previous_session.artifact.session_recap", wantKind: SourceKindPreviousArtifact, wantKey: "session_recap", wantPrev: true},
{name: "invalid previous", source: "narratio.previous_session.artifact.", wantErr: ErrInvalidPreviousSessionSource},
@@ -225,7 +224,6 @@ 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: SourceInputSpellCatalog, manifestKind: "spell_catalog", filename: "spell_catalog.json"},
}
for _, tt := range tests {
@@ -243,6 +241,12 @@ func TestDescribePreparedInputSource(t *testing.T) {
if _, ok := DescribePreparedInputSource("narratio.input.unknown"); ok {
t.Fatal("DescribePreparedInputSource(unknown) ok = true")
}
if _, ok := DescribePreparedInputSource(SourceInputSpellCatalog); ok {
t.Fatal("retired spell catalog source was accepted")
}
if _, err := ClassifySource(SourceInputSpellCatalog); err == nil {
t.Fatal("retired spell catalog source was classified")
}
}
func TestValidateInputConfiguredReference(t *testing.T) {

View File

@@ -13,10 +13,10 @@ import (
)
func TestResolvePreparedInputReturnsVerifiedIdentity(t *testing.T) {
paths, m, canonicalPath, checksum := preparedInputFixture(t, artifactpolicy.SourceInputSpellCatalog, []byte("{\"spells\":[]}\n"))
m.Inputs[0].Path = filepath.ToSlash(filepath.Join("inputs", "spell_catalog.json"))
paths, m, canonicalPath, checksum := preparedInputFixture(t, artifactpolicy.SourceInputParty, []byte("{\"spells\":[]}\n"))
m.Inputs[0].Path = filepath.ToSlash(filepath.Join("inputs", "party.yml"))
identity, err := ResolvePreparedInput(paths, m, artifactpolicy.SourceInputSpellCatalog)
identity, err := ResolvePreparedInput(paths, m, artifactpolicy.SourceInputParty)
if err != nil {
t.Fatalf("ResolvePreparedInput() error = %v", err)
}
@@ -24,10 +24,10 @@ func TestResolvePreparedInputReturnsVerifiedIdentity(t *testing.T) {
if err != nil {
t.Fatalf("filepath.Abs() error = %v", err)
}
if identity.SourceID != artifactpolicy.SourceInputSpellCatalog ||
identity.ManifestKind != "spell_catalog" ||
if identity.SourceID != artifactpolicy.SourceInputParty ||
identity.ManifestKind != "party" ||
identity.Path != wantAbsolute ||
identity.RelativePath != "inputs/spell_catalog.json" ||
identity.RelativePath != "inputs/party.yml" ||
identity.Checksum != checksum ||
identity.Size != int64(len("{\"spells\":[]}\n")) {
t.Fatalf("ResolvePreparedInput() = %#v", identity)
@@ -105,9 +105,9 @@ func TestResolvePreparedInputRejectsInvalidManifestEvidence(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, m, canonicalPath, _ := preparedInputFixture(t, artifactpolicy.SourceInputSpellCatalog, []byte("{\"spells\":[]}\n"))
paths, m, canonicalPath, _ := preparedInputFixture(t, artifactpolicy.SourceInputParty, []byte("{\"spells\":[]}\n"))
tt.mutate(t, paths, m, canonicalPath)
_, err := ResolvePreparedInput(paths, m, artifactpolicy.SourceInputSpellCatalog)
_, err := ResolvePreparedInput(paths, m, artifactpolicy.SourceInputParty)
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("ResolvePreparedInput() error = %v, want containing %q", err, tt.wantErr)
}
@@ -155,9 +155,9 @@ func TestResolvePreparedInputRejectsInvalidCanonicalFile(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, m, canonicalPath, _ := preparedInputFixture(t, artifactpolicy.SourceInputSpellCatalog, []byte("{\"spells\":[]}\n"))
paths, m, canonicalPath, _ := preparedInputFixture(t, artifactpolicy.SourceInputParty, []byte("{\"spells\":[]}\n"))
tt.mutate(t, canonicalPath)
_, err := ResolvePreparedInput(paths, m, artifactpolicy.SourceInputSpellCatalog)
_, err := ResolvePreparedInput(paths, m, artifactpolicy.SourceInputParty)
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("ResolvePreparedInput() error = %v, want containing %q", err, tt.wantErr)
}

View File

@@ -138,10 +138,10 @@ type CampaignInputsConfig struct {
System *string `yaml:"system" json:"system"`
Glossary map[string]any `yaml:"glossary" json:"glossary"`
SpeakersFile string `yaml:"speakers_file" json:"speakers_file"`
AutocorrectFile string `yaml:"autocorrect_file" json:"autocorrect_file"`
AutocorrectFile string `yaml:"-" json:"-"`
GlossaryFile *string `yaml:"glossary_file" json:"glossary_file"`
PartyFile string `yaml:"party_file" json:"party_file"`
SpellCatalogFile string `yaml:"spell_catalog_file" json:"spell_catalog_file"`
SpellCatalogFile string `yaml:"-" json:"-"`
Autocorrect []AutocorrectionRule `yaml:"autocorrect" json:"autocorrect"`
}

View File

@@ -42,6 +42,20 @@ func sessionFieldExplicit(cfg *SessionConfig, name string) bool {
return result != nil && result.Metadata().IsExplicit(configkit.Keys("inputs", name))
}
// AutocorrectionSource identifies the authored source of the selected rules.
func AutocorrectionSource(cfg *Config) string {
if cfg == nil || cfg.Session == nil {
return "derived_from_configuration"
}
if sessionFieldExplicit(cfg.Session, "autocorrect") || (cfg.Session.ConfigKitResult() == nil && cfg.Session.Inputs.Autocorrect != nil) {
return "session_config"
}
if cfg.Campaign != nil && cfg.Campaign.Inputs.Autocorrect != nil {
return "campaign_config"
}
return "derived_from_configuration"
}
func documentResource(resolution *configkit.Resolution, path configkit.Path, value *string, invocationDir string, sources map[string]string) {
if info, ok := resolution.EntryInfo(path); ok && len(info.Origin.Locations) == 1 {
if source, ok := resolution.Source(info.Origin.Locations[0].SourceID); ok {

View File

@@ -69,13 +69,9 @@ func RenderSessionDocument(cfg *Config, sessionID string) ([]byte, error) {
if result != nil {
metadata = result.Metadata()
}
// Materialized sessions retain authored overrides and receiving-campaign defaults.
inputValue := func(name, value string) *string {
if result != nil {
if !metadata.IsExplicit(configkit.Keys("inputs", name)) {
return nil
}
} else if value == "" {
// Materialized sessions carry the resolved values needed independently of the campaign.
inputValue := func(value string) *string {
if value == "" {
return nil
}
return &value
@@ -87,8 +83,8 @@ func RenderSessionDocument(cfg *Config, sessionID string) ([]byte, error) {
SpeakersFile *string `yaml:"speakers_file,omitempty"`
Extra map[string]any `yaml:",inline"`
}{doc.Inputs.AudioDir, doc.Inputs.AudioFiles, doc.Inputs.AudioS3,
inputValue("speakers_file", doc.Inputs.SpeakersFile),
glossaryFields(result != nil, metadata, doc.Inputs.Setting, doc.Inputs.System, doc.Inputs.GlossaryFile, doc.Inputs.Glossary, true)}
inputValue(doc.Inputs.SpeakersFile),
glossaryFields(result != nil, metadata, doc.Inputs.Setting, doc.Inputs.System, doc.Inputs.GlossaryFile, doc.Inputs.Glossary, false)}
autocorrectPath := configkit.Keys("inputs", "autocorrect")
if result != nil && metadata.IsExplicit(autocorrectPath) {
if info, ok := metadata.Lookup(autocorrectPath); ok && info.Null {
@@ -96,7 +92,7 @@ func RenderSessionDocument(cfg *Config, sessionID string) ([]byte, error) {
} else {
inputs.Extra["autocorrect"] = doc.Inputs.Autocorrect
}
} else if result == nil && doc.Inputs.Autocorrect != nil {
} else if doc.Inputs.Autocorrect != nil {
inputs.Extra["autocorrect"] = doc.Inputs.Autocorrect
}
value := struct {
@@ -110,6 +106,16 @@ func RenderSessionDocument(cfg *Config, sessionID string) ([]byte, error) {
return yaml.Marshal(value)
}
// RenderAutocorrection produces the Seriatim rule-list envelope.
func RenderAutocorrection(rules []AutocorrectionRule) ([]byte, error) {
if rules == nil {
rules = []AutocorrectionRule{}
}
return yaml.Marshal(struct {
Autocorrect []AutocorrectionRule `yaml:"autocorrect"`
}{Autocorrect: rules})
}
func glossaryFields(hasResult bool, metadata configkit.Metadata, setting, system, file *string, glossary map[string]any, authoredOnly bool) map[string]any {
result := map[string]any{}
for _, field := range []struct {

View File

@@ -304,10 +304,8 @@ func deriveStableInputs(campaignCfg *CampaignConfig, sessionCfg *SessionConfig,
campaignOnly bool
}{
{"speakers_file", sessionCfg.Inputs.SpeakersFile, &stable.SpeakersFile, false},
{"autocorrect_file", sessionCfg.Inputs.AutocorrectFile, &stable.AutocorrectFile, false},
{"glossary_file", OptionalString(sessionCfg.Inputs.GlossaryFile), &stable.GlossaryFile, false},
{"party_file", campaignCfg.Inputs.PartyFile, &stable.PartyFile, true},
{"spell_catalog_file", sessionCfg.Inputs.SpellCatalogFile, &stable.SpellCatalogFile, false},
} {
reference := ResolvedInputFile{Path: field.value, ConfigPath: sessionPath, Source: "session_config"}
metadata := sessionCfg.resolution

View File

@@ -66,6 +66,13 @@ narratio:
if len(again.Inputs.Autocorrect) != tc.rules || (again.Inputs.Glossary != nil) != tc.glossary {
t.Fatalf("snapshot: %s", output)
}
standalone, err := LoadSessionBytesWithOptions("snapshot.yml", output, SessionLoadOptions{})
if err != nil {
t.Fatalf("standalone snapshot: %v\n%s", err, output)
}
if len(standalone.Inputs.Autocorrect) != tc.rules || (standalone.Inputs.Glossary != nil) != tc.glossary {
t.Fatalf("standalone snapshot: %s", output)
}
})
}
output, err := RenderCampaignDocument(&Config{Campaign: campaign})

View File

@@ -37,7 +37,7 @@ func Validate(cfg *Config) error {
if _, err := DeriveArtifactCatalog(cfg.Pipeline, cfg.Party); err != nil {
return err
}
if err := validateCrossConfig(cfg.Pipeline, cfg.Session, cfg.StableInputs); err != nil {
if err := validateCrossConfig(cfg.Pipeline, cfg.Session); err != nil {
return fmt.Errorf("pipeline/session config invalid: %w", err)
}

View File

@@ -6,7 +6,6 @@ import (
configkit "go.maximumdirect.net/configkit"
"gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy"
"gitea.maximumdirect.net/eric/narratio/internal/pathsafe"
)
@@ -118,19 +117,10 @@ func validateSessionIdentifier(fieldName, value string, required bool) error {
return nil
}
func validateCrossConfig(pipeline *PipelineConfig, session *SessionConfig, stableInputs ResolvedStableInputs) error {
func validateCrossConfig(pipeline *PipelineConfig, session *SessionConfig) error {
if pipeline == nil || session == nil {
return nil
}
if pipeline.Notarius != nil && pipeline.Notarius.Enabled {
for _, selector := range sortedStringKeys(pipeline.Notarius.References) {
source := pipeline.Notarius.References[selector]
if source == artifactpolicy.SourceInputSpellCatalog && strings.TrimSpace(stableInputs.SpellCatalogFile.Path) == "" {
return fmt.Errorf("pipeline.notarius.references.%s requires campaign.inputs.spell_catalog_file or session.inputs.spell_catalog_file", selector)
}
}
}
audioS3Enabled := session.Inputs.AudioS3 != nil
publishUploadEnabled := publishUploadConfiguredForS3(pipeline)
if audioS3Enabled && !strings.EqualFold(strings.TrimSpace(pipeline.Storage.Backend), StorageBackendS3) {

View File

@@ -1149,12 +1149,12 @@ func TestAnalyzeResolvesPreparedStableInputSources(t *testing.T) {
playersPath := filepath.Join(paths.InputsDir, "players.yml")
partyPath := filepath.Join(paths.InputsDir, "party.yml")
glossaryPath := filepath.Join(paths.InputsDir, "glossaries", "campaign.yml")
spellCatalogPath := filepath.Join(paths.InputsDir, "spell_catalog.json")
spellCatalogPath := filepath.Join(paths.InputsDir, "glossaries", "spells.yml")
recordPreparedAnalyzeInput(t, m, artifactpolicy.SourceInputPlayers, playersPath, "- Eric\n")
m.Inputs[len(m.Inputs)-1].Source = "derived_from_party"
recordPreparedAnalyzeInput(t, m, artifactpolicy.SourceInputParty, partyPath, "- Arannis\n")
recordPreparedAnalyzeInput(t, m, artifactpolicy.SourceInputGlossaryCampaign, glossaryPath, "campaign: {entries: [{id: ten_towns, name: Ten Towns}]}\n")
recordPreparedAnalyzeInput(t, m, artifactpolicy.SourceInputSpellCatalog, spellCatalogPath, "{\"spells\":[]}\n")
recordPreparedAnalyzeInput(t, m, artifactpolicy.SourceInputGlossarySpells, spellCatalogPath, "{\"spells\":[]}\n")
artifact := env.Config.ArtifactCatalog.Artifacts["session_recap"]
artifact.Inputs["players"] = config.ScriptoriumInputConfig{
@@ -1170,7 +1170,7 @@ func TestAnalyzeResolvesPreparedStableInputSources(t *testing.T) {
Required: true,
}
artifact.Inputs["spells"] = config.ScriptoriumInputConfig{
Source: "narratio.input.spell_catalog",
Source: "narratio.input.glossary.spells",
Required: true,
}
env.Config.ArtifactCatalog.Artifacts["session_recap"] = artifact

View File

@@ -172,7 +172,7 @@ func TestExtractStageResolvesAllPreparedReferencesInSelectorOrder(t *testing.T)
contents string
}{
{selector: " players ", sourceID: artifactpolicy.SourceInputPlayers, contents: "players-secret\n"},
{selector: "spells.spell_catalog", sourceID: artifactpolicy.SourceInputSpellCatalog, contents: "spell-secret\n"},
{selector: "spells.spell_catalog", sourceID: artifactpolicy.SourceInputGlossarySpells, contents: "spell-secret\n"},
{selector: "glossary", sourceID: artifactpolicy.SourceInputGlossaryCampaign, contents: "glossary-secret\n"},
{selector: "party", sourceID: artifactpolicy.SourceInputParty, contents: "party-secret\n"},
}

View File

@@ -57,35 +57,17 @@ func (prepareStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
sessionDir := filepath.Dir(sessionSrc)
speakersInput := stableInputSource(env.Config.StableInputs.SpeakersFile, env.Config.Session.Inputs.SpeakersFile, sessionSrc)
autocorrectInput := stableInputSource(env.Config.StableInputs.AutocorrectFile, env.Config.Session.Inputs.AutocorrectFile, sessionSrc)
spellCatalogInput := stableInputSource(env.Config.StableInputs.SpellCatalogFile, env.Config.Session.Inputs.SpellCatalogFile, sessionSrc)
speakersSrc, err := resolveConfigRelativePath(speakersInput)
if err != nil {
return nil, fmt.Errorf("prepare: speakers path: %w", err)
}
autocorrectSrc, err := resolveConfigRelativePath(autocorrectInput)
if err != nil {
return nil, fmt.Errorf("prepare: autocorrect path: %w", err)
}
spellCatalogConfigured := strings.TrimSpace(spellCatalogInput.Path) != ""
spellCatalogSrc := ""
if spellCatalogConfigured {
spellCatalogSrc, err = resolveConfigRelativePath(spellCatalogInput)
if err != nil {
return nil, fmt.Errorf("prepare: spell catalog path: %w", err)
}
if err := requireRegularReadableFile(spellCatalogSrc, "spell catalog"); err != nil {
return nil, fmt.Errorf("prepare: %w", err)
}
}
for _, required := range []struct {
path string
name string
}{
{path: speakersSrc, name: "speakers.yml"},
{path: autocorrectSrc, name: "autocorrect.yml"},
} {
if err := requireFile(required.path, required.name); err != nil {
return nil, fmt.Errorf("prepare: %w", err)
@@ -162,22 +144,6 @@ func (prepareStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
}
preparedConfigFiles := []preparedConfigFile{
{kind: "speakers", src: speakersSrc, dst: filepath.Join(paths.InputsDir, "speakers.yml"), source: speakersInput.Source},
{kind: "autocorrect", src: autocorrectSrc, dst: filepath.Join(paths.InputsDir, "autocorrect.yml"), source: autocorrectInput.Source},
}
spellDescriptor, ok := artifactpolicy.DescribePreparedInputSource(artifactpolicy.SourceInputSpellCatalog)
if !ok {
return nil, fmt.Errorf("prepare: spell catalog prepared-input descriptor is unavailable")
}
spellCatalogDst := filepath.Join(paths.InputsDir, spellDescriptor.Filename)
if spellCatalogConfigured {
preparedConfigFiles = append(preparedConfigFiles, preparedConfigFile{
kind: spellDescriptor.ManifestKind,
src: spellCatalogSrc,
dst: spellCatalogDst,
source: spellCatalogInput.Source,
})
} else if err := fileops.RemoveFileUnderRoot(paths.Root, spellCatalogDst); err != nil {
return nil, fmt.Errorf("prepare: remove obsolete spell catalog: %w", err)
}
for _, cfgFile := range preparedConfigFiles {
@@ -187,6 +153,16 @@ func (prepareStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
}
registerConfigInput(cfgFile.kind, cfgFile.dst, checksum, cfgFile.source)
}
autocorrectBytes, err := config.RenderAutocorrection(env.Config.Session.Inputs.Autocorrect)
if err != nil {
return nil, fmt.Errorf("prepare: render autocorrection: %w", err)
}
autocorrectDst := filepath.Join(paths.InputsDir, "autocorrect.yml")
autocorrectChecksum, err := writeBytesIfChanged(env.ArtifactStore, autocorrectDst, autocorrectBytes)
if err != nil {
return nil, fmt.Errorf("prepare: materialize autocorrection: %w", err)
}
inputs = append(inputs, manifest.InputRecord{Kind: "autocorrect", Path: autocorrectDst, Checksum: autocorrectChecksum, Size: int64(len(autocorrectBytes)), Source: config.AutocorrectionSource(env.Config)})
for _, item := range []struct{ name, source string }{
{"party", artifactpolicy.SourceInputGlossaryParty},
{"campaign", artifactpolicy.SourceInputGlossaryCampaign},

View File

@@ -15,8 +15,8 @@ func TestPrepareMaterializesImportedDocumentsWithoutAuthoringFiles(t *testing.T)
dir := filepath.Dir(env.Config.CampaignPath)
campaignFragment := filepath.Join(dir, "fragments", "campaign.yml")
sessionFragment := filepath.Join(dir, "fragments", "session.yml")
writeFile(t, env.Config.CampaignPath, "config:\n imports:\n - path: fragments/campaign.yml\ncampaign_id: sample-campaign\n")
writeFile(t, campaignFragment, "inputs:\n speakers_file: ../speakers.yml\n autocorrect_file: ../autocorrect.yml\n glossary_file: ../glossary.yml\n party_file: ../party.yml\n")
writeFile(t, env.Config.CampaignPath, "config:\n imports:\n - path: fragments/campaign.yml\nschema_version: maximumdirect.rpg.campaign.v1\nid: sample-campaign\n")
writeFile(t, campaignFragment, "references: {party: ../party.yml}\nnarratio:\n inputs:\n speakers_file: ../speakers.yml\n autocorrect: [{target: Lantern, match: [Lan turn]}]\n")
writeFile(t, env.Config.SessionPath, "config:\n imports:\n - path: fragments/session.yml\nsession_id: 2026-05-03\n")
writeFile(t, sessionFragment, "title: Imported title\ninputs:\n audio_dir: ../audio\n")
writeFile(t, filepath.Join(dir, "audio", "one.flac"), "audio")
@@ -61,10 +61,17 @@ func TestPrepareMaterializesImportedDocumentsWithoutAuthoringFiles(t *testing.T)
if err != nil || preparedCampaign.Inputs.SpeakersFile != filepath.Join(dir, "speakers.yml") {
t.Fatalf("prepared campaign = %#v, %v", preparedCampaign, err)
}
preparedSession, err := config.LoadSessionWithOptions(filepath.Join(paths.InputsDir, "session.yml"), config.SessionLoadOptions{Campaign: preparedCampaign, CampaignPath: filepath.Join(paths.InputsDir, "campaign.yml")})
preparedSession, err := config.LoadSessionWithOptions(filepath.Join(paths.InputsDir, "session.yml"), config.SessionLoadOptions{})
if err != nil || preparedSession.Title != "Imported title" || preparedSession.Inputs.SpeakersFile != filepath.Join(dir, "speakers.yml") {
t.Fatalf("prepared session = %#v, %v", preparedSession, err)
}
if len(preparedSession.Inputs.Autocorrect) != 1 || preparedSession.Inputs.Autocorrect[0].Target != "Lantern" {
t.Fatalf("prepared autocorrection = %+v", preparedSession.Inputs.Autocorrect)
}
rulesRecord := findManifestInput(t, m.Inputs, "autocorrect")
if rulesRecord.Source != "campaign_config" || rulesRecord.Size <= 0 || rulesRecord.Checksum == "" {
t.Fatalf("autocorrection provenance = %+v", rulesRecord)
}
record := findManifestInput(t, m.Inputs, "session_config")
if record.Source != "session_config.s3" || record.S3Bucket != "test-bucket" || record.S3ETag != "synthetic-etag" {
t.Fatalf("session provenance = %#v", record)
@@ -74,5 +81,5 @@ func TestPrepareMaterializesImportedDocumentsWithoutAuthoringFiles(t *testing.T)
assertPrepareResume(t, env, m, false)
env.Config.SessionDocument.Title = "Imported title"
env.Config.CampaignDocument.SessionTemplateFile = "/new/template.yml"
assertPrepareResume(t, env, m, false)
assertPrepareResume(t, env, m, true)
}

View File

@@ -1,45 +0,0 @@
//go:build unix
package stage
import (
"context"
"path/filepath"
"strings"
"testing"
"time"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"golang.org/x/sys/unix"
)
func TestPrepareStageRejectsSpellCatalogFIFOWithoutBlocking(t *testing.T) {
env, m := setupPrepareEnv(t)
root := filepath.Dir(env.Config.SessionPath)
writeFile(t, filepath.Join(root, "audio", "a.flac"), "audio")
env.Config.Session.Inputs.AudioFiles = []string{"./audio/a.flac"}
sourcePath := filepath.Join(root, "spells.fifo")
if err := unix.Mkfifo(sourcePath, 0o644); err != nil {
t.Fatalf("Mkfifo() error = %v", err)
}
env.Config.StableInputs.SpellCatalogFile = config.ResolvedInputFile{
Path: "./spells.fifo",
ConfigPath: env.Config.CampaignPath,
Source: "campaign_config",
}
done := make(chan error, 1)
go func() {
_, err := (prepareStage{}).Run(context.Background(), env, m)
done <- err
}()
select {
case err := <-done:
if err == nil || !strings.Contains(err.Error(), "not a regular file") {
t.Fatalf("prepare.Run() error = %v, want regular-file rejection", err)
}
case <-time.After(time.Second):
t.Fatal("prepare.Run() blocked while inspecting a FIFO spell catalog")
}
}

View File

@@ -23,6 +23,7 @@ type prepareExpectedInput struct {
kind string
destinationName string
checksum string
source string
configSnapshot bool
s3Bucket string
s3Key string
@@ -115,9 +116,11 @@ func currentPrepareSourceInputs(ctx context.Context, env *Env, m *manifest.Manif
if err := appendFile("speakers", cfg.StableInputs.SpeakersFile, cfg.Session.Inputs.SpeakersFile); err != nil {
return nil, err
}
if err := appendFile("autocorrect", cfg.StableInputs.AutocorrectFile, cfg.Session.Inputs.AutocorrectFile); err != nil {
autocorrect, err := config.RenderAutocorrection(cfg.Session.Inputs.Autocorrect)
if err != nil {
return nil, err
}
expected = append(expected, prepareExpectedInput{kind: "autocorrect", checksum: checksumPrepareBytes(autocorrect), source: config.AutocorrectionSource(cfg)})
documents, err := config.ResolveGlossaries(cfg)
if err != nil {
return nil, err
@@ -132,17 +135,6 @@ func currentPrepareSourceInputs(ctx context.Context, env *Env, m *manifest.Manif
}
expected = append(expected, prepareExpectedInput{kind: descriptor.ManifestKind, checksum: checksumPrepareBytes(documents[item.name])})
}
spellCatalog, ok := artifactpolicy.DescribePreparedInputSource(artifactpolicy.SourceInputSpellCatalog)
if !ok {
return nil, fmt.Errorf("spell catalog prepared-input descriptor is unavailable")
}
spellInput := stableInputSource(cfg.StableInputs.SpellCatalogFile, cfg.Session.Inputs.SpellCatalogFile, cfg.SessionPath)
if strings.TrimSpace(spellInput.Path) != "" {
if err := appendFile(spellCatalog.ManifestKind, cfg.StableInputs.SpellCatalogFile, cfg.Session.Inputs.SpellCatalogFile); err != nil {
return nil, err
}
}
partyInputs, err := currentPreparePartySourceInputs(env)
if err != nil {
return nil, err
@@ -234,7 +226,7 @@ func prepareSourceInputsMatch(paths artifacts.SessionPaths, expected []prepareEx
"campaign_config": {}, "session_config": {},
"audio": {}, "speakers": {}, "autocorrect": {}, "glossary": {},
"glossary_party": {}, "glossary_campaign": {}, "glossary_setting": {}, "glossary_spells": {},
"players": {}, "party": {}, "spell_catalog": {},
"players": {}, "party": {},
}
expectedCounts := make(map[string]int, len(managedKinds))
recordCounts := make(map[string]int, len(managedKinds))
@@ -282,6 +274,9 @@ func prepareInputRecordMatches(paths artifacts.SessionPaths, expected prepareExp
if record.Kind != expected.kind {
return false
}
if expected.source != "" && record.Source != expected.source {
return false
}
if expected.destinationName != "" && filepath.Base(record.Path) != expected.destinationName {
return false
}
@@ -308,10 +303,26 @@ func prepareConfigSnapshotChecksum(data []byte) (string, error) {
return "", err
}
if inputs, ok := document["inputs"].(map[string]any); ok {
for _, key := range []string{"setting", "system", "glossary_file", "glossary"} {
for _, key := range []string{"setting", "system", "glossary_file", "glossary", "speakers_file", "audio_dir", "audio_files"} {
delete(inputs, key)
}
}
delete(document, "setting")
delete(document, "system")
if references, ok := document["references"].(map[string]any); ok {
delete(references, "party")
if len(references) == 0 {
delete(document, "references")
}
}
if narratio, ok := document["narratio"].(map[string]any); ok {
delete(narratio, "session_template_file")
if inputs, ok := narratio["inputs"].(map[string]any); ok {
for _, key := range []string{"speakers_file", "glossary_file", "glossary"} {
delete(inputs, key)
}
}
}
normalized, err := yaml.Marshal(document)
if err != nil {
return "", err

View File

@@ -143,6 +143,70 @@ func TestPrepareResumeAcceptsRelocatedEquivalentLocalSource(t *testing.T) {
assertPrepareResume(t, env, m, true)
}
func TestPrepareAutocorrectionEvidenceAndReuse(t *testing.T) {
env, m, _ := prepareResumeLocalFixture(t)
assertPrepareResume(t, env, m, true)
record := findManifestInput(t, m.Inputs, "autocorrect")
data, err := os.ReadFile(record.Path)
if err != nil {
t.Fatal(err)
}
if string(data) != "autocorrect: []\n" || record.Size != int64(len(data)) || record.Checksum != checksumPrepareBytes(data) || record.Source != "derived_from_configuration" {
t.Fatalf("empty rules: %q, %+v", data, record)
}
env.Config.Session.Inputs.Autocorrect = []config.AutocorrectionRule{{Target: "Lantern", Match: []string{"Lan turn"}}}
assertPrepareResume(t, env, m, false)
if _, err := (prepareStage{}).Run(context.Background(), env, m); err != nil {
t.Fatal(err)
}
record = findManifestInput(t, m.Inputs, "autocorrect")
data, err = os.ReadFile(record.Path)
if err != nil {
t.Fatal(err)
}
want, err := config.RenderAutocorrection(env.Config.Session.Inputs.Autocorrect)
if err != nil {
t.Fatal(err)
}
if string(data) != string(want) || record.Size != int64(len(data)) || record.Checksum != checksumPrepareBytes(data) || record.Source != "session_config" {
t.Fatalf("rules: %q, %+v", data, record)
}
assertPrepareResume(t, env, m, true)
}
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")
a, err := prepareConfigSnapshotChecksum(first)
if err != nil {
t.Fatal(err)
}
b, err := prepareConfigSnapshotChecksum(second)
if err != nil {
t.Fatal(err)
}
if a != b {
t.Fatal("equivalent inputs from relocated sources changed the snapshot identity")
}
}
func TestPrepareResumeAcceptsRelocatedEquivalentSpeakerAndRosterSources(t *testing.T) {
env, m, _ := prepareResumeLocalFixture(t)
dir := filepath.Dir(env.Config.CampaignPath)
writeFile(t, filepath.Join(dir, "moved-speakers.yml"), "alice: alice.flac\n")
env.Config.Campaign.Inputs.SpeakersFile = "./moved-speakers.yml"
env.Config.Session.Inputs.SpeakersFile = "./moved-speakers.yml"
env.Config.StableInputs.SpeakersFile.Path = "./moved-speakers.yml"
party, err := os.ReadFile(filepath.Join(dir, "party.yml"))
if err != nil {
t.Fatal(err)
}
writeFile(t, filepath.Join(dir, "moved-party.yml"), string(party))
env.Config.Campaign.Inputs.PartyFile = "./moved-party.yml"
env.Config.StableInputs.PartyFile.Path = "./moved-party.yml"
assertPrepareResume(t, env, m, true)
}
func TestPrepareResumeDetectsCanonicalPartyChange(t *testing.T) {
env, m := setupPrepareEnv(t)
audioPath := filepath.Join(filepath.Dir(env.Config.SessionPath), "audio", "one.flac")

View File

@@ -3,8 +3,6 @@ package stage
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"os"
"path/filepath"
"strings"
@@ -230,167 +228,6 @@ characters:
}
}
func TestPrepareStageMaterializesSpellCatalogWithProvenance(t *testing.T) {
tests := []struct {
name string
configPath func(*config.Config) string
source string
}{
{name: "campaign", configPath: func(cfg *config.Config) string { return cfg.CampaignPath }, source: "campaign_config"},
{name: "session", configPath: func(cfg *config.Config) string { return cfg.SessionPath }, source: "session_config"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
env, m := setupPrepareEnv(t)
root := filepath.Dir(env.Config.SessionPath)
writeFile(t, filepath.Join(root, "audio", "a.flac"), "audio")
env.Config.Session.Inputs.AudioFiles = []string{"./audio/a.flac"}
payload := []byte(`{"spells":[{"name":"Fireball"}]}` + "\n")
sourcePath := filepath.Join(filepath.Dir(tt.configPath(env.Config)), tt.name+"-spells.json")
writeFile(t, sourcePath, string(payload))
env.Config.StableInputs.SpellCatalogFile = config.ResolvedInputFile{
Path: filepath.Base(sourcePath),
ConfigPath: tt.configPath(env.Config),
Source: tt.source,
}
if _, err := (prepareStage{}).Run(context.Background(), env, m); err != nil {
t.Fatalf("prepare.Run() error = %v", err)
}
destination := filepath.Join(sessionPathsForEnv(env, m.SessionID).InputsDir, "spell_catalog.json")
got, err := os.ReadFile(destination)
if err != nil {
t.Fatalf("ReadFile(destination) error = %v", err)
}
if string(got) != string(payload) {
t.Fatalf("destination bytes = %q, want %q", got, payload)
}
record := findManifestInput(t, m.Inputs, "spell_catalog")
digest := sha256.Sum256(payload)
wantChecksum := hex.EncodeToString(digest[:])
if record.Path != destination || record.Source != tt.source || record.Checksum != wantChecksum {
t.Fatalf("spell catalog record = %#v, want path=%q source=%q checksum=%q", record, destination, tt.source, wantChecksum)
}
assertManifestInputsSorted(t, m.Inputs)
})
}
}
func TestPrepareStageSpellCatalogOptionalOmission(t *testing.T) {
env, m := setupPrepareEnv(t)
root := filepath.Dir(env.Config.SessionPath)
writeFile(t, filepath.Join(root, "audio", "a.flac"), "audio")
env.Config.Session.Inputs.AudioFiles = []string{"./audio/a.flac"}
if _, err := (prepareStage{}).Run(context.Background(), env, m); err != nil {
t.Fatalf("prepare.Run() error = %v", err)
}
for _, input := range m.Inputs {
if input.Kind == "spell_catalog" {
t.Fatalf("unexpected spell catalog record: %#v", input)
}
}
destination := filepath.Join(sessionPathsForEnv(env, m.SessionID).InputsDir, "spell_catalog.json")
if _, err := os.Lstat(destination); !os.IsNotExist(err) {
t.Fatalf("Lstat(destination) error = %v, want not exist", err)
}
}
func TestPrepareStageSpellCatalogMissingOrNonRegularSource(t *testing.T) {
tests := []struct {
name string
setup func(string) error
}{
{name: "missing", setup: func(string) error { return nil }},
{name: "directory", setup: func(path string) error { return os.Mkdir(path, 0o755) }},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
env, m := setupPrepareEnv(t)
root := filepath.Dir(env.Config.SessionPath)
writeFile(t, filepath.Join(root, "audio", "a.flac"), "audio")
env.Config.Session.Inputs.AudioFiles = []string{"./audio/a.flac"}
sourcePath := filepath.Join(root, "spells.json")
if err := tt.setup(sourcePath); err != nil {
t.Fatalf("setup source: %v", err)
}
env.Config.StableInputs.SpellCatalogFile = config.ResolvedInputFile{
Path: "./spells.json",
ConfigPath: env.Config.CampaignPath,
Source: "campaign_config",
}
_, err := (prepareStage{}).Run(context.Background(), env, m)
if err == nil || !strings.Contains(err.Error(), "spell catalog") {
t.Fatalf("prepare.Run() error = %v, want spell catalog source error", err)
}
})
}
}
func TestPrepareStageReplacesAndRemovesSpellCatalog(t *testing.T) {
env, m := setupPrepareEnv(t)
root := filepath.Dir(env.Config.SessionPath)
writeFile(t, filepath.Join(root, "audio", "a.flac"), "audio")
env.Config.Session.Inputs.AudioFiles = []string{"./audio/a.flac"}
sourcePath := filepath.Join(root, "spells.json")
writeFile(t, sourcePath, "first\n")
env.Config.StableInputs.SpellCatalogFile = config.ResolvedInputFile{
Path: "./spells.json",
ConfigPath: env.Config.CampaignPath,
Source: "campaign_config",
}
stage := prepareStage{}
if _, err := stage.Run(context.Background(), env, m); err != nil {
t.Fatalf("first prepare.Run() error = %v", err)
}
firstChecksum := findManifestInput(t, m.Inputs, "spell_catalog").Checksum
destination := filepath.Join(sessionPathsForEnv(env, m.SessionID).InputsDir, "spell_catalog.json")
writeFile(t, sourcePath, "second\n")
if _, err := stage.Run(context.Background(), env, m); err != nil {
t.Fatalf("replacement prepare.Run() error = %v", err)
}
secondChecksum := findManifestInput(t, m.Inputs, "spell_catalog").Checksum
if secondChecksum == firstChecksum {
t.Fatalf("replacement checksum = %q, want different from %q", secondChecksum, firstChecksum)
}
mustReadFileEquals(t, destination, "second\n")
env.Config.StableInputs.SpellCatalogFile = config.ResolvedInputFile{}
env.Config.Session.Inputs.SpellCatalogFile = ""
if _, err := stage.Run(context.Background(), env, m); err != nil {
t.Fatalf("removal prepare.Run() error = %v", err)
}
if _, err := os.Lstat(destination); !os.IsNotExist(err) {
t.Fatalf("Lstat(destination) error = %v, want removed", err)
}
for _, input := range m.Inputs {
if input.Kind == "spell_catalog" {
t.Fatalf("stale spell catalog record remains: %#v", input)
}
}
}
func TestPrepareStageRefusesAmbiguousObsoleteSpellCatalog(t *testing.T) {
env, m := setupPrepareEnv(t)
root := filepath.Dir(env.Config.SessionPath)
writeFile(t, filepath.Join(root, "audio", "a.flac"), "audio")
env.Config.Session.Inputs.AudioFiles = []string{"./audio/a.flac"}
destination := filepath.Join(sessionPathsForEnv(env, m.SessionID).InputsDir, "spell_catalog.json")
writeFile(t, filepath.Join(destination, "keep.txt"), "keep")
_, err := (prepareStage{}).Run(context.Background(), env, m)
if err == nil || !strings.Contains(err.Error(), "remove obsolete spell catalog") || !strings.Contains(err.Error(), "non-regular") {
t.Fatalf("prepare.Run() error = %v, want ambiguous destination rejection", err)
}
mustReadFileEquals(t, filepath.Join(destination, "keep.txt"), "keep")
}
func TestPrepareStageRecordsLocalSessionProvenance(t *testing.T) {
env, m := setupPrepareEnv(t)
root := filepath.Dir(env.Config.SessionPath)
@@ -889,7 +726,7 @@ inputs:
Workspace: config.WorkspaceConfig{Root: workspace},
Cache: config.CacheConfig{Root: filepath.Join(t.TempDir(), "cache"), S3Audio: boolPtr(true)},
},
Campaign: &config.CampaignConfig{CampaignID: "sample-campaign"},
Campaign: &config.CampaignConfig{CampaignID: "sample-campaign", Inputs: config.CampaignInputsConfig{SpeakersFile: "./speakers.yml", PartyFile: "./party.yml"}},
SessionPath: sessionPath,
CampaignPath: campaignPath,
PipelinePath: pipelinePath,
@@ -900,7 +737,7 @@ inputs:
SessionID: "2026-05-03",
Campaign: "sample-campaign",
Inputs: config.SessionInputsConfig{
AudioDir: "./audio",
AudioDir: "./audio", SpeakersFile: "./speakers.yml",
},
},
StableInputs: config.ResolvedStableInputs{

View File

@@ -151,11 +151,10 @@ func prepareStableInputSemantics(cfg *config.Config) []prepareStableInputSelecti
stable := cfg.StableInputs
return []prepareStableInputSelection{
prepareStableInput("speakers", stable.SpeakersFile, cfg.Session.Inputs.SpeakersFile),
prepareStableInput("autocorrect", stable.AutocorrectFile, cfg.Session.Inputs.AutocorrectFile),
{Kind: "autocorrect", Present: true},
{Kind: "glossary_party", Present: true}, {Kind: "glossary_campaign", Present: true},
{Kind: "glossary_setting", Present: true}, {Kind: "glossary_spells", Present: true},
prepareStableInput("party", stable.PartyFile, ""),
prepareStableInput("spell_catalog", stable.SpellCatalogFile, cfg.Session.Inputs.SpellCatalogFile),
}
}