Files
narratio/internal/config/load.go

383 lines
14 KiB
Go
Raw Normal View History

package config
import (
"fmt"
2026-05-02 11:44:15 -05:00
"path/filepath"
"regexp"
"sort"
"strings"
configkit "go.maximumdirect.net/configkit"
)
// LoadPipeline loads pipeline configuration from a YAML file with strict field checking.
func LoadPipeline(path string) (*PipelineConfig, error) {
2026-08-30 13:25:02 +00:00
return LoadPipelineWithOptions(path, PipelineLoadOptions{})
}
// PipelineLoadOptions carries an optional explicit overlay selection. Nil,
2026-09-07 03:54:41 +00:00
// empty, and the exact name "default" select the base configuration.
2026-08-30 13:25:02 +00:00
type PipelineLoadOptions struct {
Overlay *string
Search *configkit.Search
Overrides []configkit.Override
2026-08-30 13:25:02 +00:00
}
// LoadPipelineWithOptions loads pipeline configuration with strict field
// checking and optional named-overlay selection.
2026-08-30 13:25:02 +00:00
func LoadPipelineWithOptions(path string, opts PipelineLoadOptions) (*PipelineConfig, error) {
2026-09-07 03:54:41 +00:00
cfg, err := loadPipelineWithConfigKit(path, opts)
if err != nil {
2026-09-07 03:54:41 +00:00
return nil, err
}
return finalizeLoadedPipeline(cfg)
}
func finalizeLoadedPipeline(cfg *PipelineConfig) (*PipelineConfig, error) {
2026-08-30 13:25:02 +00:00
if err := finalizePipelineResolution(cfg); err != nil {
return nil, fmt.Errorf("load pipeline config: %w", err)
}
return cfg, nil
}
2026-05-20 20:41:28 -05:00
// LoadCampaign loads campaign configuration from a YAML file with strict field checking.
func LoadCampaign(path string) (*CampaignConfig, error) {
return loadCampaignWithConfigKit(path)
2026-05-20 20:41:28 -05:00
}
// LoadSession loads session configuration from a YAML file with strict field checking.
func LoadSession(path string) (*SessionConfig, error) {
return LoadSessionWithOptions(path, SessionLoadOptions{})
}
// SessionLoadOptions supplies campaign defaults and expected session identities.
type SessionLoadOptions struct {
Campaign *CampaignConfig
CampaignPath string
SessionID string
PreviousSessionID string
Overlay *string
}
// LoadSessionWithOptions loads session configuration from a YAML file with
// strict field checking.
func LoadSessionWithOptions(path string, opts SessionLoadOptions) (*SessionConfig, error) {
cfg, _, err := loadSessionSource(configkit.File(path), path, opts, true)
return cfg, err
2026-05-20 20:55:13 -05:00
}
// LoadSessionBytesWithOptions loads a contextless session snapshot.
2026-05-20 20:55:13 -05:00
func LoadSessionBytesWithOptions(label string, data []byte, opts SessionLoadOptions) (*SessionConfig, error) {
cfg, _, err := loadSessionSource(configkit.Bytes(label, data), label, opts, false)
return cfg, err
}
// SessionIdentityError identifies an explicit identity assertion that the
// completed session configuration does not satisfy.
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)
}
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)
}
func validateSessionIdentity(label string, cfg *SessionConfig, opts SessionLoadOptions) error {
for _, assertion := range []struct{ field, expected, actual string }{
{"session_id", opts.SessionID, cfg.SessionID},
{"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}
2026-08-10 21:32:15 +00:00
}
}
if opts.Campaign != nil && cfg.Campaign != CampaignID(opts.Campaign) {
return &SessionIdentityError{Source: label, Field: "campaign", Expected: CampaignID(opts.Campaign), Actual: cfg.Campaign}
}
return nil
}
2026-05-20 20:41:28 -05:00
// Load loads and resolves combined pipeline, campaign, and session configuration.
// Passing only a session path is supported for package-internal compatibility;
// in that form campaign.yml is expected next to the session file.
func Load(pipelinePath string, paths ...string) (*Config, error) {
campaignPath, sessionPath, err := campaignSessionPaths(paths...)
if err != nil {
return nil, err
}
return LoadWithSessionOptions(pipelinePath, campaignPath, sessionPath, SessionLoadOptions{})
}
2026-05-20 20:41:28 -05:00
// LoadWithSessionOptions loads and resolves combined pipeline, campaign, and
// session configuration with expected session identity checks.
2026-05-20 20:41:28 -05:00
func LoadWithSessionOptions(pipelinePath, campaignPath, sessionPath string, sessionOpts SessionLoadOptions) (*Config, error) {
pipelineCfg, err := LoadPipelineWithOptions(pipelinePath, PipelineLoadOptions{Overlay: sessionOpts.Overlay})
if err != nil {
return nil, err
}
2026-05-20 20:41:28 -05:00
campaignCfg, err := LoadCampaign(campaignPath)
if err != nil {
return nil, err
}
loaded, err := LoadPipelineCampaign(pipelinePath, pipelineCfg, campaignPath, campaignCfg)
if err != nil {
return nil, err
}
return LoadSessionWithPipelineCampaignOptions(loaded, sessionPath, sessionOpts)
}
// LoadedPipelineCampaign retains one already loaded pipeline and campaign for
// subsequent local or remote session resolution. It prevents a command from
// reloading the root pipeline after campaign selection.
type LoadedPipelineCampaign struct {
PipelinePath string
Pipeline *PipelineConfig
CampaignPath string
Campaign *CampaignConfig
Party ResolvedParty
ArtifactCatalog *ArtifactCatalog
}
// LoadPipelineCampaign combines already loaded pipeline and campaign documents
// with their campaign-owned party source. Callers that later resolve a session
// retain this context rather than independently reimplementing party loading.
func LoadPipelineCampaign(pipelinePath string, pipeline *PipelineConfig, campaignPath string, campaign *CampaignConfig) (LoadedPipelineCampaign, error) {
return LoadPipelineCampaignWithPartyFile(pipelinePath, pipeline, campaignPath, campaign, nil)
}
// LoadPipelineCampaignWithPartyFile derives domain context using an explicit
// invocation-relative roster file or the campaign's default when omitted.
func LoadPipelineCampaignWithPartyFile(pipelinePath string, pipeline *PipelineConfig, campaignPath string, campaign *CampaignConfig, partyFile *string) (LoadedPipelineCampaign, error) {
if pipeline == nil {
return LoadedPipelineCampaign{}, fmt.Errorf("pipeline config is required")
}
if campaign == nil {
return LoadedPipelineCampaign{}, fmt.Errorf("campaign config is required")
}
party, err := ResolveParty(campaignPath, campaign, partyFile)
if err != nil {
return LoadedPipelineCampaign{}, err
}
return LoadPipelineCampaignWithParty(pipelinePath, pipeline, campaignPath, campaign, party)
}
// LoadPipelineCampaignWithParty combines an already loaded pipeline and
// campaign with one already resolved party. Independently loaded pipelines can
// derive their catalogs against the same selected roster.
func LoadPipelineCampaignWithParty(pipelinePath string, pipeline *PipelineConfig, campaignPath string, campaign *CampaignConfig, party ResolvedParty) (LoadedPipelineCampaign, error) {
if pipeline == nil {
return LoadedPipelineCampaign{}, fmt.Errorf("pipeline config is required")
}
if campaign == nil {
return LoadedPipelineCampaign{}, fmt.Errorf("campaign config is required")
}
2026-09-02 12:04:35 +00:00
if party.Canonical == nil {
return LoadedPipelineCampaign{}, fmt.Errorf("resolved campaign party is required")
}
if party.Players == nil {
players, err := party.Canonical.PlayersYAML()
if err != nil {
return LoadedPipelineCampaign{}, err
}
party.Players = players
}
catalog, err := DeriveArtifactCatalog(pipeline, party)
if err != nil {
return LoadedPipelineCampaign{}, err
}
return LoadedPipelineCampaign{
PipelinePath: pipelinePath,
Pipeline: pipeline,
CampaignPath: campaignPath,
Campaign: campaign,
Party: party,
ArtifactCatalog: catalog,
}, nil
}
2026-05-20 20:41:28 -05:00
// LoadSessionWithPipelineCampaignOptions loads one local session and combines
// it with an already loaded pipeline and campaign.
func LoadSessionWithPipelineCampaignOptions(loaded LoadedPipelineCampaign, sessionPath string, sessionOpts SessionLoadOptions) (*Config, error) {
sessionOpts.Campaign = loaded.Campaign
sessionOpts.CampaignPath = loaded.CampaignPath
sessionCfg, err := LoadSessionWithOptions(sessionPath, sessionOpts)
if err != nil {
return nil, err
}
return ResolveLoadedPipelineCampaign(loaded, sessionPath, sessionCfg, SessionSource{
2026-05-20 20:55:13 -05:00
Source: "session_config",
LocalPath: sessionPath,
})
}
// ResolveLoadedPipelineCampaign combines an already loaded pipeline and
// campaign with optional already loaded session data. A nil session preserves
// the resolved pipeline/campaign context for callers that need to locate or
// retrieve a session without rereading the root pipeline.
func ResolveLoadedPipelineCampaign(loaded LoadedPipelineCampaign, sessionPath string, sessionCfg *SessionConfig, sessionSource SessionSource) (*Config, error) {
if loaded.Pipeline == nil {
return nil, fmt.Errorf("pipeline config is required")
}
if loaded.Campaign == nil {
return nil, fmt.Errorf("campaign config is required")
}
2026-09-02 12:04:35 +00:00
if loaded.Party.Canonical == nil {
party, err := resolveCampaignParty(loaded.CampaignPath, loaded.Campaign)
if err != nil {
return nil, err
}
loaded.Party = party
}
cfg := &Config{
Pipeline: loaded.Pipeline,
Campaign: loaded.Campaign,
Session: sessionCfg,
PipelinePath: loaded.PipelinePath,
CampaignPath: loaded.CampaignPath,
SessionPath: sessionPath,
SessionSource: sessionSource,
Party: loaded.Party,
ArtifactCatalog: loaded.ArtifactCatalog,
}
cfg.CampaignDocument = loaded.Campaign
cfg.SessionDocument = sessionCfg
if sessionCfg == nil {
return cfg, nil
}
stableInputs, err := deriveStableInputs(loaded.Campaign, sessionCfg, loaded.CampaignPath, sessionPath)
2026-05-20 20:41:28 -05:00
if err != nil {
return nil, err
}
if strings.TrimSpace(cfg.SessionSource.Source) == "" {
cfg.SessionSource.Source = "session_config"
2026-05-20 20:55:13 -05:00
}
if strings.TrimSpace(cfg.SessionSource.LocalPath) == "" {
cfg.SessionSource.LocalPath = sessionPath
2026-05-20 20:55:13 -05:00
}
stableInputs.PartyFile = ResolvedInputFile{Path: loaded.Party.Source.Path, ConfigPath: loaded.Party.Source.ConfigPath, Source: loaded.Party.Source.Source}
cfg.StableInputs = stableInputs
return cfg, nil
}
2026-05-20 20:41:28 -05:00
// Resolve builds final stage-facing configuration from already loaded
// pipeline, campaign, and session documents.
func Resolve(pipelinePath string, pipelineCfg *PipelineConfig, campaignPath string, campaignCfg *CampaignConfig, sessionPath string, sessionCfg *SessionConfig, sessionSource SessionSource) (*Config, error) {
if sessionCfg == nil {
return nil, fmt.Errorf("session config is required")
}
loaded, err := LoadPipelineCampaign(pipelinePath, pipelineCfg, campaignPath, campaignCfg)
if err != nil {
return nil, err
}
return ResolveLoadedPipelineCampaign(loaded, sessionPath, sessionCfg, sessionSource)
}
2026-05-20 20:41:28 -05:00
func campaignSessionPaths(paths ...string) (campaignPath, sessionPath string, err error) {
switch len(paths) {
case 1:
sessionPath = paths[0]
campaignPath = filepath.Join(filepath.Dir(sessionPath), "campaign.yml")
case 2:
campaignPath = paths[0]
sessionPath = paths[1]
default:
return "", "", fmt.Errorf("load config: expected session path or campaign and session paths")
}
return campaignPath, sessionPath, nil
}
func deriveStableInputs(campaignCfg *CampaignConfig, sessionCfg *SessionConfig, campaignPath, sessionPath string) (ResolvedStableInputs, error) {
2026-05-20 20:41:28 -05:00
if campaignCfg == nil {
return ResolvedStableInputs{}, fmt.Errorf("campaign config is required")
}
if sessionCfg == nil {
return ResolvedStableInputs{}, fmt.Errorf("session config is required")
}
if sessionCfg.Campaign != CampaignID(campaignCfg) {
return ResolvedStableInputs{}, &SessionIdentityError{Source: sessionPath, Field: "campaign", Expected: CampaignID(campaignCfg), Actual: sessionCfg.Campaign}
2026-05-20 20:41:28 -05:00
}
stable := ResolvedStableInputs{}
for _, field := range []struct {
name, value string
target *ResolvedInputFile
campaignOnly bool
}{
{"speakers_file", sessionCfg.Inputs.SpeakersFile, &stable.SpeakersFile, false},
{"autocorrect_file", sessionCfg.Inputs.AutocorrectFile, &stable.AutocorrectFile, false},
{"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},
} {
reference := ResolvedInputFile{Path: field.value, ConfigPath: sessionPath, Source: "session_config"}
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] != "" {
reference.ConfigPath = metadata.sources["/inputs/"+field.name]
}
*field.target = reference
}
2026-05-20 20:41:28 -05:00
return stable, nil
}
// CampaignID returns the canonical campaign identity from campaign config.
func CampaignID(cfg *CampaignConfig) string {
if cfg == nil {
return ""
}
return strings.TrimSpace(cfg.CampaignID)
}
var sessionTemplatePlaceholderPattern = regexp.MustCompile(`\{\{[^}]*\}\}`)
var sessionTemplateVariablePattern = regexp.MustCompile(`\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}`)
func rejectSessionTemplatePlaceholders(label, content string) error {
placeholders := sessionTemplatePlaceholderPattern.FindAllString(content, -1)
if len(placeholders) == 0 {
return nil
}
seen := map[string]struct{}{}
vars := make([]string, 0, len(placeholders))
for _, placeholder := range placeholders {
name := strings.TrimSpace(placeholder)
if match := sessionTemplateVariablePattern.FindStringSubmatch(placeholder); len(match) > 1 {
name = match[1]
}
if _, ok := seen[name]; ok {
continue
}
seen[name] = struct{}{}
vars = append(vars, name)
}
sort.Strings(vars)
return fmt.Errorf(
"session file %q contains template placeholder(s): %s; session.yml must be concrete; run narratio session init to generate it",
label,
strings.Join(vars, ", "),
)
}
2026-05-02 11:44:15 -05:00
func shortName(path, fallback string) string {
base := filepath.Base(path)
if base == "." || base == string(filepath.Separator) {
return fallback
}
return base
}