Complete session defaults within the ConfigKit lifecycle

This commit is contained in:
2026-11-20 04:24:20 +00:00
parent 16a4f7ee12
commit c3e6245416
17 changed files with 315 additions and 154 deletions

View File

@@ -160,6 +160,15 @@ or mutate its completed result to make derived artifacts appear.
## Stage 3: Complete session defaults within ConfigKit's lifecycle ## Stage 3: Complete session defaults within ConfigKit's lifecycle
**Completed.** Session loads receive selected-campaign defaults and record them
before handoff, retaining their actual native result and source inventory.
Concrete-session checks run in definition validation; typed identity assertions
remain explicit. Stable input references are derived without mutating loaded
values, and standalone rendering preserves explicit optional-input clearing.
Session/default/import/discovery, preparation, initialization, native boundary,
and build checks pass with Go 1.27.4. The two catalog dependency tests noted in
Stage 2 remain pending Stage 4.
Read: `internal/config/document_configkit.go`, `load.go` and Read: `internal/config/document_configkit.go`, `load.go` and
`mergeCampaignSession`, `document_render.go`, campaign/session validation, `mergeCampaignSession`, `document_render.go`, campaign/session validation,
and ConfigKit's resolution recording and presence contracts. and ConfigKit's resolution recording and presence contracts.

View File

