2026-11-20 05:23:32 +00:00
package app
import (
"context"
"errors"
"fmt"
2026-11-27 16:48:38 +00:00
"path/filepath"
2026-11-20 05:23:32 +00:00
"strings"
2026-11-27 16:48:38 +00:00
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
2026-11-20 05:23:32 +00:00
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
2026-11-27 16:48:38 +00:00
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
2026-11-26 04:29:18 +00:00
"gitea.maximumdirect.net/eric/narratio/internal/preflight"
2026-11-27 16:48:38 +00:00
"gitea.maximumdirect.net/eric/narratio/internal/stage"
2026-11-20 05:23:32 +00:00
"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 } )
2026-11-23 14:23:53 +00:00
flags := [ ] commandkit . Flag [ * sessionInspectionInput ] { common . Config , common . Overlay , common . Campaign , common . CampaignFile , common . SessionFile , common . PartyFile ,
2026-11-20 05:23:32 +00:00
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 {
2026-11-20 05:59:09 +00:00
report , err := validateSelectedSession ( invocation . Context , input , withCommandReporting ( deps , invocation ) )
2026-11-20 05:23:32 +00:00
if report != nil {
err = errors . Join ( err , invocation . Reporter ( ) . Report ( commandkit . Report { Value : report } ) )
}
2026-11-20 15:22:57 +00:00
return reportOperationOutcome ( invocation , err )
2026-11-20 05:23:32 +00:00
}
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 ) ( * sessionValidationReport , error ) {
2026-11-26 04:29:18 +00:00
deps = normalizeCommandDependencies ( deps )
2026-11-20 05:23:32 +00:00
report := & sessionValidationReport { Campaign : cfg . Session . Campaign , SessionID : cfg . Session . SessionID , SessionSource : sessionSourceSummary ( cfg ) , Findings : [ ] finding { } }
var resultErr error
fail := func ( category string , err error ) {
if err != nil {
report . Findings = append ( report . Findings , errorFinding ( category , err . Error ( ) ) )
resultErr = errors . Join ( resultErr , err )
}
}
2026-11-26 04:29:18 +00:00
configErr := config . Validate ( cfg )
if configErr != nil {
fail ( "config" , configErr )
2026-11-20 05:23:32 +00:00
} 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 )
2026-11-26 04:29:18 +00:00
if configErr == nil && effectiveErr == nil {
2026-11-27 16:48:38 +00:00
targets , targetErr := validationDownstreamTargets ( cfg , cfg . Session . SessionID )
2026-11-26 04:29:18 +00:00
if targetErr != nil {
2026-11-27 16:48:38 +00:00
fail ( "preflight" , targetErr )
} else {
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" ) )
paths := artifacts . NewLocalStore ( cfg . Pipeline . Workspace . Root ) . SessionPathsFor ( cfg . Session . Campaign , cfg . Session . SessionID )
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
}
}
}
}
}
checked , checkErr := preflight . CheckDownstream ( ctx , inspector , checker , targets , request )
hasError := false
2026-11-26 04:29:18 +00:00
for _ , item := range checked . Findings {
2026-11-27 16:48:38 +00:00
category , message := "scriptorium" , formatPromptFinding ( item )
if item . Stage == "polish" {
category , message = "audita" , item . Message
}
2026-11-26 04:29:18 +00:00
switch item . Severity {
case preflight . SeverityError :
2026-11-27 16:48:38 +00:00
hasError = true
report . Findings = append ( report . Findings , errorFinding ( category , message ) )
2026-11-26 04:29:18 +00:00
case preflight . SeverityWarning :
2026-11-27 16:48:38 +00:00
report . Findings = append ( report . Findings , warnFinding ( category , message ) )
2026-11-26 04:29:18 +00:00
default :
2026-11-27 16:48:38 +00:00
report . Findings = append ( report . Findings , infoFinding ( category , message ) )
2026-11-26 04:29:18 +00:00
}
}
if checkErr != nil {
resultErr = errors . Join ( resultErr , checkErr )
2026-11-27 16:48:38 +00:00
if ! hasError {
report . Findings = append ( report . Findings , errorFinding ( "preflight" , checkErr . Error ( ) ) )
2026-11-26 04:29:18 +00:00
}
}
}
}
2026-11-20 05:23:32 +00:00
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
}