package config import ( "fmt" "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) { return LoadPipelineWithOptions(path, PipelineLoadOptions{}) } // PipelineLoadOptions carries an optional explicit overlay selection. Nil, // empty, and the exact name "default" select the base configuration. type PipelineLoadOptions struct { Overlay *string Search *configkit.Search } // LoadPipelineWithOptions loads pipeline configuration with strict field // checking and optional named-overlay selection. func LoadPipelineWithOptions(path string, opts PipelineLoadOptions) (*PipelineConfig, error) { cfg, err := loadPipelineWithConfigKit(path, opts) if err != nil { return nil, err } return finalizeLoadedPipeline(cfg) } // LoadPipelineOverlayPair resolves two overlays as independent ConfigKit loads. func LoadPipelineOverlayPair(path, leftOverlay, rightOverlay string) (*PipelineConfig, *PipelineConfig, error) { if leftOverlay == rightOverlay { return nil, nil, fmt.Errorf("load pipeline overlays: left and right overlay selections must differ") } leftOptions := PipelineLoadOptions{Overlay: &leftOverlay} rightOptions := PipelineLoadOptions{Overlay: &rightOverlay} left, err := LoadPipelineWithOptions(path, leftOptions) if err != nil { return nil, nil, fmt.Errorf("load left pipeline overlay: %w", err) } right, err := LoadPipelineWithOptions(path, rightOptions) if err != nil { return nil, nil, fmt.Errorf("load right pipeline overlay: %w", err) } return left, right, nil } func finalizeLoadedPipeline(cfg *PipelineConfig) (*PipelineConfig, error) { if err := finalizePipelineResolution(cfg); err != nil { return nil, fmt.Errorf("load pipeline config: %w", err) } return cfg, nil } // LoadCampaign loads campaign configuration from a YAML file with strict field checking. func LoadCampaign(path string) (*CampaignConfig, error) { return loadCampaignWithConfigKit(path) } // 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 } // LoadSessionBytesWithOptions loads a contextless session snapshot. 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} } } if opts.Campaign != nil && cfg.Campaign != CampaignID(opts.Campaign) { return &SessionIdentityError{Source: label, Field: "campaign", Expected: CampaignID(opts.Campaign), Actual: cfg.Campaign} } return nil } // 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{}) } // LoadWithSessionOptions loads and resolves combined pipeline, campaign, and // session configuration with expected session identity checks. func LoadWithSessionOptions(pipelinePath, campaignPath, sessionPath string, sessionOpts SessionLoadOptions) (*Config, error) { pipelineCfg, err := LoadPipelineWithOptions(pipelinePath, PipelineLoadOptions{Overlay: sessionOpts.Overlay}) if err != nil { return nil, err } 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") } 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 } // 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{ 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") } 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) if err != nil { return nil, err } if strings.TrimSpace(cfg.SessionSource.Source) == "" { cfg.SessionSource.Source = "session_config" } if strings.TrimSpace(cfg.SessionSource.LocalPath) == "" { cfg.SessionSource.LocalPath = sessionPath } stableInputs.PartyFile = ResolvedInputFile{Path: loaded.Party.Source.Path, ConfigPath: loaded.Party.Source.ConfigPath, Source: loaded.Party.Source.Source} cfg.StableInputs = stableInputs return cfg, nil } // 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) } 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) { 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} } 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 } 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, ", "), ) } func shortName(path, fallback string) string { base := filepath.Base(path) if base == "." || base == string(filepath.Separator) { return fallback } return base }