package app import ( "context" "errors" "fmt" "strings" "gitea.maximumdirect.net/eric/narratio/internal/adapters/storage" "gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/config" "gitea.maximumdirect.net/eric/narratio/internal/manifest" "gitea.maximumdirect.net/eric/narratio/internal/stage" "go.maximumdirect.net/commandkit" ) type sessionPlanReport struct { Campaign string `json:"campaign"` SessionID string `json:"session_id"` Stages []plannedStage `json:"stages"` Publication []plannedPublication `json:"publication_actions"` ReferencePreparation *preparationAssessment `json:"reference_preparation,omitempty"` InputIssues []string `json:"input_issues,omitempty"` } type plannedStage struct { Name string `json:"name"` Action string `json:"action"` Reason string `json:"reason"` Analysis *plannedAnalysis `json:"analysis,omitempty"` } type plannedAnalysis struct { Targets []string `json:"targets"` Prerequisites []plannedArtifact `json:"prerequisites"` Execute []plannedArtifact `json:"execute"` Reuse []plannedArtifact `json:"reuse"` } type plannedArtifact struct { Key string `json:"key"` Family string `json:"family,omitempty"` CharacterID string `json:"character_id,omitempty"` Role string `json:"role"` Reason string `json:"reason"` Forced bool `json:"forced"` } type plannedPublication struct { Source string `json:"source"` Destination string `json:"destination"` Required bool `json:"required"` Selected bool `json:"selected"` } func analysisPlanReport(summary *stage.AnalyzeResumeSummary) *plannedAnalysis { convert := func(items []stage.AnalyzeResumeArtifact) []plannedArtifact { out := make([]plannedArtifact, 0, len(items)) for _, item := range items { out = append(out, plannedArtifact{Key: item.Key, Family: item.Family, CharacterID: item.CharacterID, Role: item.Role, Reason: item.Reason, Forced: item.Forced}) } return out } return &plannedAnalysis{Targets: append([]string(nil), summary.ExplicitTargets...), Prerequisites: convert(summary.PrerequisiteWork), Execute: convert(summary.ExecutionOrder), Reuse: convert(summary.ReusedCurrent)} } func sessionPlanCommand(deps commandDependencies) commandkit.Command { spec := executionCommandSpec("plan", "Preview session work without executing it.", false) spec.Run = func(invocation commandkit.Invocation, input *executionInput) commandkit.Outcome { report, err := planSelectedPipeline(invocation.Context, input, withCommandReporting(deps, invocation)) if report != nil { err = errors.Join(err, invocation.Reporter().Report(commandkit.Report{Value: report})) } return reportOperationOutcome(invocation, err) } return commandkit.NewCommand(spec) } func planSelectedPipeline(ctx context.Context, input *executionInput, deps commandDependencies) (report *sessionPlanReport, err error) { deps = normalizeCommandDependencies(deps) acquired := newConfigurationAcquisition(input.Selection, deps) acquired.previousSessionID = input.PreviousSession.Value defer func() { err = errors.Join(err, acquired.Close()) }() cfg, err := acquired.Domain(ctx) if err != nil { return nil, err } if err := config.Validate(cfg); err != nil { return nil, err } selected, err := normalizeArtifactSelection(cfg, input.selectedArtifacts) if err != nil { return nil, &inputError{message: err.Error(), cause: err} } effective, err := resolveEffectiveArtifacts(cfg, selected) if err != nil { return nil, &inputError{message: err.Error(), cause: err} } return buildSessionPlan(ctx, cfg, input, selected, effective, deps) } func buildSessionPlan(ctx context.Context, cfg *config.Config, input *executionInput, selectedArtifacts []string, effective artifacts.EffectiveArtifactSet, deps commandDependencies) (*sessionPlanReport, error) { if err := ctx.Err(); err != nil { return nil, err } m, err := loadManifestIfPresent(ctx, cfg) if err != nil { return nil, fmt.Errorf("plan: %w", err) } if err := validateBoundedPrerequisites(input.plan, m, cfg); err != nil { return nil, fmt.Errorf("plan: %w", err) } var objectStore storage.ObjectStore if input.plan.Contains("prepare") && !input.Force.Value && !suppliedCompletion(cfg, m)["transcribe"] && cfg.Session.Inputs.AudioS3 != nil && recordedStageStatus(m, "prepare") == manifest.StatusSucceeded { objectStore, err = newCommandObjectStoreWithDependencies(ctx, cfg, deps) if err != nil { return nil, fmt.Errorf("plan: %w", err) } } store := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root) projection, err := projectSelectedWork(ctx, cfg, input.plan, input.Force.Value, selectedArtifacts, effective, store, objectStore, m) if projection == nil { return nil, err } report := &sessionPlanReport{Campaign: config.CampaignID(cfg.Campaign), SessionID: cfg.Session.SessionID, Stages: []plannedStage{}, Publication: []plannedPublication{}} if m != nil && !input.plan.Contains("prepare") && suppliedCompletion(cfg, m)["transcribe"] && projectionNeedsReferences(projection) { report.ReferencePreparation = &preparationAssessment{Outcome: "planned", Reason: "reference-only preparation before downstream work"} current, checkErr := referencePreparationCurrent(ctx, cfg, m, store, effective) if checkErr != nil { return report, checkErr } if current { report.ReferencePreparation = &preparationAssessment{Outcome: "reused", Reason: "prepared references are current"} } env := &stage.Env{Config: cfg, ArtifactStore: store, EffectiveArtifacts: effective} if validationErr := stage.ValidateReferenceSources(ctx, env, m); !current && validationErr != nil { report.ReferencePreparation.Outcome = "blocked" report.ReferencePreparation.Reason = validationErr.Error() } requirements, requirementErr := artifacts.CollectPreviousArtifactRequirements(configuredScriptoriumArtifacts(cfg), effective) if requirementErr != nil { return report, requirementErr } if strings.TrimSpace(cfg.Session.PreviousSessionID) == "" { for _, requirement := range requirements { if requirement.Required { report.InputIssues = append(report.InputIssues, fmt.Sprintf("previous_session_id is required for previous artifact %q", requirement.Name)) } } } } report.InputIssues = append(report.InputIssues, unavailablePlannedBuiltIns(cfg, m, projection)...) for _, item := range projection.Stages { entry := plannedStage{Name: item.Name, Action: string(item.Decision.action), Reason: item.Reason} if item.Analysis != nil { entry.Analysis = analysisPlanReport(item.Analysis) } report.Stages = append(report.Stages, entry) } if err != nil { return report, err } model := projection.Model if input.plan.Contains("publish") && cfg.Pipeline.Publish != nil && (cfg.Pipeline.Publish.Enabled == nil || *cfg.Pipeline.Publish.Enabled) { catalog, err := buildHelperArtifactCatalog(cfg, model) if err != nil { return nil, err } actions, err := stage.PlanPublicationOutputs(catalog, cfg.PublicationOutputs(), selectedArtifacts) if err != nil { return nil, err } for _, action := range actions { report.Publication = append(report.Publication, plannedPublication{Source: action.Source, Destination: action.Destination, Required: action.Required, Selected: action.Selected}) } } return report, ctx.Err() }