package app import ( "context" "errors" "fmt" "os" "path/filepath" "strings" "gitea.maximumdirect.net/eric/narratio/internal/adapters/audita" "gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius" "gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium" "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/preflight" "gitea.maximumdirect.net/eric/narratio/internal/stage" "go.maximumdirect.net/commandkit" ) type sessionInspectionInput struct { Selection configurationSelection PreviousSession commandkit.Supplied[string] Remote commandkit.Supplied[bool] } type sessionValidationReport struct { Campaign string `json:"campaign"` SessionID string `json:"session_id"` SessionSource string `json:"session_source,omitempty"` Valid bool `json:"valid"` Findings []finding `json:"findings"` } func sessionInspectionSpec(name, summary string, remoteOption bool) commandkit.CommandSpec[*sessionInspectionInput] { common := newConfigurationFlags(func(input **sessionInspectionInput) *configurationSelection { return &(*input).Selection }) flags := []commandkit.Flag[*sessionInspectionInput]{common.Config, common.Overlay, common.Campaign, common.CampaignFile, common.SessionFile, common.PartyFile, commandkit.ValueFlag(commandkit.FlagMeta{Name: "previous-session-id", Usage: "Assert the previous session identity."}, nil, stringValue, func(input **sessionInspectionInput, value commandkit.Supplied[string]) { (*input).PreviousSession = value }), } if remoteOption { flags = append(flags, commandkit.BoolFlag(commandkit.FlagMeta{Name: "remote", Usage: "Inspect remote publication and locks."}, false, func(input **sessionInspectionInput, value commandkit.Supplied[bool]) { (*input).Remote = value })) } return commandkit.CommandSpec[*sessionInspectionInput]{Name: name, Summary: summary, NewInput: func() *sessionInspectionInput { return &sessionInspectionInput{} }, Flags: flags, Arguments: []commandkit.Argument[*sessionInspectionInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "SESSION", Usage: "Session identity."}, true, stringValue, func(input **sessionInspectionInput, value commandkit.Supplied[string]) { (*input).Selection.Session = value })}, CheckInput: func(input *sessionInspectionInput) error { return checkConfigurationSelection(input.Selection) }, } } func sessionValidationCommand(deps commandDependencies) commandkit.Command { spec := sessionInspectionSpec("validate", "Check session readiness without executing work.", false) spec.Run = func(invocation commandkit.Invocation, input *sessionInspectionInput) commandkit.Outcome { report, err := validateSelectedSession(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 validateSelectedSession(ctx context.Context, input *sessionInspectionInput, deps commandDependencies) (report *sessionValidationReport, 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 &sessionValidationReport{Campaign: input.Selection.Campaign.Value, SessionID: input.Selection.Session.Value, Findings: []finding{errorFinding("config", err.Error())}}, err } return inspectSessionValidation(ctx, cfg, deps) } func inspectSessionValidation(ctx context.Context, cfg *config.Config, deps commandDependencies) (report *sessionValidationReport, resultErr error) { deps = normalizeCommandDependencies(deps) report = &sessionValidationReport{Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID, SessionSource: sessionSourceSummary(cfg), Findings: []finding{}} fail := func(category string, err error) { if err != nil { report.Findings = append(report.Findings, errorFinding(category, err.Error())) resultErr = errors.Join(resultErr, err) } } configErr := config.Validate(cfg) if configErr != nil { fail("config", configErr) } else { report.Findings = append(report.Findings, okFinding("config", "resolved pipeline, campaign, and session config")) } for _, check := range inspectStableInputs(cfg) { if check.Err != nil { fail("inputs", fmt.Errorf("%s: %w", check.Name, check.Err)) } else { report.Findings = append(report.Findings, okFinding("inputs", check.Name+": "+check.Path)) } } local := inspectLocalAudioPresence(cfg) if local.Checked { if local.Err != nil { fail("audio", local.Err) } else { report.Findings = append(report.Findings, okFinding("audio", fmt.Sprintf("%d local audio file(s)", len(local.Paths)))) } } store, storeErr := objectStoreIfConfiguredWithDependencies(ctx, cfg, deps) fail("storage", storeErr) if cfg.Session.Inputs.AudioS3 != nil { if storeErr != nil { report.Findings = append(report.Findings, errorFinding("audio", "remote audio cannot be checked because storage is unavailable")) } else { remote := inspectRemoteAudioPresence(ctx, cfg, store) if remote.Err != nil { fail("audio", remote.Err) } else { report.Findings = append(report.Findings, okFinding("audio", fmt.Sprintf("%d remote .flac object(s)", len(remote.Keys)))) } } } effective, effectiveErr := resolveEffectiveArtifacts(cfg, nil) fail("config", effectiveErr) if configErr == nil && effectiveErr == nil { targets, targetErr := validationDownstreamTargets(cfg, cfg.Session.SessionID) if targetErr != nil { fail("preflight", targetErr) } else { probeStore := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root) paths := probeStore.SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) if targets.Polish || targets.Notarius { // Check presence only before locking. Prepared evidence is read below // while locked; missing preparation must not bootstrap a workspace. _, statErr := os.Stat(paths.ManifestPath) if statErr == nil { lock, lockErr := probeStore.AcquireSessionLockForContext(ctx, cfg.Session.Campaign, cfg.Session.SessionID) if lockErr != nil { fail("workspace", fmt.Errorf("acquire validation session lock: %w", lockErr)) targets.Polish, targets.Notarius = false, false } else { defer func() { fail("workspace", probeStore.ReleaseSessionLock(lock)) report.Valid = resultErr == nil }() } } else { if errors.Is(statErr, os.ErrNotExist) { if targets.Polish { fail("audita", fmt.Errorf("prepared inputs are unavailable; run prepare")) } if targets.Notarius { fail("notarius", fmt.Errorf("prepared inputs are unavailable; run prepare")) } } else { fail("workspace", fmt.Errorf("inspect prepared manifest: %w", statErr)) } targets.Polish, targets.Notarius = false, false } } var inspector scriptorium.Runner if len(targets.Scriptorium) > 0 { inspector = deps.newScriptorium() } var checker preflight.AuditaChecker var request audita.PolishRequest if targets.Polish { report.Findings = append(report.Findings, infoFinding("audita", "preflight uses a synthetic transcript, probes destinations, and may contact providers")) local, present, loadErr := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, paths.ManifestPath) if loadErr != nil { fail("audita", fmt.Errorf("load prepared manifest; run prepare: %w", loadErr)) targets.Polish = false } else if !present { fail("audita", fmt.Errorf("prepared inputs are unavailable; run prepare")) targets.Polish = false } else if identityErr := (invocationIdentity{Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID}).validateSessionManifest(local); identityErr != nil { fail("audita", fmt.Errorf("prepared manifest is invalid; run prepare: %w", identityErr)) targets.Polish = false } else if local.Stages["prepare"] == nil || local.Stages["prepare"].Status != manifest.StatusSucceeded { fail("audita", fmt.Errorf("prepared inputs are not current; run prepare")) targets.Polish = false } else { root := artifacts.SessionValidationPolishDir(paths) request, _, loadErr = stage.BuildPolishRequest(paths, local, "", filepath.Join(root, "outputs", "transcripts", "polished.json"), filepath.Join(root, "logs"), filepath.Join(root, "debug")) if loadErr != nil { fail("audita", loadErr) targets.Polish = false } else { runner, runnerErr := deps.newAudita(cfg) if runnerErr != nil { fail("audita", runnerErr) targets.Polish = false } else { var ok bool checker, ok = runner.(preflight.AuditaChecker) if !ok || checker == nil { fail("audita", fmt.Errorf("audita runner does not support preflight")) targets.Polish = false } } } } } var native notarius.ReadinessChecker var probe stage.NotariusReadiness if targets.Notarius { local, present, loadErr := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, paths.ManifestPath) switch { case loadErr != nil: fail("notarius", fmt.Errorf("load prepared manifest; run prepare: %w", loadErr)) targets.Notarius = false case !present: fail("notarius", fmt.Errorf("prepared inputs are unavailable; run prepare")) targets.Notarius = false default: identityErr := (invocationIdentity{Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID}).validateSessionManifest(local) if identityErr != nil { fail("notarius", fmt.Errorf("prepared manifest is invalid; run prepare: %w", identityErr)) targets.Notarius = false } else if local.Stages["prepare"] == nil || local.Stages["prepare"].Status != manifest.StatusSucceeded { fail("notarius", fmt.Errorf("prepared inputs are not current; run prepare")) targets.Notarius = false } else { probe, loadErr = stage.BuildNotariusReadiness(cfg, paths, local, artifacts.SessionValidationNotariusDir(paths), true, false) if loadErr != nil { fail("notarius", loadErr) targets.Notarius = false } else { var ok bool native, ok = deps.newNotarius().(notarius.ReadinessChecker) if !ok || native == nil { fail("notarius", fmt.Errorf("notarius runner does not support preflight")) targets.Notarius = false } } } } } checked, checkErr := preflight.Check(ctx, inspector, targets.Scriptorium) if targets.Polish && ctx.Err() == nil { auditaResult, auditaErr := preflight.CheckAudita(ctx, checker, request) checked.Findings = append(checked.Findings, auditaResult.Findings...) checkErr = errors.Join(checkErr, auditaErr) } if targets.Notarius && ctx.Err() == nil { nativeResult, nativeErr := preflight.CheckNotarius(ctx, native, probe.Request) checked.Findings = append(checked.Findings, nativeResult.Findings...) if verifyErr := probe.VerifyReferences(); verifyErr != nil { nativeErr = errors.Join(nativeErr, fmt.Errorf("verify Notarius probe references: %w", verifyErr)) } checkErr = errors.Join(checkErr, nativeErr) } hasError := false for _, item := range checked.Findings { category, message := "scriptorium", formatPromptFinding(item) if item.Stage == "polish" { category, message = "audita", item.Message } else if item.Stage == "extract" { category, message = "notarius", item.Message } switch item.Severity { case preflight.SeverityError: hasError = true report.Findings = append(report.Findings, errorFinding(category, message)) case preflight.SeverityWarning: report.Findings = append(report.Findings, warnFinding(category, message)) default: report.Findings = append(report.Findings, infoFinding(category, message)) } } if checkErr != nil { resultErr = errors.Join(resultErr, checkErr) if !hasError { report.Findings = append(report.Findings, errorFinding("preflight", checkErr.Error())) } } } } if effectiveErr == nil { previous := inspectPreviousArtifactReadiness(ctx, cfg, store, artifacts.CollectPreviousArtifactRequirements(configuredScriptoriumArtifacts(cfg), effective)) if len(previous.Requirements) == 0 { report.Findings = append(report.Findings, okFinding("previous", "no previous-session artifacts required")) } else if previous.Err != nil { fail("previous", previous.Err) } else { for _, requirement := range previous.Requirements { message := fmt.Sprintf("%s required=%t", requirement.Name, requirement.Required) if !requirement.Required && previousRequirementSkipped(previous.SkippedMissing, requirement.Name) { message += " unavailable" } report.Findings = append(report.Findings, okFinding("previous", message)) } } } locks := inspectRemoteLocks(ctx, cfg, store) if locks.Err != nil { fail("locks", locks.Err) } else if len(locks.Locks) == 0 { report.Findings = append(report.Findings, okFinding("locks", "no publish locks")) } else { for _, lock := range locks.Locks { report.Findings = append(report.Findings, warnFinding("locks", fmt.Sprintf("%s locked: %s", lock.Source, strings.TrimSpace(lock.Reason)))) } } paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) report.Findings = append(report.Findings, infoFinding("workspace", "manifest path: "+paths.ManifestPath)) report.Valid = resultErr == nil return report, resultErr }