Files
narratio/internal/app/reference_preparation_test.go

248 lines
11 KiB
Go
Raw Normal View History

package app
import (
"bytes"
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/seriatim"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
func TestBoundedAnalysisPreparesReferencesForSuppliedTranscript(t *testing.T) {
root := t.TempDir()
pipeline, campaign, session := writeValidConfigFilesWithScriptoriumArtifacts(t, root)
cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{})
if err != nil {
t.Fatal(err)
}
cfg.Session.Inputs.AudioDir = ""
cfg.Session.Inputs.AudioFiles = nil
cfg.Session.Inputs.AudioS3 = nil
cfg.ArtifactCatalog.Artifacts = map[string]config.ScriptoriumArtifactConfig{"recap": {Enabled: true, PromptID: "dnd.recap", OutputPath: "artifacts/recap.md", Inputs: map[string]config.ScriptoriumInputConfig{"party": {Source: artifactpolicy.SourceInputParty, Required: true}, "transcript": {Source: artifacts.ArtifactTranscriptFinalTrimmed, Required: true}}}}
paths := artifacts.NewLocalStore(root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
transcript := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed))
if err := os.MkdirAll(filepath.Dir(transcript), 0755); err != nil {
t.Fatal(err)
}
body := []byte(`{"segments":[]}`)
if err := os.WriteFile(transcript, body, 0600); err != nil {
t.Fatal(err)
}
checksum, err := artifacts.SHA256File(transcript)
if err != nil {
t.Fatal(err)
}
m := manifest.New(cfg.Session.SessionID, time.Now())
m.Campaign = cfg.Session.Campaign
m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{artifacts.ArtifactTranscriptFinalTrimmed: {Path: artifacts.TranscriptPathFinalTrimmed, Checksum: checksum, Size: int64(len(body))}}}
saveBoundedManifest(t, cfg, m)
plan := mustBoundedPlan(t, "analyze", "analyze")
fake := &scriptorium.FakeRunner{}
result, err := executePlan(context.Background(), cfg, plan, RunOptions{Env: &Env{Scriptorium: fake}})
if err != nil {
t.Fatal(err)
}
if len(fake.RunRequests) != 1 {
t.Fatalf("requests %+v", fake.RunRequests)
}
if fake.RunRequests[0].InputPaths["party"] != filepath.Join(paths.InputsDir, "party.yml") {
t.Fatalf("inputs %+v", fake.RunRequests[0].InputPaths)
}
saved, err := (&manifest.LocalStore{}).Load(context.Background(), result.ManifestPath)
if err != nil {
t.Fatal(err)
}
if _, ok := saved.SuppliedProducts.Products[artifacts.ArtifactTranscriptFinalTrimmed]; !ok {
t.Fatal("lost supplied transcript")
}
speakers := cfg.StableInputs.SpeakersFile
speakerPath := speakers.Path
if !filepath.IsAbs(speakerPath) {
speakerPath = filepath.Join(filepath.Dir(speakers.ConfigPath), speakerPath)
}
if err := os.Remove(speakerPath); err != nil {
t.Fatal(err)
}
if _, err := executePlan(context.Background(), cfg, plan, RunOptions{Force: true, Env: &Env{Scriptorium: fake}}); err == nil {
t.Fatal("missing reference did not block forced downstream work")
}
if len(fake.RunRequests) != 1 {
t.Fatal("adapter invoked after reference preparation failed")
}
}
func TestFullRunWithSuppliedTranscriptPreparesAndRendersSelectedVariant(t *testing.T) {
root := t.TempDir()
pipeline, campaign, session := writeValidConfigFilesWithScriptoriumArtifacts(t, root)
cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{})
if err != nil {
t.Fatal(err)
}
cfg.Session.Inputs.AudioDir = ""
cfg.Session.Inputs.AudioFiles = nil
cfg.Session.Inputs.AudioS3 = nil
cfg.Pipeline.Render.Variants = []string{"trimmed"}
cfg.ArtifactCatalog.Artifacts = map[string]config.ScriptoriumArtifactConfig{"recap": {Enabled: true, PromptID: "dnd.recap", OutputPath: "artifacts/recap.md", Inputs: map[string]config.ScriptoriumInputConfig{"party": {Source: artifactpolicy.SourceInputParty, Required: true}, "transcript": {Source: artifacts.ArtifactTranscriptFinalTrimmed, Required: true}}}}
fake := &storage.FakeBackend{}
seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/final.trimmed.json": []byte(`{"segments":[]}`)})
if _, err := restoreSessionState(context.Background(), cfg, RestorePlanOptions{}, normalizeCommandDependencies(restoreCommandDependencies(fake))); err != nil {
t.Fatal(err)
}
plan := mustBoundedPlan(t, "", "analyze")
effective, err := resolveEffectiveArtifacts(cfg, nil)
if err != nil {
t.Fatal(err)
}
preview, err := buildSessionPlan(context.Background(), cfg, &executionInput{plan: plan}, nil, effective, commandDependencies{})
if err != nil {
t.Fatal(err)
}
for _, item := range preview.Stages {
if item.Name == "transcribe" || item.Name == "merge" || item.Name == "polish" || item.Name == "normalize" || item.Name == "trim" {
if item.Action != "skip" {
t.Fatalf("covered stage planned as %s: %#v", item.Action, item)
}
}
}
sf := &scriptorium.FakeRunner{}
ser := &seriatim.FakeRunner{}
result, err := executePlan(context.Background(), cfg, plan, RunOptions{Env: &Env{Scriptorium: sf, Seriatim: ser}})
if err != nil {
t.Fatal(err)
}
if len(ser.RenderRequests) != 1 || len(sf.RunRequests) != 1 {
t.Fatalf("render %d analyze %d, executed %v", len(ser.RenderRequests), len(sf.RunRequests), result.Executed)
}
for _, name := range []string{"transcribe", "merge", "polish", "normalize", "trim"} {
for _, executed := range result.Executed {
if name == executed {
t.Fatalf("covered stage %s executed", name)
}
}
}
forced := mustBoundedPlan(t, "transcribe", "transcribe")
input := &executionInput{plan: forced}
input.Force.Value = true
effective, err = resolveEffectiveArtifacts(cfg, nil)
if err != nil {
t.Fatal(err)
}
report, err := buildSessionPlan(context.Background(), cfg, input, nil, effective, commandDependencies{})
if err != nil || !strings.Contains(strings.Join(report.InputIssues, " "), "audio") {
t.Fatalf("forced plan did not report missing audio: %+v %v", report, err)
}
if _, err := executePlan(context.Background(), cfg, forced, RunOptions{Force: true}); err == nil {
t.Fatal("forced transcription accepted a session without audio")
}
}
func TestBoundedPlanReportsReferencePreparationAndMissingInput(t *testing.T) {
root := t.TempDir()
pipeline, campaign, session := writeValidConfigFilesWithScriptoriumArtifacts(t, root)
cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{})
if err != nil {
t.Fatal(err)
}
cfg.Session.Inputs.AudioDir = ""
cfg.Session.Inputs.AudioFiles = nil
cfg.ArtifactCatalog.Artifacts = map[string]config.ScriptoriumArtifactConfig{"recap": {Enabled: true, PromptID: "dnd.recap", OutputPath: "artifacts/recap.md", Inputs: map[string]config.ScriptoriumInputConfig{"transcript": {Source: artifacts.ArtifactTranscriptFinal, Required: true}}}}
paths := artifacts.NewLocalStore(root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
transcript := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed))
if err := os.MkdirAll(filepath.Dir(transcript), 0755); err != nil {
t.Fatal(err)
}
body := []byte(`{"segments":[]}`)
if err := os.WriteFile(transcript, body, 0600); err != nil {
t.Fatal(err)
}
checksum, err := artifacts.SHA256File(transcript)
if err != nil {
t.Fatal(err)
}
m := manifest.New(cfg.Session.SessionID, time.Now())
m.Campaign = cfg.Session.Campaign
m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{artifacts.ArtifactTranscriptFinalTrimmed: {Path: artifacts.TranscriptPathFinalTrimmed, Checksum: checksum, Size: int64(len(body))}}}
path := saveBoundedManifest(t, cfg, m)
before, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
effective, err := resolveEffectiveArtifacts(cfg, nil)
if err != nil {
t.Fatal(err)
}
input := &executionInput{plan: mustBoundedPlan(t, "analyze", "analyze")}
report, err := buildSessionPlan(context.Background(), cfg, input, nil, effective, commandDependencies{})
if err != nil {
t.Fatal(err)
}
if report.ReferencePreparation == nil || report.ReferencePreparation.Outcome != "planned" || len(report.InputIssues) != 1 || !strings.Contains(report.InputIssues[0], artifacts.ArtifactTranscriptFinal) {
t.Fatalf("report %+v", report)
}
after, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(before, after) {
t.Fatal("plan changed manifest")
}
if _, err := os.Stat(filepath.Join(paths.InputsDir, "party.yml")); !os.IsNotExist(err) {
t.Fatalf("plan wrote references: %v", err)
}
recap := cfg.ArtifactCatalog.Artifacts["recap"]
recap.Inputs["history"] = config.ScriptoriumInputConfig{Source: artifactpolicy.PreviousSessionSourceID("recap"), Required: true}
cfg.ArtifactCatalog.Artifacts["recap"] = recap
report, err = buildSessionPlan(context.Background(), cfg, input, nil, effective, commandDependencies{})
if err != nil {
t.Fatal(err)
}
if len(report.InputIssues) < 2 || !strings.Contains(strings.Join(report.InputIssues, " "), "previous_session_id") {
t.Fatalf("missing required history not reported: %+v", report.InputIssues)
}
if _, err := executePlan(context.Background(), cfg, input.plan, RunOptions{Env: &Env{Scriptorium: &scriptorium.FakeRunner{}}}); err == nil || !strings.Contains(err.Error(), "previous_session_id") {
t.Fatalf("missing history execution error: %v", err)
}
}
func TestStandalonePreflightWithSuppliedTranscriptStillProbesProviders(t *testing.T) {
root := t.TempDir()
pipeline, campaign, session := writeValidConfigFiles(t, root)
cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{})
if err != nil {
t.Fatal(err)
}
cfg.Session.Inputs.AudioDir = ""
cfg.Session.Inputs.AudioFiles = nil
cfg.Session.Inputs.AudioS3 = nil
fake := &storage.FakeBackend{}
seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/final.trimmed.json": []byte(`{"segments":[]}`)})
if _, err := restoreSessionState(context.Background(), cfg, RestorePlanOptions{}, normalizeCommandDependencies(restoreCommandDependencies(fake))); err != nil {
t.Fatal(err)
}
provider := &audita.FakeRunner{}
deps := fakeCommandDependencies(&storage.FakeBackend{}, nil)
deps.newAudita = func(*config.Config) (audita.Runner, error) { return provider, nil }
report, err := inspectConfiguredForTest(context.Background(), cfg, deps)
if err != nil || !report.Ready || len(provider.PreflightRequests) != 1 {
t.Fatalf("report %+v err %v", report, err)
}
saved, err := (&manifest.LocalStore{}).Load(context.Background(), manifestPathFor(cfg))
if err != nil {
t.Fatal(err)
}
if saved.Stages["prepare"].Metadata["audio_prepared"] != false {
t.Fatal("preflight claimed audio preparation")
}
}