@@ -1,6 +1,7 @@
package app package app
import ( import (
"gitea.maximumdirect.net/eric/narratio/internal/config"
"go.maximumdirect.net/ckconfig" "go.maximumdirect.net/ckconfig"
"go.maximumdirect.net/commandkit" "go.maximumdirect.net/commandkit"
) )
@@ -22,7 +23,8 @@ func operationOutcome(err error) commandkit.Outcome {
} }
func classifyOperationError(err error) commandkit.OutcomeKind { func classifyOperationError(err error) commandkit.OutcomeKind {
if _, ok := err.(*inputError); ok { switch err.(type) {
case *inputError, *config.SessionIdentityError:
return commandkit.OutcomeUsage return commandkit.OutcomeUsage
} }
switch wrapped := err.(type) { switch wrapped := err.(type) {

View File

@@ -92,6 +92,7 @@ func TestOperationOutcomePreservesCausesAndOperationalPrecedence(t *testing.T) {
status int status int
}{ }{
{nil, 0}, {input, 2}, {invalid, 2}, {nil, 0}, {input, 2}, {invalid, 2},
{&config.SessionIdentityError{Source: "session.yml", Field: "session_id", Expected: "one", Actual: "two"}, 2},
{fmt.Errorf("request: %w", errors.Join(input, invalid)), 2}, {fmt.Errorf("request: %w", errors.Join(input, invalid)), 2},
{errors.Join(input, operational), 1}, {errors.Join(input, operational), 1},
{fmt.Errorf("request: %w", errors.Join(invalid, context.Canceled)), 1}, {fmt.Errorf("request: %w", errors.Join(invalid, context.Canceled)), 1},

View File

@@ -54,6 +54,9 @@ func loadCommandConfigWithDependencies(ctx context.Context, pipelineFlag, campai
return nil, err return nil, err
} }
sessionOpts.Campaign = base.Campaign
sessionOpts.CampaignPath = base.CampaignPath
if explicitSession := strings.TrimSpace(sessionFlag); explicitSession != "" { if explicitSession := strings.TrimSpace(sessionFlag); explicitSession != "" {
cfg, err := config.LoadSessionWithPipelineCampaignOptions(*base, explicitSession, sessionOpts) cfg, err := config.LoadSessionWithPipelineCampaignOptions(*base, explicitSession, sessionOpts)
if err != nil { if err != nil {

View File

@@ -97,6 +97,8 @@ func sessionInitWithDependencies(ctx context.Context, args []string, out io.Writ
authoringPath = resolveSessionInitTemplatePath(input.CampaignPath, input.TemplateFile) authoringPath = resolveSessionInitTemplatePath(input.CampaignPath, input.TemplateFile)
} }
sessionCfg, err := config.LoadSessionAuthoringBytes(authoringPath, data, config.SessionLoadOptions{ sessionCfg, err := config.LoadSessionAuthoringBytes(authoringPath, data, config.SessionLoadOptions{
Campaign: base.Campaign,
CampaignPath: base.CampaignPath,
SessionID: sessionID, SessionID: sessionID,
PreviousSessionID: previousSessionID, PreviousSessionID: previousSessionID,
}) })

View File

@@ -28,7 +28,7 @@ func TestSessionInitMaterializesLocalTemplateImports(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if loaded.Title != "Shared metadata" || loaded.Inputs.SpeakersFile != "" { if loaded.Title != "Shared metadata" || loaded.Inputs.SpeakersFile != filepath.Join(filepath.Dir(campaign), "speakers.yml") {
t.Fatalf("unexpected standalone session: %#v", loaded) t.Fatalf("unexpected standalone session: %#v", loaded)
} }
} }

View File

@@ -225,7 +225,7 @@ func TestCampaignSessionMismatchFails(t *testing.T) {
if err == nil { if err == nil {
t.Fatal("expected load error, got nil") t.Fatal("expected load error, got nil")
} }
if !strings.Contains(err.Error(), "does not match campaign config") { if !strings.Contains(err.Error(), "campaign mismatch") {
t.Fatalf("error = %q, want campaign mismatch context", err.Error()) t.Fatalf("error = %q, want campaign mismatch context", err.Error())
} }
} }

View File

@@ -26,6 +26,20 @@ func (cfg *CampaignConfig) ConfigKitResult() *configkit.Result[CampaignConfig] {
return cfg.resolution.campaign return cfg.resolution.campaign
} }
// ConfigKitResult returns the session's actual completed native load result.
// Constructed session values have no result.
func (cfg *SessionConfig) ConfigKitResult() *configkit.Result[SessionConfig] {
if cfg == nil || cfg.resolution == nil {
return nil
}
return cfg.resolution.session
}
func sessionFieldExplicit(cfg *SessionConfig, name string) bool {
result := cfg.ConfigKitResult()
return result != nil && result.Metadata().IsExplicit(configkit.Keys("inputs", name))
}
func documentResource(resolution *configkit.Resolution, path configkit.Path, value *string, invocationDir string, sources map[string]string) { 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 info, ok := resolution.EntryInfo(path); ok && len(info.Origin.Locations) == 1 {
if source, ok := resolution.Source(info.Origin.Locations[0].SourceID); ok { if source, ok := resolution.Source(info.Origin.Locations[0].SourceID); ok {
@@ -57,8 +71,14 @@ func campaignDefinition(invocationDir string, sources map[string]string) configk
}, Validate: validateCampaignConfigKit} }, Validate: validateCampaignConfigKit}
} }
func sessionDefinition(invocationDir string, sources map[string]string) configkit.Definition[SessionConfig] { func sessionDefinition(invocationDir string, sources map[string]string, label string, opts SessionLoadOptions) configkit.Definition[SessionConfig] {
hasSource := false
return configkit.Definition[SessionConfig]{Resolve: func(cfg *SessionConfig, resolution *configkit.Resolution) error { return configkit.Definition[SessionConfig]{Resolve: func(cfg *SessionConfig, resolution *configkit.Resolution) error {
info, ok := resolution.EntryInfo(configkit.Keys())
hasSource = ok && len(info.Origin.Locations) > 0
if !hasSource {
return nil
}
inputs := configkit.Keys("inputs") inputs := configkit.Keys("inputs")
for _, field := range []struct { for _, field := range []struct {
name string name string
@@ -73,10 +93,51 @@ func sessionDefinition(invocationDir string, sources map[string]string) configki
for index := range cfg.Inputs.AudioFiles { for index := range cfg.Inputs.AudioFiles {
documentResource(resolution, inputs.Key("audio_files").Index(index), &cfg.Inputs.AudioFiles[index], invocationDir, sources) documentResource(resolution, inputs.Key("audio_files").Index(index), &cfg.Inputs.AudioFiles[index], invocationDir, sources)
} }
applyCampaignSessionDefaults(cfg, resolution, opts)
return nil return nil
}, Validate: func(cfg *SessionConfig, validation *configkit.Validation) {
// Optional discovery with no selected document leaves acquisition to
// the caller's next source. There is no session to validate yet.
if !hasSource {
return
}
data, err := json.Marshal(cfg)
if err != nil {
validation.Error(configkit.Keys(), "cannot inspect session configuration")
return
}
if err := rejectSessionTemplatePlaceholders(label, string(data)); err != nil {
validation.Error(configkit.Keys(), err.Error())
return
}
if path, err := sessionConfigurationError(cfg); err != nil {
validation.Error(path, err.Error())
}
}} }}
} }
func applyCampaignSessionDefaults(cfg *SessionConfig, resolution *configkit.Resolution, opts SessionLoadOptions) {
if opts.Campaign == nil {
return
}
campaign := opts.Campaign
reason := fmt.Sprintf("default from campaign %q (%s)", CampaignID(campaign), opts.CampaignPath)
configkit.Default(resolution, configkit.Keys("campaign"), &cfg.Campaign, CampaignID(campaign), reason)
for _, field := range []struct {
name, value string
target *string
}{
{"speakers_file", campaign.Inputs.SpeakersFile, &cfg.Inputs.SpeakersFile},
{"autocorrect_file", campaign.Inputs.AutocorrectFile, &cfg.Inputs.AutocorrectFile},
{"glossary_file", campaign.Inputs.GlossaryFile, &cfg.Inputs.GlossaryFile},
{"spell_catalog_file", campaign.Inputs.SpellCatalogFile, &cfg.Inputs.SpellCatalogFile},
} {
if field.value != "" {
configkit.Default(resolution, configkit.Keys("inputs", field.name), field.target, field.value, reason)
}
}
}
func loadCampaignWithConfigKit(path string) (*CampaignConfig, error) { func loadCampaignWithConfigKit(path string) (*CampaignConfig, error) {
invocationDir, err := os.Getwd() invocationDir, err := os.Getwd()
if err != nil { if err != nil {
@@ -117,7 +178,7 @@ func loadSessionSourceWithFilesystem(source configkit.Source, label string, opts
invocationDir = filesystem.BaseDir invocationDir = filesystem.BaseDir
} }
sources := make(map[string]string) sources := make(map[string]string)
result, err := configkit.Load(source, configkit.Options[SessionConfig]{Imports: imports, Filesystem: filesystem, Definition: sessionDefinition(invocationDir, sources)}) result, err := configkit.Load(source, configkit.Options[SessionConfig]{Imports: imports, Filesystem: filesystem, Definition: sessionDefinition(invocationDir, sources, label, opts)})
if err != nil { if err != nil {
return nil, "", describeConfigKitLoadError("session", err) return nil, "", describeConfigKitLoadError("session", err)
} }
@@ -129,19 +190,12 @@ func loadSessionSourceWithFilesystem(source configkit.Source, label string, opts
if selected == "" { if selected == "" {
selected = label selected = label
} }
cfg := result.Config cfg := &result.Config
data, err := json.Marshal(cfg) if err := validateSessionIdentity(selected, cfg, opts); err != nil {
if err != nil {
return nil, "", fmt.Errorf("inspect session config: %w", err)
}
if err := rejectSessionTemplatePlaceholders(selected, string(data)); err != nil {
return nil, "", fmt.Errorf("load session config: %w", err)
}
if err := validateSessionIdentity(selected, &cfg, opts); err != nil {
return nil, "", err return nil, "", err
} }
cfg.resolution = &documentResolution{session: result, sources: sources} cfg.resolution = &documentResolution{session: result, sources: sources}
return &cfg, filepath.Clean(selected), nil return cfg, filepath.Clean(selected), nil
} }
// DiscoverSession loads the first selected local candidate, or returns nil when // DiscoverSession loads the first selected local candidate, or returns nil when

View File

@@ -42,18 +42,18 @@ inputs:
t.Fatalf("audio[%d] = %q", i, got) t.Fatalf("audio[%d] = %q", i, got)
} }
} }
if cfg.SessionDocument.Inputs.GlossaryFile != "" || cfg.SessionDocument.Inputs.SpeakersFile != filepath.Join(dir, "session/override.yml") { if cfg.SessionDocument.Inputs.GlossaryFile != filepath.Join(dir, "campaign/glossary.yml") || cfg.SessionDocument.Inputs.SpeakersFile != filepath.Join(dir, "session/override.yml") {
t.Fatalf("detached session = %#v", cfg.SessionDocument) t.Fatalf("completed session = %#v", cfg.SessionDocument)
} }
if cfg.CampaignDocument.Inputs.GlossaryFile != filepath.Join(dir, "campaign/glossary.yml") { if cfg.CampaignDocument.Inputs.GlossaryFile != filepath.Join(dir, "campaign/glossary.yml") {
t.Fatalf("detached campaign = %#v", cfg.CampaignDocument) t.Fatalf("completed campaign = %#v", cfg.CampaignDocument)
} }
} }
func TestSessionDiscoveryDistinguishesAbsenceFromInvalidSelection(t *testing.T) { func TestSessionDiscoveryDistinguishesAbsenceFromInvalidSelection(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
first := filepath.Join(dir, "first.yml") first := filepath.Join(dir, "first.yml")
second := writePipelineFixture(t, dir, "second.yml", "session_id: valid\n") second := writePipelineFixture(t, dir, "second.yml", "session_id: valid\n"+standaloneSessionFields)
if cfg, path, err := DiscoverSession([]string{first, second}, SessionLoadOptions{}); err != nil || cfg == nil || path != second { if cfg, path, err := DiscoverSession([]string{first, second}, SessionLoadOptions{}); err != nil || cfg == nil || path != second {
t.Fatalf("selected = %#v %q %v", cfg, path, err) t.Fatalf("selected = %#v %q %v", cfg, path, err)
} }
@@ -86,7 +86,7 @@ func TestRemoteSessionResourceBaseIgnoresDiagnosticLabel(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
for _, label := range []string{"s3://bucket/session.yml", filepath.Join(t.TempDir(), "download.yml")} { for _, label := range []string{"s3://bucket/session.yml", filepath.Join(t.TempDir(), "download.yml")} {
cfg, err := LoadSessionBytesWithOptions(label, []byte("session_id: test\ninputs: {audio_dir: ./audio}\n"), SessionLoadOptions{}) cfg, err := LoadSessionBytesWithOptions(label, []byte("session_id: test\n"+standaloneSessionFields), SessionLoadOptions{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -110,7 +110,7 @@ func TestEquivalentDocumentLayoutsRenderIdentically(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
session, err := LoadSession(files[1]) session, err := LoadSessionWithOptions(files[1], SessionLoadOptions{Campaign: campaign, CampaignPath: files[0]})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@@ -56,8 +56,11 @@ func RenderSessionDocument(cfg *Config, sessionID string) ([]byte, error) {
SpeakersFile string `yaml:"speakers_file,omitempty"` SpeakersFile string `yaml:"speakers_file,omitempty"`
AutocorrectFile string `yaml:"autocorrect_file,omitempty"` AutocorrectFile string `yaml:"autocorrect_file,omitempty"`
GlossaryFile string `yaml:"glossary_file,omitempty"` GlossaryFile string `yaml:"glossary_file,omitempty"`
SpellCatalogFile string `yaml:"spell_catalog_file,omitempty"` SpellCatalogFile *string `yaml:"spell_catalog_file,omitempty"`
}{doc.Inputs.AudioDir, doc.Inputs.AudioFiles, doc.Inputs.AudioS3, doc.Inputs.SpeakersFile, doc.Inputs.AutocorrectFile, doc.Inputs.GlossaryFile, doc.Inputs.SpellCatalogFile} }{doc.Inputs.AudioDir, doc.Inputs.AudioFiles, doc.Inputs.AudioS3, doc.Inputs.SpeakersFile, doc.Inputs.AutocorrectFile, doc.Inputs.GlossaryFile, nil}
if doc.Inputs.SpellCatalogFile != "" || sessionFieldExplicit(doc, "spell_catalog_file") {
inputs.SpellCatalogFile = &doc.Inputs.SpellCatalogFile
}
value := struct { value := struct {
SessionID string `yaml:"session_id"` SessionID string `yaml:"session_id"`
PreviousSessionID string `yaml:"previous_session_id,omitempty"` PreviousSessionID string `yaml:"previous_session_id,omitempty"`

View File

@@ -4,7 +4,6 @@ import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"regexp" "regexp"
"slices"
"sort" "sort"
"strings" "strings"
@@ -69,8 +68,10 @@ func LoadSession(path string) (*SessionConfig, error) {
return LoadSessionWithOptions(path, SessionLoadOptions{}) return LoadSessionWithOptions(path, SessionLoadOptions{})
} }
// SessionLoadOptions configures expected session identity checks. // SessionLoadOptions supplies campaign defaults and expected session identities.
type SessionLoadOptions struct { type SessionLoadOptions struct {
Campaign *CampaignConfig
CampaignPath string
SessionID string SessionID string
PreviousSessionID string PreviousSessionID string
Overlay *string Overlay *string
@@ -89,19 +90,35 @@ func LoadSessionBytesWithOptions(label string, data []byte, opts SessionLoadOpti
return cfg, err return cfg, err
} }
func validateSessionIdentity(label string, cfg *SessionConfig, opts SessionLoadOptions) error { // SessionIdentityError identifies an explicit identity assertion that the
if strings.TrimSpace(opts.SessionID) != "" && strings.TrimSpace(cfg.SessionID) != "" && strings.TrimSpace(cfg.SessionID) != strings.TrimSpace(opts.SessionID) { // completed session configuration does not satisfy.
return fmt.Errorf("load session config: session file %q: session_id mismatch: --session-id %q does not match session_id %q", label, strings.TrimSpace(opts.SessionID), strings.TrimSpace(cfg.SessionID)) type SessionIdentityError struct {
Source string
Field string
Expected string
Actual string
}
func (e *SessionIdentityError) Error() string {
if e.Actual == "" {
return fmt.Sprintf("load session config: session file %q: %s is required when %q is selected", e.Source, e.Field, e.Expected)
} }
if expected := strings.TrimSpace(opts.PreviousSessionID); expected != "" { return fmt.Sprintf("load session config: session file %q: %s mismatch: selected %q does not match %q", e.Source, e.Field, e.Expected, e.Actual)
actual := strings.TrimSpace(cfg.PreviousSessionID) }
if actual == "" {
return fmt.Errorf("load session config: session file %q: previous_session_id is required when --previous-session-id %q is provided", label, expected) func validateSessionIdentity(label string, cfg *SessionConfig, opts SessionLoadOptions) error {
} for _, assertion := range []struct{ field, expected, actual string }{
if actual != expected { {"session_id", opts.SessionID, cfg.SessionID},
return fmt.Errorf("load session config: session file %q: previous_session_id mismatch: --previous-session-id %q does not match previous_session_id %q", label, expected, actual) {"previous_session_id", opts.PreviousSessionID, cfg.PreviousSessionID},
} {
expected := strings.TrimSpace(assertion.expected)
if expected != "" && strings.TrimSpace(assertion.actual) != expected {
return &SessionIdentityError{Source: label, Field: assertion.field, Expected: expected, Actual: assertion.actual}
} }
} }
if opts.Campaign != nil && cfg.Campaign != CampaignID(opts.Campaign) {
return &SessionIdentityError{Source: label, Field: "campaign", Expected: CampaignID(opts.Campaign), Actual: cfg.Campaign}
}
return nil return nil
} }
@@ -192,6 +209,8 @@ func LoadPipelineCampaignWithParty(pipelinePath string, pipeline *PipelineConfig
// LoadSessionWithPipelineCampaignOptions loads one local session and combines // LoadSessionWithPipelineCampaignOptions loads one local session and combines
// it with an already loaded pipeline and campaign. // it with an already loaded pipeline and campaign.
func LoadSessionWithPipelineCampaignOptions(loaded LoadedPipelineCampaign, sessionPath string, sessionOpts SessionLoadOptions) (*Config, error) { func LoadSessionWithPipelineCampaignOptions(loaded LoadedPipelineCampaign, sessionPath string, sessionOpts SessionLoadOptions) (*Config, error) {
sessionOpts.Campaign = loaded.Campaign
sessionOpts.CampaignPath = loaded.CampaignPath
sessionCfg, err := LoadSessionWithOptions(sessionPath, sessionOpts) sessionCfg, err := LoadSessionWithOptions(sessionPath, sessionOpts)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -230,20 +249,13 @@ func ResolveLoadedPipelineCampaign(loaded LoadedPipelineCampaign, sessionPath st
SessionSource: sessionSource, SessionSource: sessionSource,
Party: loaded.Party, Party: loaded.Party,
} }
campaignDocument := *loaded.Campaign cfg.CampaignDocument = loaded.Campaign
cfg.CampaignDocument = &campaignDocument cfg.SessionDocument = sessionCfg
if sessionCfg == nil { if sessionCfg == nil {
return cfg, nil return cfg, nil
} }
sessionDocument := *sessionCfg
sessionDocument.Inputs.AudioFiles = slices.Clone(sessionCfg.Inputs.AudioFiles)
if sessionCfg.Inputs.AudioS3 != nil {
audio := *sessionCfg.Inputs.AudioS3
sessionDocument.Inputs.AudioS3 = &audio
}
cfg.SessionDocument = &sessionDocument
stableInputs, err := mergeCampaignSession(loaded.Campaign, sessionCfg, loaded.CampaignPath, sessionPath) stableInputs, err := deriveStableInputs(loaded.Campaign, sessionCfg, loaded.CampaignPath, sessionPath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -284,86 +296,44 @@ func campaignSessionPaths(paths ...string) (campaignPath, sessionPath string, er
return campaignPath, sessionPath, nil return campaignPath, sessionPath, nil
} }
func mergeCampaignSession(campaignCfg *CampaignConfig, sessionCfg *SessionConfig, campaignPath, sessionPath string) (ResolvedStableInputs, error) { func deriveStableInputs(campaignCfg *CampaignConfig, sessionCfg *SessionConfig, campaignPath, sessionPath string) (ResolvedStableInputs, error) {
if campaignCfg == nil { if campaignCfg == nil {
return ResolvedStableInputs{}, fmt.Errorf("campaign config is required") return ResolvedStableInputs{}, fmt.Errorf("campaign config is required")
} }
if sessionCfg == nil { if sessionCfg == nil {
return ResolvedStableInputs{}, fmt.Errorf("session config is required") return ResolvedStableInputs{}, fmt.Errorf("session config is required")
} }
if campaignCfg.Inputs.SpellCatalogFile != "" && strings.TrimSpace(campaignCfg.Inputs.SpellCatalogFile) == "" { if sessionCfg.Campaign != CampaignID(campaignCfg) {
return ResolvedStableInputs{}, fmt.Errorf("campaign.inputs.spell_catalog_file must be non-empty when provided") return ResolvedStableInputs{}, &SessionIdentityError{Source: sessionPath, Field: "campaign", Expected: CampaignID(campaignCfg), Actual: sessionCfg.Campaign}
}
if sessionCfg.Inputs.SpellCatalogFile != "" && strings.TrimSpace(sessionCfg.Inputs.SpellCatalogFile) == "" {
return ResolvedStableInputs{}, fmt.Errorf("session.inputs.spell_catalog_file must be non-empty when provided")
}
campaignName := CampaignID(campaignCfg)
sessionCampaign := strings.TrimSpace(sessionCfg.Campaign)
if sessionCampaign != "" && campaignName != "" && sessionCampaign != campaignName {
return ResolvedStableInputs{}, fmt.Errorf(
"campaign/session config invalid: session campaign %q does not match campaign config %q",
sessionCampaign,
campaignName,
)
}
if sessionCampaign == "" {
sessionCfg.Campaign = campaignName
}
stable := ResolvedStableInputs{
SpeakersFile: selectStableInput(
campaignCfg.Inputs.SpeakersFile,
sessionCfg.Inputs.SpeakersFile,
campaignPath,
sessionPath,
),
AutocorrectFile: selectStableInput(
campaignCfg.Inputs.AutocorrectFile,
sessionCfg.Inputs.AutocorrectFile,
campaignPath,
sessionPath,
),
GlossaryFile: selectStableInput(
campaignCfg.Inputs.GlossaryFile,
sessionCfg.Inputs.GlossaryFile,
campaignPath,
sessionPath,
),
PartyFile: selectStableInput(
campaignCfg.Inputs.PartyFile,
"",
campaignPath,
sessionPath,
),
SpellCatalogFile: selectStableInput(
campaignCfg.Inputs.SpellCatalogFile,
sessionCfg.Inputs.SpellCatalogFile,
campaignPath,
sessionPath,
),
} }
stable := ResolvedStableInputs{}
for _, field := range []struct { for _, field := range []struct {
name string name, value string
input *ResolvedInputFile target *ResolvedInputFile
campaignOnly bool
}{ }{
{"speakers_file", &stable.SpeakersFile}, {"autocorrect_file", &stable.AutocorrectFile}, {"speakers_file", sessionCfg.Inputs.SpeakersFile, &stable.SpeakersFile, false},
{"glossary_file", &stable.GlossaryFile}, {"party_file", &stable.PartyFile}, {"autocorrect_file", sessionCfg.Inputs.AutocorrectFile, &stable.AutocorrectFile, false},
{"spell_catalog_file", &stable.SpellCatalogFile}, {"glossary_file", sessionCfg.Inputs.GlossaryFile, &stable.GlossaryFile, false},
{"party_file", campaignCfg.Inputs.PartyFile, &stable.PartyFile, true},
{"spell_catalog_file", sessionCfg.Inputs.SpellCatalogFile, &stable.SpellCatalogFile, false},
} { } {
metadata := campaignCfg.resolution reference := ResolvedInputFile{Path: field.value, ConfigPath: sessionPath, Source: "session_config"}
if field.input.Source == "session_config" { metadata := sessionCfg.resolution
metadata = sessionCfg.resolution fromCampaign := field.campaignOnly
if sessionCfg.ConfigKitResult() != nil && !sessionFieldExplicit(sessionCfg, field.name) {
fromCampaign = true
}
if fromCampaign {
reference.ConfigPath = campaignPath
reference.Source = "campaign_config"
metadata = campaignCfg.resolution
} }
if metadata != nil && metadata.sources["/inputs/"+field.name] != "" { if metadata != nil && metadata.sources["/inputs/"+field.name] != "" {
field.input.ConfigPath = metadata.sources["/inputs/"+field.name] reference.ConfigPath = metadata.sources["/inputs/"+field.name]
} }
*field.target = reference
} }
sessionCfg.Inputs.SpeakersFile = stable.SpeakersFile.Path
sessionCfg.Inputs.AutocorrectFile = stable.AutocorrectFile.Path
sessionCfg.Inputs.GlossaryFile = stable.GlossaryFile.Path
sessionCfg.Inputs.SpellCatalogFile = stable.SpellCatalogFile.Path
return stable, nil return stable, nil
} }
@@ -375,21 +345,6 @@ func CampaignID(cfg *CampaignConfig) string {
return strings.TrimSpace(cfg.CampaignID) return strings.TrimSpace(cfg.CampaignID)
} }
func selectStableInput(campaignValue, sessionValue, campaignPath, sessionPath string) ResolvedInputFile {
if strings.TrimSpace(sessionValue) != "" {
return ResolvedInputFile{
Path: sessionValue,
ConfigPath: sessionPath,
Source: "session_config",
}
}
return ResolvedInputFile{
Path: campaignValue,
ConfigPath: campaignPath,
Source: "campaign_config",
}
}
var sessionTemplatePlaceholderPattern = regexp.MustCompile(`\{\{[^}]*\}\}`) var sessionTemplatePlaceholderPattern = regexp.MustCompile(`\{\{[^}]*\}\}`)
var sessionTemplateVariablePattern = regexp.MustCompile(`\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}`) var sessionTemplateVariablePattern = regexp.MustCompile(`\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}`)

View File

@@ -117,7 +117,7 @@ func TestResolveAndLoadedCampaignShareCanonicalPartyResolution(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("LoadCampaign() error = %v", err) t.Fatalf("LoadCampaign() error = %v", err)
} }
session, err := LoadSession(sessionPath) session, err := LoadSessionWithOptions(sessionPath, SessionLoadOptions{Campaign: campaign, CampaignPath: campaignPath})
if err != nil { if err != nil {
t.Fatalf("LoadSession() error = %v", err) t.Fatalf("LoadSession() error = %v", err)
} }

View File

@@ -0,0 +1,122 @@
package config
import (
"bytes"
"errors"
"path/filepath"
"reflect"
"strings"
"testing"
configkit "go.maximumdirect.net/configkit"
"gopkg.in/yaml.v3"
)
func TestSessionDefaultsCompleteBeforeNativeHandoff(t *testing.T) {
dir := t.TempDir()
pipeline := writePipelineFixture(t, dir, "pipeline.yml", "workspace: {root: work}\n")
campaign := writePipelineFixture(t, dir, "campaign.yml", "config:\n imports:\n - path: campaign/resources.yml\ncampaign_id: campaign\n")
fragment := writePipelineFixture(t, dir, "campaign/resources.yml", `inputs:
speakers_file: speakers.yml
autocorrect_file: autocorrect.yml
glossary_file: glossary.yml
party_file: party.yml
spell_catalog_file: spells.yml
`)
writePipelineFixture(t, dir, "campaign/party.yml", canonicalPartyFixture)
session := writePipelineFixture(t, dir, "session.yml", "config:\n imports:\n - path: session/resources.yml\nsession_id: session\n")
sessionFragment := writePipelineFixture(t, dir, "session/resources.yml", "inputs:\n audio_dir: audio\n speakers_file: override.yml\n spell_catalog_file: ''\n")
cfg, err := LoadWithSessionOptions(pipeline, campaign, session, SessionLoadOptions{SessionID: "session"})
if err != nil {
t.Fatal(err)
}
result := cfg.Session.ConfigKitResult()
if result == nil || cfg.Session != &result.Config {
t.Fatal("session lost its actual native result")
}
if len(result.Sources()) != 2 {
t.Fatalf("session sources include unrelated campaign inputs: %+v", result.Sources())
}
if cfg.Session.Campaign != "campaign" || cfg.Session.Inputs.GlossaryFile != filepath.Join(dir, "campaign/glossary.yml") || cfg.Session.Inputs.SpellCatalogFile != "" {
t.Fatalf("session defaults/explicit clearing: %+v", cfg.Session)
}
if cfg.StableInputs.GlossaryFile.Source != "campaign_config" || cfg.StableInputs.GlossaryFile.ConfigPath != fragment || cfg.StableInputs.SpeakersFile.ConfigPath != sessionFragment || cfg.StableInputs.SpellCatalogFile.Source != "session_config" {
t.Fatalf("stable input references: %+v", cfg.StableInputs)
}
explanation, ok := result.Explain(configkit.Keys("inputs", "glossary_file"))
if !ok || explanation.Origin.Layer != configkit.LayerResolution {
t.Fatalf("default origin: %+v", explanation)
}
found := false
for _, change := range explanation.History {
if strings.Contains(strings.Join(change.Reasons, " "), campaign) {
found = true
}
}
if !found {
t.Fatalf("default history lacks campaign context: %+v", explanation.History)
}
var shown bytes.Buffer
if err := result.WriteEffective(&shown); err != nil {
t.Fatal(err)
}
var decoded SessionConfig
if err := yaml.Unmarshal(shown.Bytes(), &decoded); err != nil {
t.Fatal(err)
}
if decoded.Campaign != cfg.Session.Campaign || !reflect.DeepEqual(decoded.Inputs, cfg.Session.Inputs) {
t.Fatal("native show and domain session differ")
}
before := shown.String()
if _, err := deriveStableInputs(cfg.Campaign, cfg.Session, campaign, session); err != nil {
t.Fatal(err)
}
shown.Reset()
if err := result.WriteEffective(&shown); err != nil {
t.Fatal(err)
}
if shown.String() != before {
t.Fatal("reference derivation changed native configuration")
}
materialized, err := RenderSessionDocument(cfg, "session")
if err != nil {
t.Fatal(err)
}
reloaded, err := LoadSessionBytesWithOptions("materialized", materialized, SessionLoadOptions{Campaign: cfg.Campaign, CampaignPath: campaign})
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(reloaded.Inputs, cfg.Session.Inputs) {
t.Fatalf("standalone rendering lost effective values or explicit clearing: %s", materialized)
}
}
func TestSessionDefaultsRespectExplicitEmptyInputsAndIdentity(t *testing.T) {
dir := t.TempDir()
campaignPath := writePipelineFixture(t, dir, "campaign.yml", "campaign_id: campaign\ninputs: {speakers_file: speakers.yml, autocorrect_file: autocorrect.yml, glossary_file: glossary.yml, party_file: party.yml}\n")
campaign, err := LoadCampaign(campaignPath)
if err != nil {
t.Fatal(err)
}
opts := SessionLoadOptions{Campaign: campaign, CampaignPath: campaignPath, SessionID: "session"}
for _, data := range []string{
"session_id: session\ninputs: {audio_dir: audio, glossary_file: ''}\n",
"session_id: session\ncampaign: ''\ninputs: {audio_dir: audio}\n",
"session_id: session\ninputs: null\n",
} {
_, err := LoadSessionBytesWithOptions("session.yml", []byte(data), opts)
var native *configkit.LoadError
if !errors.As(err, &native) {
t.Fatalf("explicit invalid value did not retain a native validation failure: %v", err)
}
}
_, err = LoadSessionBytesWithOptions("session.yml", []byte("session_id: other\ninputs: {audio_dir: audio}\n"), opts)
var mismatch *SessionIdentityError
if !errors.As(err, &mismatch) || mismatch.Field != "session_id" || mismatch.Actual != "other" {
t.Fatalf("identity assertion was concealed by defaults: %v", err)
}
_, err = LoadSessionBytesWithOptions("session.yml", []byte("session_id: session\ncampaign: other\ninputs: {audio_dir: audio}\n"), opts)
if !errors.As(err, &mismatch) || mismatch.Field != "campaign" {
t.Fatalf("campaign assertion was concealed: %v", err)
}
}

View File

@@ -116,11 +116,7 @@ inputs:
func TestLoadSessionWithOptionsRequiresExpectedPreviousSession(t *testing.T) { func TestLoadSessionWithOptionsRequiresExpectedPreviousSession(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
sessionPath := filepath.Join(dir, "session.yml") sessionPath := filepath.Join(dir, "session.yml")
sessionYAML := `session_id: 2026-05-03 sessionYAML := "session_id: 2026-05-03\n" + standaloneSessionFields
campaign: sample-campaign
inputs:
audio_dir: ./audio
`
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil { if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
t.Fatalf("write session.yml: %v", err) t.Fatalf("write session.yml: %v", err)
} }
@@ -196,7 +192,7 @@ inputs:
} }
func TestLoadSessionBytesWithOptionsStrictDecode(t *testing.T) { func TestLoadSessionBytesWithOptionsStrictDecode(t *testing.T) {
cfg, err := LoadSessionBytesWithOptions("s3://bucket/session.yml", []byte("session_id: 2026-05-03\n"), SessionLoadOptions{}) cfg, err := LoadSessionBytesWithOptions("s3://bucket/session.yml", []byte("session_id: 2026-05-03\n"+standaloneSessionFields), SessionLoadOptions{})
if err != nil { if err != nil {
t.Fatalf("LoadSessionBytesWithOptions() error = %v", err) t.Fatalf("LoadSessionBytesWithOptions() error = %v", err)
} }
@@ -214,7 +210,7 @@ func TestLoadSessionBytesWithOptionsStrictDecode(t *testing.T) {
} }
func TestLoadSessionBytesWithOptionsMismatchFails(t *testing.T) { func TestLoadSessionBytesWithOptionsMismatchFails(t *testing.T) {
_, err := LoadSessionBytesWithOptions("s3://bucket/session.yml", []byte("session_id: 2026-05-03\n"), SessionLoadOptions{SessionID: "2026-04-04"}) _, err := LoadSessionBytesWithOptions("s3://bucket/session.yml", []byte("session_id: 2026-05-03\n"+standaloneSessionFields), SessionLoadOptions{SessionID: "2026-04-04"})
if err == nil { if err == nil {
t.Fatal("expected mismatch error, got nil") t.Fatal("expected mismatch error, got nil")
} }
@@ -226,7 +222,7 @@ func TestLoadSessionBytesWithOptionsMismatchFails(t *testing.T) {
func TestLoadSessionBytesWithOptionsRequiresExpectedPreviousSession(t *testing.T) { func TestLoadSessionBytesWithOptionsRequiresExpectedPreviousSession(t *testing.T) {
_, err := LoadSessionBytesWithOptions( _, err := LoadSessionBytesWithOptions(
"s3://bucket/session.yml", "s3://bucket/session.yml",
[]byte("session_id: 2026-05-03\n"), []byte("session_id: 2026-05-03\n"+standaloneSessionFields),
SessionLoadOptions{PreviousSessionID: "2026-04-26"}, SessionLoadOptions{PreviousSessionID: "2026-04-26"},
) )
if err == nil || !strings.Contains(err.Error(), "previous_session_id is required") { if err == nil || !strings.Contains(err.Error(), "previous_session_id is required") {
@@ -248,3 +244,13 @@ func assertConcreteSessionTemplateError(t *testing.T, err error, vars ...string)
} }
} }
} }
// Minimal concrete session fields for tests that exercise source acquisition or
// identity assertions independently of campaign defaulting.
const standaloneSessionFields = `campaign: sample-campaign
inputs:
audio_dir: audio
speakers_file: speakers.yml
autocorrect_file: autocorrect.yml
glossary_file: glossary.yml
`

View File

@@ -707,10 +707,9 @@ storage:
pipelinePath, sessionPath := writeConfigFiles(t, pipelineYAML, tt.sessionYAML) pipelinePath, sessionPath := writeConfigFiles(t, pipelineYAML, tt.sessionYAML)
cfg, err := Load(pipelinePath, sessionPath) cfg, err := Load(pipelinePath, sessionPath)
if err != nil { if err == nil {
t.Fatalf("Load() error = %v", err) err = Validate(cfg)
} }
err = Validate(cfg)
if tt.wantErr != "" { if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) { if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("Validate() error = %v, want to contain %q", err, tt.wantErr) t.Fatalf("Validate() error = %v, want to contain %q", err, tt.wantErr)

View File

@@ -62,33 +62,38 @@ func validateCache(cfg CacheConfig) error {
} }
func validateSession(cfg *SessionConfig) error { func validateSession(cfg *SessionConfig) error {
_, err := sessionConfigurationError(cfg)
return err
}
func sessionConfigurationError(cfg *SessionConfig) (configkit.Path, error) {
if err := validateSessionIdentifier("session.session_id", cfg.SessionID, true); err != nil { if err := validateSessionIdentifier("session.session_id", cfg.SessionID, true); err != nil {
return err return configkit.Keys("session_id"), err
} }
if err := validateSessionIdentifier("session.previous_session_id", cfg.PreviousSessionID, false); err != nil { if err := validateSessionIdentifier("session.previous_session_id", cfg.PreviousSessionID, false); err != nil {
return err return configkit.Keys("previous_session_id"), err
} }
if strings.TrimSpace(cfg.PreviousSessionID) != "" && strings.TrimSpace(cfg.PreviousSessionID) == strings.TrimSpace(cfg.SessionID) { if strings.TrimSpace(cfg.PreviousSessionID) != "" && strings.TrimSpace(cfg.PreviousSessionID) == strings.TrimSpace(cfg.SessionID) {
return fmt.Errorf("session.previous_session_id must not equal session.session_id") return configkit.Keys("previous_session_id"), fmt.Errorf("session.previous_session_id must not equal session.session_id")
} }
if strings.TrimSpace(cfg.Campaign) == "" { if strings.TrimSpace(cfg.Campaign) == "" {
return fmt.Errorf("session.campaign is required") return configkit.Keys("campaign"), fmt.Errorf("session.campaign is required")
} }
if err := pathsafe.ValidateOpaqueSegment(cfg.Campaign); err != nil { if err := pathsafe.ValidateOpaqueSegment(cfg.Campaign); err != nil {
return fmt.Errorf("session.campaign: %w", err) return configkit.Keys("campaign"), fmt.Errorf("session.campaign: %w", err)
} }
if strings.TrimSpace(cfg.Inputs.SpeakersFile) == "" { if strings.TrimSpace(cfg.Inputs.SpeakersFile) == "" {
return fmt.Errorf("session.inputs.speakers_file is required") return configkit.Keys("inputs", "speakers_file"), fmt.Errorf("session.inputs.speakers_file is required")
} }
if strings.TrimSpace(cfg.Inputs.AutocorrectFile) == "" { if strings.TrimSpace(cfg.Inputs.AutocorrectFile) == "" {
return fmt.Errorf("session.inputs.autocorrect_file is required") return configkit.Keys("inputs", "autocorrect_file"), fmt.Errorf("session.inputs.autocorrect_file is required")
} }
if strings.TrimSpace(cfg.Inputs.GlossaryFile) == "" { if strings.TrimSpace(cfg.Inputs.GlossaryFile) == "" {
return fmt.Errorf("session.inputs.glossary_file is required") return configkit.Keys("inputs", "glossary_file"), fmt.Errorf("session.inputs.glossary_file is required")
} }
if cfg.Inputs.SpellCatalogFile != "" && strings.TrimSpace(cfg.Inputs.SpellCatalogFile) == "" { if cfg.Inputs.SpellCatalogFile != "" && strings.TrimSpace(cfg.Inputs.SpellCatalogFile) == "" {
return fmt.Errorf("session.inputs.spell_catalog_file must be non-empty when provided") return configkit.Keys("inputs", "spell_catalog_file"), fmt.Errorf("session.inputs.spell_catalog_file must be non-empty when provided")
} }
hasAudioDir := strings.TrimSpace(cfg.Inputs.AudioDir) != "" hasAudioDir := strings.TrimSpace(cfg.Inputs.AudioDir) != ""
@@ -96,20 +101,20 @@ func validateSession(cfg *SessionConfig) error {
hasAudioS3 := cfg.Inputs.AudioS3 != nil hasAudioS3 := cfg.Inputs.AudioS3 != nil
if hasAudioS3 { if hasAudioS3 {
if strings.TrimSpace(cfg.Inputs.AudioS3.Prefix) == "" { if strings.TrimSpace(cfg.Inputs.AudioS3.Prefix) == "" {
return fmt.Errorf("session.inputs.audio_s3.prefix is required when session.inputs.audio_s3 is configured") return configkit.Keys("inputs", "audio_s3", "prefix"), fmt.Errorf("session.inputs.audio_s3.prefix is required when session.inputs.audio_s3 is configured")
} }
if err := validateRelativeSafePath("session.inputs.audio_s3.prefix", cfg.Inputs.AudioS3.Prefix); err != nil { if err := validateRelativeSafePath("session.inputs.audio_s3.prefix", cfg.Inputs.AudioS3.Prefix); err != nil {
return err return configkit.Keys("inputs", "audio_s3", "prefix"), err
} }
} }
if hasAudioS3 && (hasAudioDir || hasAudioFiles) { if hasAudioS3 && (hasAudioDir || hasAudioFiles) {
return fmt.Errorf("session.inputs.audio_dir/audio_files and session.inputs.audio_s3 are mutually exclusive") return configkit.Keys("inputs", "audio_dir"), fmt.Errorf("session.inputs.audio_dir/audio_files and session.inputs.audio_s3 are mutually exclusive")
} }
if !hasAudioDir && !hasAudioFiles && !hasAudioS3 { if !hasAudioDir && !hasAudioFiles && !hasAudioS3 {
return fmt.Errorf("session.inputs requires audio_dir, at least one audio_files entry, or audio_s3") return configkit.Keys("inputs"), fmt.Errorf("session.inputs requires audio_dir, at least one audio_files entry, or audio_s3")
} }
return nil return configkit.Keys(), nil
} }
func validateResolvedPartyInputs(cfg *Config) error { func validateResolvedPartyInputs(cfg *Config) error {

View File

@@ -24,7 +24,7 @@ func TestPrepareMaterializesImportedDocumentsWithoutAuthoringFiles(t *testing.T)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
session, err := config.LoadSession(env.Config.SessionPath) session, err := config.LoadSessionWithOptions(env.Config.SessionPath, config.SessionLoadOptions{Campaign: campaign, CampaignPath: env.Config.CampaignPath})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -62,7 +62,7 @@ func TestPrepareMaterializesImportedDocumentsWithoutAuthoringFiles(t *testing.T)
t.Fatalf("prepared campaign = %#v, %v", preparedCampaign, err) t.Fatalf("prepared campaign = %#v, %v", preparedCampaign, err)
} }
preparedSession, err := config.LoadSession(filepath.Join(paths.InputsDir, "session.yml")) preparedSession, err := config.LoadSession(filepath.Join(paths.InputsDir, "session.yml"))
if err != nil || preparedSession.Title != "Imported title" || preparedSession.Inputs.SpeakersFile != "" { if err != nil || preparedSession.Title != "Imported title" || preparedSession.Inputs.SpeakersFile != filepath.Join(dir, "speakers.yml") {
t.Fatalf("prepared session = %#v, %v", preparedSession, err) t.Fatalf("prepared session = %#v, %v", preparedSession, err)
} }
record := findManifestInput(t, m.Inputs, "session_config") record := findManifestInput(t, m.Inputs, "session_config")