Files
narratio/internal/app/native_workflow_test.go

133 lines
6.1 KiB
Go

package app
import (
"bufio"
"context"
"encoding/json"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/seriatim"
"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 TestNativePromptWorkflowInspectsFutureInputsAndRetries(t *testing.T) {
cfg := testConfig(t)
eventsPath := filepath.Join(t.TempDir(), "commands.jsonl")
t.Setenv("SCRIPTORIUM_HELPER_RECORD_PATH", eventsPath)
t.Setenv("SCRIPTORIUM_HELPER_MODE", "fail-character")
enabled := true
cfg.Pipeline.Trim = &config.TrimConfig{Enabled: &enabled, OutputPath: "transcripts/final.trimmed.json", Bounds: config.TrimBoundsConfig{PromptID: "workflow.bounds", TranscriptInputName: "transcript", OutputPath: "artifacts/bounds.json"}}
cfg.Pipeline.Scriptorium = &config.ScriptoriumConfig{Binary: writeScriptoriumAppTestWrapper(t), Timeout: "1m", RenderDebug: true,
Artifacts: map[string]config.ScriptoriumArtifactConfig{"parent": {Enabled: false, PromptID: "workflow.parent", OutputPath: "artifacts/parent.md", Inputs: map[string]config.ScriptoriumInputConfig{"transcript": {Source: artifacts.ArtifactTranscriptFinalTrimmed, Required: true}}}},
ArtifactFamilies: map[string]config.ScriptoriumArtifactFamilyConfig{"character": {Enabled: true, ForEach: "party.characters", PromptID: "workflow.character", OutputPathPattern: "artifacts/{character_id}.md", DependsOn: []string{"parent"}, MemberVars: map[string]string{"character_name": "character.name"}, Inputs: map[string]config.ScriptoriumInputConfig{"transcript": {Source: artifacts.ArtifactTranscriptFinalTrimmed, Required: true}, "prior": {Source: "narratio.artifact.parent", Required: true}}}},
}
var err error
cfg.ArtifactCatalog, err = config.DeriveArtifactCatalog(cfg.Pipeline, cfg.Party)
if err != nil {
t.Fatal(err)
}
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
normalized := filepath.Join(paths.TranscriptsDir, "final.json")
mustWriteTestFile(t, normalized, `{"segments":[{"id":1}]}`)
seed := manifest.New(cfg.Session.SessionID, time.Now().UTC())
seed.Campaign = cfg.Session.Campaign
seed.MarkStageSucceeded("normalize", time.Now().UTC(), nil)
setCurrentBuiltInEvidence(t, seed, "normalize", artifacts.TranscriptOutputKindFinal, artifacts.ArtifactTranscriptFinal, normalized)
saveBoundedManifest(t, cfg, seed)
if _, err := os.Stat(filepath.Join(paths.TranscriptsDir, "final.trimmed.json")); !os.IsNotExist(err) {
t.Fatalf("future transcript already exists: %v", err)
}
stages := []stage.Stage{mustSelectStage(t, "trim"), mustSelectStage(t, "analyze")}
runner := scriptorium.NewSubprocessRunner()
_, err = executeStages(context.Background(), cfg, stages, RunOptions{Env: &Env{Scriptorium: runner, Seriatim: &seriatim.FakeRunner{}}})
if err == nil || !strings.Contains(err.Error(), "synthetic generation failure") {
t.Fatalf("first run error = %v", err)
}
commands := readNativeWorkflowCommands(t, eventsPath)
if len(commands) < 8 {
t.Fatalf("commands = %v", commands)
}
for i, prompt := range []string{"workflow.bounds", "workflow.parent", "workflow.character"} {
if len(commands[i]) < 4 || strings.Join(commands[i][:3], " ") != "promptkit requirements show" || commands[i][3] != prompt {
t.Fatalf("inspection order = %v", commands)
}
if strings.Contains(strings.Join(commands[i], " "), "--input-file") {
t.Fatalf("discovery received future file: %v", commands[i])
}
}
characterSeen := false
for _, command := range commands {
if len(command) >= 4 && strings.Join(command[:3], " ") == "promptkit show prepared" && command[3] == "workflow.character" {
characterSeen = strings.Contains(strings.Join(command, " "), "character_name=Arannis")
}
}
if !characterSeen {
t.Fatalf("character preview missing effective variables: %v", commands)
}
if err := os.Remove(eventsPath); err != nil {
t.Fatal(err)
}
t.Setenv("SCRIPTORIUM_HELPER_MODE", "")
if _, err := executeStages(context.Background(), cfg, []stage.Stage{mustSelectStage(t, "analyze")}, RunOptions{Env: &Env{Scriptorium: runner}}); err != nil {
t.Fatal(err)
}
commands = readNativeWorkflowCommands(t, eventsPath)
if len(commands) != 3 || strings.Join(commands[0][:3], " ") != "promptkit requirements show" || commands[0][3] != "workflow.character" || commands[2][0] != "run" || commands[2][1] != "workflow.character" {
t.Fatalf("retry commands = %v", commands)
}
store := &manifest.LocalStore{}
before, err := store.Load(context.Background(), manifestPathFor(cfg))
if err != nil {
t.Fatal(err)
}
outputPath := filepath.Join(paths.ArtifactsDir, "arannis.md")
beforeBytes, err := os.ReadFile(outputPath)
if err != nil {
t.Fatal(err)
}
t.Setenv("SCRIPTORIUM_HELPER_MODE", "missing-character")
_, err = executeStages(context.Background(), cfg, []stage.Stage{mustSelectStage(t, "analyze")}, RunOptions{Force: true, SelectedArtifacts: []string{"character_arannis"}, Env: &Env{Scriptorium: runner}})
if err == nil || !strings.Contains(err.Error(), `required input "missing"`) {
t.Fatalf("forced preflight error = %v", err)
}
after, err := store.Load(context.Background(), manifestPathFor(cfg))
if err != nil {
t.Fatal(err)
}
afterBytes, err := os.ReadFile(outputPath)
if err != nil || !reflect.DeepEqual(beforeBytes, afterBytes) || !reflect.DeepEqual(before.Stages["analyze"], after.Stages["analyze"]) {
t.Fatalf("forced failure changed authority or output: %v", err)
}
}
func readNativeWorkflowCommands(t *testing.T, path string) [][]string {
t.Helper()
file, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer file.Close()
var commands [][]string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
var command []string
if err := json.Unmarshal(scanner.Bytes(), &command); err != nil {
t.Fatal(err)
}
commands = append(commands, command)
}
if err := scanner.Err(); err != nil {
t.Fatal(err)
}
return commands
}