Verify native Scriptorium workflows and retry behavior

This commit is contained in:
2026-11-26 04:34:47 +00:00
parent d48215678a
commit e9d57fb7aa
6 changed files with 201 additions and 30 deletions

View File

@@ -167,9 +167,7 @@ Check: `go test ./internal/adapters/scriptorium ./internal/stage`.
## Stage 4: Add the native requirements adapter ## Stage 4: Add the native requirements adapter
**Status: Complete.** The application package compiles; its older offline **Status: Complete.**
Scriptorium subprocess fixtures require the native-interface updates scheduled
for Stage 11.
**Purpose:** Inspect prompt requirements without input files, output paths, or **Purpose:** Inspect prompt requirements without input files, output paths, or
model execution. model execution.
@@ -254,8 +252,7 @@ Check: `go test ./internal/stage ./internal/config`.
## Stage 6: Extract reusable read-only planning and closure ## Stage 6: Extract reusable read-only planning and closure
**Status: Complete.** Focused planning and stage checks pass. The full **Status: Complete.**
application check still has the offline fixture failures recorded under Stage 4.
**Purpose:** Reuse the existing projected plan for early inspection while keeping **Purpose:** Reuse the existing projected plan for early inspection while keeping
actual execution authoritative. actual execution authoritative.
@@ -383,8 +380,7 @@ Check: `go test ./internal/preflight`.
## Stage 9: Run preflight before stage attempts ## Stage 9: Run preflight before stage attempts
**Status: Complete.** Focused lifecycle and composition checks pass; the full **Status: Complete.**
application suite still requires the offline fixture migration in Stage 11.
**Purpose:** Catch actionable Scriptorium problems before expensive work while **Purpose:** Catch actionable Scriptorium problems before expensive work while
preserving completed results on preflight failure. preserving completed results on preflight failure.
@@ -467,6 +463,8 @@ the focused validation tests under their final names.
## Stage 11: Verify assembled workflows and remove superseded machinery ## Stage 11: Verify assembled workflows and remove superseded machinery
**Status: Complete.** The full offline and race-enabled test suites pass.
**Purpose:** Prove the integrated cutover and retain a proportionate test suite. **Purpose:** Prove the integrated cutover and retain a proportionate test suite.
Review the focused tests added in Stages 1–10 and existing plan, lifecycle, Review the focused tests added in Stages 1–10 and existing plan, lifecycle,

View File

