package app import ( "bytes" "context" "errors" "os" "path/filepath" "reflect" "testing" "time" "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/stage" ) func TestPlanDoesNotCreateWorkdir(t *testing.T) { workspaceRoot := t.TempDir() pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot) var out bytes.Buffer args := []string{"2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath} if err := invokeNativeCommand(context.Background(), append([]string{"session", "plan"}, args...), &out); err != nil { t.Fatalf("first Plan() error = %v", err) } report := decodeNativeReport[sessionPlanReport](t, out.Bytes()) for index, name := range canonicalStageNames() { if index >= len(report.Stages) || report.Stages[index].Name != name || report.Stages[index].Action != "run" { t.Fatalf("initial plan=%#v", report) } } sessionWorkdir := artifacts.SessionWorkDirForCampaign(workspaceRoot, "sample-campaign", "2026-05-03") if _, err := os.Stat(sessionWorkdir); !errors.Is(err, os.ErrNotExist) { t.Fatalf("workdir stat error = %v, want absent", err) } out.Reset() if err := invokeNativeCommand(context.Background(), append([]string{"session", "plan"}, args...), &out); err != nil { t.Fatalf("second Plan() error = %v", err) } if repeated := decodeNativeReport[sessionPlanReport](t, out.Bytes()); !reflect.DeepEqual(repeated, report) { t.Fatalf("read-only plan changed: %#v", repeated) } } type observingArtifactStore struct { artifacts.Store pathLookups int } func (s *observingArtifactStore) SessionPathsFor(campaign, sessionID string) artifacts.SessionPaths { s.pathLookups++ return s.Store.SessionPathsFor(campaign, sessionID) } func TestProjectionUsesInjectedSnapshotAndSchedulesPrerequisites(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) } cfg.ArtifactCatalog.Artifacts = map[string]config.ScriptoriumArtifactConfig{ "prerequisite": {Enabled: false, PromptID: "parent", OutputPath: "artifacts/parent.md"}, "target": {Enabled: true, PromptID: "child", OutputPath: "artifacts/child.md", DependsOn: []string{"prerequisite"}}, } selection := []string{"target"} effective, err := resolveEffectiveArtifacts(cfg, selection) if err != nil { t.Fatal(err) } plan, err := BuildBoundedPlan("analyze", "analyze") if err != nil { t.Fatal(err) } snapshot := manifest.New(cfg.Session.SessionID, time.Now().UTC()) snapshot.Campaign = cfg.Session.Campaign snapshot.MarkStageSucceeded("analyze", time.Now().UTC(), nil) snapshot.Stages["analyze"].AnalyzeStateVersion = manifest.AnalyzeStateContractVersion snapshot.Stages["analyze"].AnalyzeArtifacts = map[string]manifest.AnalyzeArtifactRecord{"target": {Key: "target", Status: manifest.AnalyzeArtifactMissing, ProducerRunID: "prior", UpdatedAt: time.Now().UTC()}} before, err := cloneManifestForPlan(snapshot, cfg) if err != nil { t.Fatal(err) } store := &observingArtifactStore{Store: artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root)} projection, err := projectSelectedWork(context.Background(), cfg, plan, false, selection, effective, store, snapshot) if err != nil { t.Fatal(err) } if store.pathLookups == 0 { t.Fatal("projection did not use injected store") } if !reflect.DeepEqual(snapshot, before) { t.Fatal("projection mutated authoritative manifest") } if len(projection.Stages) != 1 || projection.Stages[0].Analysis == nil { t.Fatalf("projection = %+v", projection) } work := projection.Stages[0].Analysis.ExecutionOrder if len(work) != 2 || work[0].Key != "prerequisite" || work[1].Key != "target" { t.Fatalf("scheduled work = %+v", work) } } func TestPlanShowsRunAndSkipFromManifest(t *testing.T) { workspaceRoot := t.TempDir() pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot) manifestPath := filepath.Join(workspaceRoot, "work", "sample-campaign", "2026-05-03", "manifest.json") store := &manifest.LocalStore{} materializePrepareResumeFixture(t, pipelinePath, campaignPath, sessionPath) m, err := store.Load(context.Background(), manifestPath) if err != nil { t.Fatalf("load prepared manifest: %v", err) } m.MarkStageSucceeded("transcribe", time.Date(2026, 5, 3, 10, 2, 0, 0, time.UTC), nil) seedCurrentSemanticEvidence(t, loadConfigForSemanticEvidence(t, pipelinePath, campaignPath, sessionPath), m, "prepare", "transcribe") if err := store.Save(context.Background(), manifestPath, m); err != nil { t.Fatalf("save manifest: %v", err) } var out bytes.Buffer if err := invokeNativeCommand(context.Background(), []string{"session", "plan", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath}, &out); err != nil { t.Fatalf("Plan() error = %v", err) } report := decodeNativeReport[sessionPlanReport](t, out.Bytes()) skipped := 0 for _, item := range report.Stages { if item.Action == "skip" { skipped++ if item.Name != "prepare" && item.Name != "transcribe" { t.Fatalf("unexpected reuse: %#v", item) } } } if skipped != 2 || len(report.Stages) != len(canonicalStageNames()) { t.Fatalf("plan=%#v", report) } } func TestPlanLoadsWithoutConfiguredSecretsDirectory(t *testing.T) { workspaceRoot := t.TempDir() configDir := t.TempDir() pipelinePath := filepath.Join(configDir, "pipeline.yml") campaignPath := writeAppTestCampaignConfig(t, configDir) sessionPath := filepath.Join(configDir, "session.yml") pipelineYAML := `workspace: root: ` + workspaceRoot + ` storage: backend: local whisperx: transcribe_url: https://example.com/transcribe seriatim: binary: seriatim audita: binary: audita notification: mode: noop ` sessionYAML := `session_id: 2026-05-03 campaign: sample-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil { t.Fatalf("write pipeline.yml: %v", err) } if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil { t.Fatalf("write session.yml: %v", err) } var out bytes.Buffer err := invokeNativeCommand(context.Background(), []string{"session", "plan", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath}, &out) if err != nil { t.Fatalf("Plan() error = %v, want absent conventional secrets directory skipped", err) } } func TestPlanAndRunShareAnalyzeArtifactDecisionsWithoutPlanSideEffects(t *testing.T) { workspaceRoot := t.TempDir() pipelinePath, campaignPath, sessionPath := writeValidConfigFilesWithScriptoriumArtifacts(t, workspaceRoot) cfg, err := config.LoadWithSessionOptions(pipelinePath, campaignPath, sessionPath, config.SessionLoadOptions{}) if err != nil { t.Fatalf("load config: %v", err) } analyze, err := stage.Select("analyze") if err != nil { t.Fatal(err) } fake := &scriptorium.FakeRunner{} first, err := executeStages(context.Background(), cfg, []stage.Stage{analyze}, RunOptions{ Env: &Env{Scriptorium: fake}, }) if err != nil { t.Fatalf("initial analyze: %v", err) } if len(fake.RunRequests) != 2 { t.Fatalf("initial adapter requests = %d, want 2", len(fake.RunRequests)) } store := &manifest.LocalStore{} m, err := store.Load(context.Background(), first.ManifestPath) if err != nil { t.Fatal(err) } for _, name := range []string{"prepare", "transcribe", "merge", "polish", "normalize", "trim"} { m.MarkStageSucceeded(name, time.Now().UTC(), nil) } m.MarkStageStale("render", time.Now().UTC(), "upstream selection requires reconsideration") m.MarkStageSkipped("extract", time.Now().UTC(), "notarius_disabled") if err := store.Save(context.Background(), first.ManifestPath, m); err != nil { t.Fatal(err) } manifestBefore, err := os.ReadFile(first.ManifestPath) if err != nil { t.Fatal(err) } filesBefore := planFixtureFiles(t, filepath.Dir(first.ManifestPath)) marker := filepath.Join(t.TempDir(), "adapter-invoked") binaryDir := t.TempDir() binary := filepath.Join(binaryDir, "scriptorium") if err := os.WriteFile(binary, []byte("#!/bin/sh\ntouch \""+marker+"\"\nexit 99\n"), 0o755); err != nil { t.Fatal(err) } t.Setenv("PATH", binaryDir+string(os.PathListSeparator)+os.Getenv("PATH")) var out bytes.Buffer err = invokeNativeCommand(context.Background(), []string{"session", "plan", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--from", "render", "--through", "analyze", }, &out) if err != nil { t.Fatalf("Plan() error = %v", err) } report := decodeNativeReport[sessionPlanReport](t, out.Bytes()) if len(report.Stages) != 3 { t.Fatalf("bounded plan=%#v", report) } for _, item := range report.Stages { if item.Action != "run" { t.Fatalf("stage plan=%#v", item) } } analysis := report.Stages[2].Analysis if analysis == nil || len(analysis.Execute) != 0 || len(analysis.Prerequisites) != 0 || len(analysis.Reuse) != 2 { t.Fatalf("analysis plan=%#v", analysis) } for _, item := range analysis.Reuse { if item.Role != "target" || item.Reason != "current" { t.Fatalf("artifact reuse=%#v", item) } } manifestAfter, err := os.ReadFile(first.ManifestPath) if err != nil { t.Fatal(err) } if !bytes.Equal(manifestBefore, manifestAfter) { t.Fatal("plan modified the session manifest") } if filesAfter := planFixtureFiles(t, filepath.Dir(first.ManifestPath)); !reflect.DeepEqual(filesAfter, filesBefore) { t.Fatalf("plan files = %#v, want unchanged %#v", filesAfter, filesBefore) } if _, err := os.Stat(marker); !errors.Is(err, os.ErrNotExist) { t.Fatalf("adapter marker stat = %v, want absent", err) } fake.RunRequests = nil actual, err := executeStages(context.Background(), cfg, []stage.Stage{ resultStage{name: "render", result: &stage.StageResult{}}, resultStage{name: "extract", result: &stage.StageResult{Disposition: stage.StageDispositionSkipped, SkipReason: "notarius_disabled"}}, analyze, }, RunOptions{ Env: &Env{Scriptorium: fake}, }) if err != nil { t.Fatalf("actual analyze: %v", err) } if !reflect.DeepEqual(actual.Executed, []string{"render", "extract", "analyze"}) || !reflect.DeepEqual(actual.Skipped, []string{"extract"}) || len(fake.RunRequests) != 0 { t.Fatalf("actual decision: executed=%#v skipped=%#v adapter_requests=%d, want planned stage decisions with artifact reuse", actual.Executed, actual.Skipped, len(fake.RunRequests)) } } func planFixtureFiles(t *testing.T, root string) []string { t.Helper() var files []string err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error { if err != nil { return err } relative, err := filepath.Rel(root, path) if err != nil { return err } files = append(files, relative+":"+entry.Type().String()) return nil }) if err != nil { t.Fatal(err) } return files }