2026-11-30 15:19:22 +00:00
package app
import (
2026-12-02 14:34:00 +00:00
"bytes"
2026-11-30 15:19:22 +00:00
"context"
"errors"
2026-12-02 14:34:00 +00:00
"fmt"
2026-11-30 15:19:22 +00:00
"os"
"path/filepath"
2026-12-02 13:12:01 +00:00
"strings"
2026-11-30 15:19:22 +00:00
"testing"
2026-11-30 15:29:28 +00:00
"time"
2026-11-30 15:19:22 +00:00
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
2026-11-30 15:29:28 +00:00
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
2026-11-30 15:19:22 +00:00
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
2026-11-30 15:42:21 +00:00
"gitea.maximumdirect.net/eric/narratio/internal/stage"
2026-11-30 15:19:22 +00:00
"go.maximumdirect.net/commandkit"
)
func readinessInput ( pipeline , campaign , session string ) * sessionInspectionInput {
return & sessionInspectionInput { Selection : configurationSelection { Config : commandkit . Supplied [ string ] { Value : pipeline , Set : true } , CampaignFile : commandkit . Supplied [ string ] { Value : campaign , Set : true } , SessionFile : commandkit . Supplied [ string ] { Value : session , Set : true } , Session : commandkit . Supplied [ string ] { Value : "2026-05-03" , Set : true } } }
}
func TestSessionReadinessPreparesAndRepeatsChecks ( t * testing . T ) {
root := t . TempDir ( )
pipeline , campaign , session := writeValidConfigFiles ( t , root )
provider := & audita . FakeRunner { }
deps := fakeCommandDependencies ( & storage . FakeBackend { } , nil )
deps . newAudita = func ( * config . Config ) ( audita . Runner , error ) { return provider , nil }
input := readinessInput ( pipeline , campaign , session )
first , err := preflightSelectedSession ( context . Background ( ) , input , deps )
if err != nil || ! first . Ready || first . Preparation . Outcome != "completed" || len ( provider . PreflightRequests ) != 1 {
t . Fatalf ( "first=%+v error=%v" , first , err )
}
second , err := preflightSelectedSession ( context . Background ( ) , input , deps )
if err != nil || ! second . Ready || second . Preparation . Outcome != "reused" || len ( provider . PreflightRequests ) != 2 {
t . Fatalf ( "second=%+v error=%v" , second , err )
}
failure := errors . New ( "synthetic provider failure" )
provider . PreflightErr = failure
failed , err := preflightSelectedSession ( context . Background ( ) , input , deps )
if ! errors . Is ( err , failure ) || failed . Ready || failed . Preparation . Outcome != "reused" {
t . Fatalf ( "failure=%+v error=%v" , failed , err )
}
cfg , err := config . LoadWithSessionOptions ( pipeline , campaign , session , config . SessionLoadOptions { } )
if err != nil {
t . Fatal ( err )
}
m , err := ( & manifest . LocalStore { } ) . Load ( context . Background ( ) , manifestPathFor ( cfg ) )
if err != nil || m . Stages [ "prepare" ] . Status != manifest . StatusSucceeded {
t . Fatalf ( "manifest=%+v error=%v" , m , err )
}
}
func TestSessionReadinessBlocksPreparedProbesButKeepsIndependentFindings ( t * testing . T ) {
pipeline , campaign , session := writeValidConfigFilesWithScriptoriumArtifacts ( t , t . TempDir ( ) )
if err := os . Remove ( filepath . Join ( filepath . Dir ( session ) , "audio" , "alice.flac" ) ) ; err != nil {
t . Fatal ( err )
}
provider := & audita . FakeRunner { }
inspector := & scriptorium . FakeRunner { RequirementsResult : & scriptorium . RequirementsReport { Complete : false } }
deps := fakeCommandDependencies ( & storage . FakeBackend { } , nil )
deps . newAudita = func ( * config . Config ) ( audita . Runner , error ) { return provider , nil }
deps . newScriptorium = func ( ) scriptorium . Runner { return inspector }
report , err := preflightSelectedSession ( context . Background ( ) , readinessInput ( pipeline , campaign , session ) , deps )
if err == nil || report . Ready || report . Preparation . Outcome != "failed" || len ( provider . PreflightRequests ) != 0 || len ( inspector . RequirementsRequests ) == 0 || ! findingMatches ( report . Findings , "WARN" , "scriptorium" , "incomplete" ) {
t . Fatalf ( "report=%+v error=%v" , report , err )
}
found := false
for _ , check := range report . Checks {
if check . Group == "audita" && check . Outcome == "blocked" {
found = true
}
}
if ! found {
t . Fatalf ( "checks=%+v" , report . Checks )
}
}
2026-11-30 15:29:28 +00:00
func TestPreflightInvalidatesChangedInputsButNotProbeFailures ( t * testing . T ) {
pipeline , campaign , session := writeValidConfigFiles ( t , t . TempDir ( ) )
cfg , err := config . LoadWithSessionOptions ( pipeline , campaign , session , config . SessionLoadOptions { } )
if err != nil {
t . Fatal ( err )
}
provider := & audita . FakeRunner { }
deps := fakeCommandDependencies ( & storage . FakeBackend { } , nil )
deps . newAudita = func ( * config . Config ) ( audita . Runner , error ) { return provider , nil }
first , err := inspectConfiguredForTest ( context . Background ( ) , cfg , deps )
if err != nil || first . Preparation . Outcome != "completed" {
t . Fatalf ( "first=%+v error=%v" , first , err )
}
store := & manifest . LocalStore { }
m , err := store . Load ( context . Background ( ) , manifestPathFor ( cfg ) )
if err != nil {
t . Fatal ( err )
}
m . MarkStageSucceeded ( "polish" , time . Now ( ) . UTC ( ) , nil )
m . Stages [ "polish" ] . Metadata = map [ string ] any { "sentinel" : "prior success" }
if err := store . Save ( context . Background ( ) , manifestPathFor ( cfg ) , m ) ; err != nil {
t . Fatal ( err )
}
failure := errors . New ( "provider unavailable" )
provider . PreflightErr = failure
failed , err := inspectConfiguredForTest ( context . Background ( ) , cfg , deps )
if ! errors . Is ( err , failure ) || failed . Ready || failed . Preparation . Outcome != "reused" {
t . Fatalf ( "failed=%+v error=%v" , failed , err )
}
after , err := store . Load ( context . Background ( ) , manifestPathFor ( cfg ) )
if err != nil || after . Stages [ "polish" ] . Status != manifest . StatusSucceeded || after . Stages [ "polish" ] . Metadata [ "sentinel" ] != "prior success" {
t . Fatalf ( "state=%+v error=%v" , after , err )
}
if err := os . WriteFile ( cfg . StableInputs . SpeakersFile . Path , [ ] byte ( "match:\n - speaker: Bob\n match: [bob]\n" ) , 0644 ) ; err != nil {
t . Fatal ( err )
}
provider . PreflightErr = nil
changed , err := inspectConfiguredForTest ( context . Background ( ) , cfg , deps )
if err != nil || changed . Preparation . Outcome != "completed" {
t . Fatalf ( "changed=%+v error=%v" , changed , err )
}
after , err = store . Load ( context . Background ( ) , manifestPathFor ( cfg ) )
if err != nil || after . Stages [ "polish" ] . Status != manifest . StatusStale {
t . Fatalf ( "changed state=%+v error=%v" , after , err )
}
var runs int
calls := len ( provider . PreflightRequests )
plan , err := BuildBoundedPlan ( "prepare" , "prepare" )
if err != nil {
t . Fatal ( err )
}
plan . stages = append ( plan . stages , countingStage { name : "polish" , runs : & runs } )
summary , err := executePlanWithDependencies ( context . Background ( ) , cfg , plan , RunOptions { Env : & Env { Audita : provider } } , invocationDependencies { } )
if err != nil || summary . StageResults [ 0 ] . Outcome != "reused" || runs != 1 || len ( provider . PreflightRequests ) != calls + 1 {
t . Fatalf ( "run=%+v calls=%d error=%v" , summary , len ( provider . PreflightRequests ) , err )
}
}
func TestPreflightReportsPreparationPersistenceAndFinalizationFailures ( t * testing . T ) {
for _ , failureAt := range [ ] string { "preparation" , "terminal" } {
t . Run ( failureAt , func ( t * testing . T ) {
pipeline , campaign , session := writeValidConfigFiles ( t , t . TempDir ( ) )
cfg , err := config . LoadWithSessionOptions ( pipeline , campaign , session , config . SessionLoadOptions { } )
if err != nil {
t . Fatal ( err )
}
providerFailure := errors . New ( "provider failure" )
terminalFailure := errors . New ( "terminal save failure" )
releaseFailure := errors . New ( "release failure" )
provider := & audita . FakeRunner { }
deps := fakeCommandDependencies ( & storage . FakeBackend { } , nil )
deps . newAudita = func ( * config . Config ) ( audita . Runner , error ) { return provider , nil }
deps = normalizeCommandDependencies ( deps )
var mstore manifest . Store = & manifest . LocalStore { }
if failureAt == "preparation" {
mstore = & successfulStageSaveFailingStore { delegate : mstore , stageName : "prepare" , dependent : "polish" }
} else {
provider . PreflightErr = providerFailure
mstore = & terminalCountingStore { Store : mstore , terminalErr : terminalFailure }
}
local := & releaseErrorArtifactStore { Store : artifacts . NewLocalStore ( cfg . Pipeline . Workspace . Root ) , err : releaseFailure }
plan , err := BuildBoundedPlan ( "prepare" , "prepare" )
if err != nil {
t . Fatal ( err )
}
report := & sessionReadinessReport { Preparation : preparationAssessment { Outcome : "not_attempted" } }
invDeps := invocationDependencies { newAudita : deps . newAudita , newScriptorium : deps . newScriptorium , newNotarius : deps . newNotarius }
2026-11-30 17:11:00 +00:00
result , err := withLockedInvocation ( context . Background ( ) , cfg , plan , RunOptions { Env : & Env { ManifestStore : mstore , ArtifactStore : local } } , invDeps , func ( runtime * invocationRuntime ) error { return assessSessionReadiness ( runtime , report , deps ) } )
if result == nil || ! errors . Is ( err , releaseFailure ) {
t . Fatalf ( "result=%+v report=%+v error=%v" , result , report , err )
2026-11-30 15:29:28 +00:00
}
if failureAt == "preparation" {
if report . Preparation . Outcome != "failed" || len ( provider . PreflightRequests ) != 0 {
t . Fatalf ( "report=%+v calls=%d" , report , len ( provider . PreflightRequests ) )
}
} else if ! errors . Is ( err , providerFailure ) || ! errors . Is ( err , terminalFailure ) || report . Preparation . Outcome != "completed" {
t . Fatalf ( "report=%+v error=%v" , report , err )
}
} )
}
}
func TestPreflightDoesNotProbeSupersededPreparationAfterFailure ( t * testing . T ) {
pipeline , campaign , session := writeValidConfigFiles ( t , t . TempDir ( ) )
provider := & audita . FakeRunner { }
deps := fakeCommandDependencies ( & storage . FakeBackend { } , nil )
deps . newAudita = func ( * config . Config ) ( audita . Runner , error ) { return provider , nil }
input := readinessInput ( pipeline , campaign , session )
first , err := preflightSelectedSession ( context . Background ( ) , input , deps )
if err != nil || first . Preparation . Outcome != "completed" || len ( provider . PreflightRequests ) != 1 {
t . Fatalf ( "first=%+v error=%v" , first , err )
}
if err := os . Remove ( filepath . Join ( filepath . Dir ( session ) , "audio" , "alice.flac" ) ) ; err != nil {
t . Fatal ( err )
}
failed , err := preflightSelectedSession ( context . Background ( ) , input , deps )
if err == nil || failed . Ready || failed . Preparation . Outcome != "failed" || len ( provider . PreflightRequests ) != 1 {
t . Fatalf ( "failed=%+v calls=%d error=%v" , failed , len ( provider . PreflightRequests ) , err )
}
}
2026-11-30 15:42:21 +00:00
func TestPreflightCannotSucceedWithoutPreparedEvidence ( t * testing . T ) {
cfg := testConfig ( t )
deps := normalizeCommandDependencies ( fakeCommandDependencies ( & storage . FakeBackend { } , nil ) )
report := & sessionReadinessReport { Preparation : preparationAssessment { Outcome : "not_attempted" } }
plan := BoundedPlan { stages : [ ] stage . Stage { resultStage { name : "prepare" , result : & stage . StageResult { Disposition : stage . StageDispositionSkipped , SkipReason : "no inputs" } } } }
2026-11-30 17:11:00 +00:00
result , err := withLockedInvocation ( context . Background ( ) , cfg , plan , RunOptions { } , invocationDependencies { newAudita : deps . newAudita , newScriptorium : deps . newScriptorium } , func ( runtime * invocationRuntime ) error {
2026-11-30 15:42:21 +00:00
return assessSessionReadiness ( runtime , report , deps )
} )
2026-11-30 17:11:00 +00:00
if err == nil || result == nil || report . Preparation . Outcome != "failed" {
t . Fatalf ( "result=%+v report=%+v error=%v" , result , report , err )
2026-11-30 15:42:21 +00:00
}
}
func TestPreflightReportsOptionalPreviousInputsAcrossReuse ( t * testing . T ) {
pipeline , campaign , session := writeValidConfigFilesWithScriptoriumArtifacts ( t , t . TempDir ( ) )
cfg , err := config . LoadWithSessionOptions ( pipeline , campaign , session , config . SessionLoadOptions { } )
if err != nil {
t . Fatal ( err )
}
artifact := cfg . ArtifactCatalog . Artifacts [ "player_handout" ]
artifact . Inputs [ "recap" ] = config . ScriptoriumInputConfig { Source : "narratio.previous_session.artifact.session_recap" , Required : false }
cfg . ArtifactCatalog . Artifacts [ "player_handout" ] = artifact
deps := fakeCommandDependencies ( & storage . FakeBackend { } , nil )
for _ , want := range [ ] string { "completed" , "reused" } {
report , err := inspectConfiguredForTest ( context . Background ( ) , cfg , deps )
if err != nil || ! report . Ready || report . Preparation . Outcome != want || ! findingMatches ( report . Findings , "INFO" , "previous" , "session_recap" ) {
t . Fatalf ( "report=%+v error=%v" , report , err )
}
}
}
2026-12-02 13:12:01 +00:00
type cancelAudioListingStore struct {
storage . ObjectStore
cancel context . CancelFunc
}
func ( s cancelAudioListingStore ) List ( ctx context . Context , prefix string ) ( [ ] storage . ObjectInfo , error ) {
if strings . Contains ( prefix , "/audio/" ) {
s . cancel ( )
return nil , ctx . Err ( )
}
return s . ObjectStore . List ( ctx , prefix )
}
func TestSessionReadinessChecksS3PreparationEvidence ( t * testing . T ) {
pipeline , campaign , session := writeValidConfigFiles ( t , t . TempDir ( ) )
replaceInFileOrFatal ( t , session , "audio_dir: ./audio" , "audio_s3:\n prefix: audio/" )
cfg , err := config . LoadWithSessionOptions ( pipeline , campaign , session , config . SessionLoadOptions { } )
if err != nil {
t . Fatal ( err )
}
key := artifacts . S3SessionPrefix ( cfg . Pipeline . Storage . S3 . RootPrefix , cfg . Session . Campaign , cfg . Session . SessionID ) + "audio/alice.flac"
remote := & storage . FakeBackend { }
remote . SeedObject ( storage . FakeObject { Key : key , Data : [ ] byte ( "original" ) } )
provider := & audita . FakeRunner { }
deps := fakeCommandDependencies ( remote , nil )
deps . newAudita = func ( * config . Config ) ( audita . Runner , error ) { return provider , nil }
input := readinessInput ( pipeline , campaign , session )
first , err := preflightSelectedSession ( context . Background ( ) , input , deps )
if err != nil || ! first . Ready || first . Preparation . Outcome != "completed" {
t . Fatalf ( "first=%+v error=%v" , first , err )
}
store := & manifest . LocalStore { }
m , err := store . Load ( context . Background ( ) , manifestPathFor ( cfg ) )
if err != nil {
t . Fatal ( err )
}
m . MarkStageSucceeded ( "polish" , time . Now ( ) . UTC ( ) , nil )
if err := store . Save ( context . Background ( ) , manifestPathFor ( cfg ) , m ) ; err != nil {
t . Fatal ( err )
}
reads := len ( remote . Reads )
reused , err := preflightSelectedSession ( context . Background ( ) , input , deps )
if err != nil || ! reused . Ready || reused . Preparation . Outcome != "reused" || len ( remote . Reads ) != reads {
t . Fatalf ( "reuse=%+v error=%v" , reused , err )
}
providerErr := errors . New ( "provider unavailable after reuse" )
provider . PreflightErr = providerErr
failedProvider , err := preflightSelectedSession ( context . Background ( ) , input , deps )
if ! errors . Is ( err , providerErr ) || failedProvider . Ready || failedProvider . Preparation . Outcome != "reused" {
t . Fatalf ( "provider=%+v error=%v" , failedProvider , err )
}
provider . PreflightErr = nil
ctx , cancel := context . WithCancel ( context . Background ( ) )
cancelDeps := deps
cancelDeps . newObjectStore = func ( context . Context , * config . Config ) ( storage . ObjectStore , error ) {
return cancelAudioListingStore { ObjectStore : remote , cancel : cancel } , nil
}
cancelled , err := preflightSelectedSession ( ctx , input , cancelDeps )
cancel ( )
if ! errors . Is ( err , context . Canceled ) || cancelled . Ready {
t . Fatalf ( "cancelled=%+v error=%v" , cancelled , err )
}
remote . SeedObject ( storage . FakeObject { Key : key , Data : [ ] byte ( "changed audio" ) } )
changed , err := preflightSelectedSession ( context . Background ( ) , input , deps )
if err != nil || ! changed . Ready || changed . Preparation . Outcome != "completed" {
t . Fatalf ( "changed=%+v error=%v" , changed , err )
}
m , err = store . Load ( context . Background ( ) , manifestPathFor ( cfg ) )
if err != nil || m . Stages [ "polish" ] . Status != manifest . StatusStale {
t . Fatalf ( "state=%+v error=%v" , m , err )
}
found := false
for _ , record := range m . Inputs {
if record . Kind == "audio" && record . S3Key == key && record . S3ETag == remote . Objects [ key ] . ETag && record . S3Size == int64 ( len ( "changed audio" ) ) {
found = true
}
}
if ! found {
t . Fatalf ( "new S3 evidence missing: %+v" , m . Inputs )
}
outage := errors . New ( "synthetic S3 access failure" )
remote . ListErr = outage
failed , err := preflightSelectedSession ( context . Background ( ) , input , deps )
if ! errors . Is ( err , outage ) || failed . Ready || failed . Preparation . Outcome != "failed" || ! strings . Contains ( failed . Preparation . Reason , "could not be verified" ) || ! strings . Contains ( err . Error ( ) , "synthetic S3 access failure" ) {
t . Fatalf ( "access failure=%+v error=%v" , failed , err )
}
}
2026-12-02 14:34:00 +00:00
func TestReadinessHydratesPrerequisiteHistory ( t * testing . T ) {
for _ , required := range [ ] bool { true , false } {
t . Run ( fmt . Sprintf ( "required=%v" , required ) , func ( t * testing . T ) {
pipeline , campaign , session := writeValidConfigFiles ( t , t . TempDir ( ) )
appendRestoreWorkflowPreviousInputConfig ( t , pipeline , session )
if ! required {
data , err := os . ReadFile ( pipeline )
if err != nil {
t . Fatal ( err )
}
data = bytes . Replace ( data , [ ] byte ( " required: true\n child:" ) , [ ] byte ( " required: false\n child:" ) , 1 )
if err := os . WriteFile ( pipeline , data , 0600 ) ; err != nil {
t . Fatal ( err )
}
}
cfg , err := config . LoadWithSessionOptions ( pipeline , campaign , session , config . SessionLoadOptions { } )
if err != nil {
t . Fatal ( err )
}
store := & storage . FakeBackend { }
seedRestorePreviousCurrent ( t , store , cfg , "# previous recap\n" )
deps := fakeCommandDependencies ( store , nil )
status , err := inspectSessionState ( context . Background ( ) , cfg , true , true , deps )
if err != nil {
t . Fatal ( err )
}
if len ( status . Previous ) != 1 || status . Previous [ 0 ] . Name != "session_recap" || status . Previous [ 0 ] . Required != required || status . Previous [ 0 ] . State != "ready" {
t . Fatalf ( "previous readiness = %#v" , status . Previous )
}
report , err := preflightSelectedSession ( context . Background ( ) , readinessInput ( pipeline , campaign , session ) , deps )
if err != nil || ! report . Ready || report . Preparation . Outcome != "completed" {
t . Fatalf ( "preflight = %+v, error = %v" , report , err )
}
paths := artifacts . NewLocalStore ( cfg . Pipeline . Workspace . Root ) . SessionPathsFor ( cfg . Session . Campaign , cfg . Session . SessionID )
mustReadEquals ( t , filepath . Join ( paths . PreviousArtifactsDir , "session_recap.md" ) , "# previous recap\n" )
} )
}
}