@@ -352,7 +352,7 @@ func TestAssembledSplitBundleProfileSwitchRecordsProvenanceAndLimitsReuse(t *tes
testingRuns := make([]int, len(names)) testingRuns := make([]int, len(names))
testingStages := assembledSemanticStages(names, providers, testingRuns) testingStages := assembledSemanticStages(names, providers, testingRuns)
testingSummary, err := executeStages(context.Background(), testingCfg, testingStages, RunOptions{}) testingSummary, err := executeStages(context.Background(), testingCfg, testingStages, RunOptions{Env: &Env{Scriptorium: &scriptorium.FakeRunner{}}})
if err != nil { if err != nil {
t.Fatalf("switch to testing profile: %v", err) t.Fatalf("switch to testing profile: %v", err)
} }

View File

@@ -11,6 +11,7 @@ import (
"strings" "strings"
"testing" "testing"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage" "gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/config" "gitea.maximumdirect.net/eric/narratio/internal/config"
"go.maximumdirect.net/commandkit" "go.maximumdirect.net/commandkit"
@@ -24,6 +25,7 @@ func TestNativeDiscoveryDoesNotAcquireConfiguration(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
application, err := newApplication(commandDependencies{ application, err := newApplication(commandDependencies{
newScriptorium: func() scriptorium.Runner { t.Fatal("discovery initialized scriptorium"); return nil },
loadPipelineSource: func(configkit.Source, config.PipelineLoadOptions) (*config.PipelineConfig, error) { loadPipelineSource: func(configkit.Source, config.PipelineLoadOptions) (*config.PipelineConfig, error) {
t.Fatal("discovery loaded pipeline configuration") t.Fatal("discovery loaded pipeline configuration")
return nil, nil return nil, nil
@@ -73,6 +75,22 @@ func TestNativeDiscoveryDoesNotAcquireConfiguration(t *testing.T) {
} }
} }
func TestPlanAndConfigInspectionDoNotInspectPrompts(t *testing.T) {
pipeline, campaign, session := writeValidConfigFilesWithScriptoriumArtifacts(t, t.TempDir())
deps := commandDependencies{newScriptorium: func() scriptorium.Runner { t.Fatal("inspection initialized scriptorium"); return nil }}
app, err := newApplication(deps, executePlan)
if err != nil {
t.Fatal(err)
}
for _, args := range [][]string{{"config", "show", "--config", pipeline}, {"session", "plan", "2026-05-03", "--config", pipeline, "--campaign-file", campaign, "--session-file", session}} {
var out, diag bytes.Buffer
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diag})
if outcome.Status != 0 {
t.Fatalf("args = %v, outcome = %+v, diagnostics = %s", args, outcome, diag.String())
}
}
}
func TestNativeSelectionRetainsPresenceAndCallerContext(t *testing.T) { func TestNativeSelectionRetainsPresenceAndCallerContext(t *testing.T) {
flags := newConfigurationFlags(func(in *configurationSelection) *configurationSelection { return in }) flags := newConfigurationFlags(func(in *configurationSelection) *configurationSelection { return in })
type contextKey struct{} type contextKey struct{}

View File

@@ -578,24 +578,46 @@ func TestScriptoriumAppHelper(t *testing.T) {
os.Exit(2) os.Exit(2)
} }
runArgs := args[start:] runArgs := args[start:]
if path := os.Getenv("SCRIPTORIUM_HELPER_RECORD_PATH"); path != "" {
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
os.Exit(2)
}
if err := json.NewEncoder(file).Encode(runArgs); err != nil {
os.Exit(2)
}
_ = file.Close()
}
outputPath := appSeriatimFlagValue(runArgs, "--out") if len(runArgs) >= 4 && strings.Join(runArgs[:3], " ") == "promptkit requirements show" {
if strings.TrimSpace(outputPath) == "" { inputs := []map[string]any{}
outputPath = appSeriatimFlagValue(runArgs, "--output") if strings.HasPrefix(runArgs[3], "workflow.") {
inputs = append(inputs, map[string]any{"name": "transcript", "kind": "required"})
if runArgs[3] == "workflow.character" {
inputs = append(inputs, map[string]any{"name": "prior", "kind": "required"})
} }
if strings.TrimSpace(outputPath) == "" { if os.Getenv("SCRIPTORIUM_HELPER_MODE") == "missing-character" && runArgs[3] == "workflow.character" {
_, _ = os.Stderr.WriteString("missing output flag\n") inputs = append(inputs, map[string]any{"name": "missing", "kind": "required"})
}
}
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{"prompt_id": runArgs[3], "profile_id": "", "complete": true, "inputs": inputs, "variables": []any{}, "issues": []any{}})
} else if len(runArgs) >= 4 && strings.Join(runArgs[:3], " ") == "promptkit show prepared" {
_, _ = os.Stdout.WriteString(`{"prepared":true}`)
} else if len(runArgs) >= 2 && runArgs[0] == "run" {
if runArgs[1] == "workflow.character" && os.Getenv("SCRIPTORIUM_HELPER_MODE") == "fail-character" {
_, _ = os.Stdout.WriteString("partial")
_, _ = os.Stderr.WriteString("synthetic generation failure")
os.Exit(1)
}
if runArgs[1] == "workflow.parent" || runArgs[1] == "workflow.character" {
_, _ = fmt.Fprint(os.Stdout, "generated ", runArgs[1], "\n")
} else {
_, _ = os.Stdout.WriteString(`{"trim_action":"copy","warnings":[]}`)
}
} else {
_, _ = os.Stderr.WriteString("unsupported scriptorium command\n")
os.Exit(2) os.Exit(2)
} }
if err := os.MkdirAll(filepath.Dir(outputPath), 0o755); err != nil {
_, _ = os.Stderr.WriteString(fmt.Sprintf("mkdir output dir: %v\n", err))
os.Exit(2)
}
if err := os.WriteFile(outputPath, []byte(`{"trim_action":"copy","warnings":[]}`), 0o644); err != nil {
_, _ = os.Stderr.WriteString(fmt.Sprintf("write output: %v\n", err))
os.Exit(2)
}
_, _ = os.Stdout.WriteString("scriptorium helper stdout\n")
_, _ = os.Stderr.WriteString("scriptorium helper stderr\n") _, _ = os.Stderr.WriteString("scriptorium helper stderr\n")
os.Exit(0) os.Exit(0)
} }

View File

@@ -0,0 +1,132 @@
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
}

View File

@@ -214,21 +214,22 @@ func TestProviderCredentialProcessFixture(t *testing.T) {
_, _ = os.Stderr.WriteString("shared credential not forwarded\n") _, _ = os.Stderr.WriteString("shared credential not forwarded\n")
os.Exit(2) os.Exit(2)
} }
if appSeriatimFlagValue(args, "--prompt") != "" { if args[0] == "promptkit" || (args[0] == "run" && appSeriatimFlagValue(args, "--output-dir") == "") {
if _, present := os.LookupEnv(auditaOnlyName); present { if _, present := os.LookupEnv(auditaOnlyName); present {
os.Exit(2) os.Exit(2)
} }
if appSeriatimFlagValue(args, "--api-key-env") != "" { if appSeriatimFlagValue(args, "--api-key-env") != "" {
os.Exit(2) os.Exit(2)
} }
output := appSeriatimFlagValue(args, "--out") if len(args) >= 4 && strings.Join(args[:3], " ") == "promptkit requirements show" {
if err := os.MkdirAll(filepath.Dir(output), 0o755); err != nil { _, _ = fmt.Fprintf(os.Stdout, `{"prompt_id":%q,"profile_id":"","complete":true,"inputs":[],"variables":[],"issues":[]}`, args[3])
} else if len(args) >= 4 && strings.Join(args[:3], " ") == "promptkit show prepared" {
_, _ = os.Stdout.WriteString(`{"prepared":true}`)
} else if args[0] == "run" {
_, _ = os.Stdout.WriteString("generated recap\n")
} else {
os.Exit(2) os.Exit(2)
} }
if err := os.WriteFile(output, []byte("{}\n"), 0o644); err != nil {
os.Exit(2)
}
_, _ = os.Stdout.WriteString(sharedProviderKey + "\n")
_, _ = os.Stderr.WriteString(sharedProviderKey + "\n") _, _ = os.Stderr.WriteString(sharedProviderKey + "\n")
os.Exit(0) os.Exit(0)
} }