Files
narratio/internal/adapters/scriptorium/subprocess_test.go

453 lines
16 KiB
Go

package scriptorium
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
configkit "go.maximumdirect.net/configkit"
)
func TestSubprocessRunnerRunSuccessBuildsDeterministicArgsAndCapturesLogs(t *testing.T) {
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
t.Setenv("SCRIPTORIUM_HELPER_MODE", "run_success")
t.Setenv("OPENAI_KEY_SOURCE", "super-secret")
loaded, err := configkit.Load[struct {
Credentials []configkit.Secret `yaml:"credentials"`
}](configkit.Bytes("test.yml", []byte("credentials: [OPENAI_KEY_SOURCE]\n")))
if err != nil {
t.Fatal(err)
}
t.Setenv("OPENAI_KEY_SOURCE", "changed-after-load")
recordPath := filepath.Join(t.TempDir(), "record.json")
t.Setenv("SCRIPTORIUM_HELPER_RECORD_PATH", recordPath)
runner := NewSubprocessRunner()
wrapper := writeScriptoriumHelperWrapper(t)
dir := t.TempDir()
req := RunArtifactRequest{
Binary: wrapper,
ConfigPath: "/etc/scriptorium/config.yml",
PromptID: "dnd.session_recap",
ProfileID: "local-quality",
InputPaths: map[string]string{"transcript": filepath.Join(dir, "polished.json"), "other": filepath.Join(dir, "other,=notes.md")},
Vars: map[string]string{"session_id": "2026-05-03", "campaign_name": "Icewind,Dale=North"},
OutputPath: filepath.Join(dir, "artifacts", "session_recap.md"),
StdoutLogPath: filepath.Join(dir, "logs", "scriptorium.run.stdout.log"),
StderrLogPath: filepath.Join(dir, "logs", "scriptorium.run.stderr.log"),
GeneratedConfigPath: filepath.Join(dir, "config", "scriptorium.run.generated.yml"),
Timeout: mustParseScriptoriumDuration(t, "2s"),
Credentials: loaded.Config.Credentials,
}
writeScriptoriumFile(t, req.InputPaths["transcript"], `{"segments":[]}`)
writeScriptoriumFile(t, req.InputPaths["other"], "notes\n")
res, err := runner.RunArtifact(context.Background(), req)
if err != nil {
t.Fatalf("RunArtifact() error = %v", err)
}
if res.ExitCode != 0 {
t.Fatalf("ExitCode = %d, want 0", res.ExitCode)
}
if res.CommandMode != CommandModeRun {
t.Fatalf("CommandMode = %q, want %q", res.CommandMode, CommandModeRun)
}
if res.OutputPath != req.OutputPath {
t.Fatalf("OutputPath = %q, want %q", res.OutputPath, req.OutputPath)
}
if res.Duration <= 0 {
t.Fatalf("Duration = %s, want > 0", res.Duration)
}
data, err := os.ReadFile(req.OutputPath)
if err != nil || !bytes.Equal(data, []byte{'a', 0, 255, '\n'}) {
t.Fatalf("artifact = %v, %v", data, err)
}
if res.StdoutLogPath != "" {
t.Fatalf("unexpected stdout log %q", res.StdoutLogPath)
}
if _, err := os.Stat(req.StdoutLogPath); !os.IsNotExist(err) {
t.Fatalf("unexpected stdout diagnostic: %v", err)
}
assertFileContains(t, req.StderrLogPath, "scriptorium helper stderr")
rec := readScriptoriumHelperRecord(t, recordPath)
wantArgs := []string{
"run",
"dnd.session_recap",
"--config", "/etc/scriptorium/config.yml",
"--profile", "local-quality",
"--input-file", "other=" + req.InputPaths["other"],
"--input-file", "transcript=" + req.InputPaths["transcript"],
"--var", "campaign_name=Icewind,Dale=North",
"--var", "session_id=2026-05-03",
"--run-timeout", "2s",
"--format", "text",
}
if strings.Join(rec.Args, "\n") != strings.Join(wantArgs, "\n") {
t.Fatalf("args = %#v, want %#v", rec.Args, wantArgs)
}
if rec.Env["OPENAI_KEY_SOURCE"] != "super-secret" {
t.Fatalf("OPENAI_KEY_SOURCE env = %q, want inherited value", rec.Env["OPENAI_KEY_SOURCE"])
}
cfgData, err := os.ReadFile(req.GeneratedConfigPath)
if err != nil {
t.Fatalf("read generated config: %v", err)
}
if strings.Contains(string(cfgData), "super-secret") {
t.Fatalf("generated config must not include credential value")
}
if !strings.Contains(string(cfgData), "stdout_destination:") || !strings.Contains(string(cfgData), req.OutputPath) || !strings.Contains(string(cfgData), "--input-file") || !strings.Contains(string(cfgData), "OPENAI_KEY_SOURCE") {
t.Fatalf("invocation record = %s", cfgData)
}
}
func TestSubprocessRunnerRejectsNonRegularOutput(t *testing.T) {
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
req := runReqForTest(t, writeScriptoriumHelperWrapper(t))
if err := os.MkdirAll(req.OutputPath, 0o700); err != nil {
t.Fatal(err)
}
if _, err := NewSubprocessRunner().RunArtifact(context.Background(), req); err == nil {
t.Fatal("expected output open failure")
}
}
func TestSubprocessRunnerRunExitCodeOneFails(t *testing.T) {
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
t.Setenv("SCRIPTORIUM_HELPER_MODE", "fail_exit1")
t.Setenv("SCRIPTORIUM_HELPER_RECORD_PATH", filepath.Join(t.TempDir(), "record.json"))
t.Setenv("CUSTOM_PROVIDER_KEY", "synthetic-failure-secret")
loaded, loadErr := configkit.Load[struct {
Credentials []configkit.Secret `yaml:"credentials"`
}](configkit.Bytes("test.yml", []byte("credentials: [CUSTOM_PROVIDER_KEY]\n")))
if loadErr != nil {
t.Fatal(loadErr)
}
runner := NewSubprocessRunner()
req := runReqForTest(t, writeScriptoriumHelperWrapper(t))
req.Credentials = loaded.Config.Credentials
res, err := runner.RunArtifact(context.Background(), req)
if err == nil {
t.Fatal("RunArtifact() error = nil, want non-nil")
}
if strings.Contains(err.Error(), "synthetic-failure-secret") {
t.Fatal("failure leaked credential")
}
data, readErr := os.ReadFile(req.StderrLogPath)
if readErr != nil {
t.Fatal(readErr)
}
if strings.Contains(string(data), "synthetic-failure-secret") || !strings.Contains(string(data), "<redacted>") {
t.Fatal("failure log did not redact selected credential")
}
if res.ExitCode != 1 {
t.Fatalf("ExitCode = %d, want 1", res.ExitCode)
}
if res.ValidationFailed {
t.Fatalf("ValidationFailed = true, want false")
}
assertFileContains(t, req.StderrLogPath, "scriptorium helper failure")
}
func TestSubprocessRunnerRunExitCodeFourReturnsValidationFailureAndPreservesOutput(t *testing.T) {
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
t.Setenv("SCRIPTORIUM_HELPER_MODE", "fail_exit4_with_output")
t.Setenv("SCRIPTORIUM_HELPER_RECORD_PATH", filepath.Join(t.TempDir(), "record.json"))
runner := NewSubprocessRunner()
req := runReqForTest(t, writeScriptoriumHelperWrapper(t))
res, err := runner.RunArtifact(context.Background(), req)
if err == nil {
t.Fatal("RunArtifact() error = nil, want non-nil")
}
if res.ExitCode != 4 {
t.Fatalf("ExitCode = %d, want 4", res.ExitCode)
}
if !res.ValidationFailed {
t.Fatalf("ValidationFailed = false, want true")
}
if res.OutputPath != req.OutputPath {
t.Fatalf("OutputPath = %q, want %q", res.OutputPath, req.OutputPath)
}
assertFileNonEmpty(t, req.OutputPath)
}
func TestSubprocessRunnerRenderRejectsInvalidOrFailedPreview(t *testing.T) {
for _, mode := range []string{"render_invalid", "render_failure"} {
t.Run(mode, func(t *testing.T) {
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
t.Setenv("SCRIPTORIUM_HELPER_MODE", mode)
dir := t.TempDir()
req := RenderArtifactRequest{Binary: writeScriptoriumHelperWrapper(t), PromptID: "example", OutputPath: filepath.Join(dir, "preview.json"), StderrLogPath: filepath.Join(dir, "stderr.log"), Timeout: 2 * time.Second}
if _, err := NewSubprocessRunner().RenderArtifact(context.Background(), req); err == nil {
t.Fatal("expected preview error")
}
})
}
}
func TestSubprocessRunnerRunExitCodeTwoIsNotContentValidation(t *testing.T) {
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
t.Setenv("SCRIPTORIUM_HELPER_MODE", "fail_exit2_with_output")
runner := NewSubprocessRunner()
req := runReqForTest(t, writeScriptoriumHelperWrapper(t))
res, err := runner.RunArtifact(context.Background(), req)
if err == nil || res.ExitCode != 2 || res.ValidationFailed {
t.Fatalf("result = %+v, error = %v", res, err)
}
assertFileNonEmpty(t, req.OutputPath)
}
func TestSubprocessRunnerRunMissingOutputOnSuccessFails(t *testing.T) {
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
t.Setenv("SCRIPTORIUM_HELPER_MODE", "run_success_missing_output")
t.Setenv("SCRIPTORIUM_HELPER_RECORD_PATH", filepath.Join(t.TempDir(), "record.json"))
runner := NewSubprocessRunner()
req := runReqForTest(t, writeScriptoriumHelperWrapper(t))
res, err := runner.RunArtifact(context.Background(), req)
if err == nil {
t.Fatal("RunArtifact() error = nil, want non-nil")
}
if res.ExitCode != 0 {
t.Fatalf("ExitCode = %d, want 0", res.ExitCode)
}
if !strings.Contains(err.Error(), "validate scriptorium run output") {
t.Fatalf("error = %q, want output validation context", err.Error())
}
}
func TestSubprocessRunnerRenderSuccess(t *testing.T) {
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
t.Setenv("SCRIPTORIUM_HELPER_MODE", "render_success")
recordPath := filepath.Join(t.TempDir(), "record.json")
t.Setenv("SCRIPTORIUM_HELPER_RECORD_PATH", recordPath)
runner := NewSubprocessRunner()
wrapper := writeScriptoriumHelperWrapper(t)
dir := t.TempDir()
req := RenderArtifactRequest{
Binary: wrapper,
ConfigPath: "/config.yml",
PromptID: "dnd.session_recap",
ProfileID: "local-quality",
InputPaths: map[string]string{"transcript": filepath.Join(dir, "polished.json")},
Vars: map[string]string{"session_id": "test,session=value"},
OutputPath: filepath.Join(dir, "artifacts", "session_recap.render.json"),
StdoutLogPath: filepath.Join(dir, "logs", "scriptorium.render.stdout.log"),
StderrLogPath: filepath.Join(dir, "logs", "scriptorium.render.stderr.log"),
GeneratedConfigPath: filepath.Join(dir, "config", "scriptorium.render.generated.yml"),
Timeout: mustParseScriptoriumDuration(t, "2s"),
}
writeScriptoriumFile(t, req.InputPaths["transcript"], `{"segments":[]}`)
res, err := runner.RenderArtifact(context.Background(), req)
if err != nil {
t.Fatalf("RenderArtifact() error = %v", err)
}
if res.CommandMode != CommandModeRender {
t.Fatalf("CommandMode = %q, want %q", res.CommandMode, CommandModeRender)
}
if res.ExitCode != 0 {
t.Fatalf("ExitCode = %d, want 0", res.ExitCode)
}
assertFileNonEmpty(t, req.OutputPath)
if res.StdoutLogPath != "" {
t.Fatalf("stdout log = %q", res.StdoutLogPath)
}
data, err := os.ReadFile(req.OutputPath)
if err != nil || string(data) != "{\"prepared\":true}\n" {
t.Fatalf("prepared output = %q, %v", data, err)
}
rec := readScriptoriumHelperRecord(t, recordPath)
wantArgs := []string{
"promptkit", "show", "prepared", "dnd.session_recap",
"--config", "/config.yml", "--profile", "local-quality",
"--input-file", "transcript=" + req.InputPaths["transcript"],
"--var", "session_id=test,session=value",
"--format", "json",
}
if strings.Join(rec.Args, "\n") != strings.Join(wantArgs, "\n") {
t.Fatalf("args = %#v, want %#v", rec.Args, wantArgs)
}
}
func TestScriptoriumSubprocessHelper(t *testing.T) {
if os.Getenv("GO_WANT_SCRIPTORIUM_HELPER") != "1" {
return
}
args := os.Args
start := -1
for i := range args {
if args[i] == "--" {
start = i + 1
break
}
}
if start < 0 || start >= len(args) {
_, _ = os.Stderr.WriteString("missing -- args separator\n")
os.Exit(2)
}
cliArgs := args[start:]
recordPath := os.Getenv("SCRIPTORIUM_HELPER_RECORD_PATH")
if strings.TrimSpace(recordPath) != "" {
rec := scriptoriumHelperRecord{
Args: cliArgs,
Env: map[string]string{
"OPENAI_KEY_SOURCE": os.Getenv("OPENAI_KEY_SOURCE"),
"CUSTOM_PROVIDER_KEY": os.Getenv("CUSTOM_PROVIDER_KEY"),
},
}
data, _ := json.Marshal(rec)
_ = os.MkdirAll(filepath.Dir(recordPath), 0o755)
_ = os.WriteFile(recordPath, data, 0o644)
}
mode := os.Getenv("SCRIPTORIUM_HELPER_MODE")
switch mode {
case "requirements":
_, _ = os.Stdout.WriteString(`{"prompt_id":"qualified.prompt","profile_id":"qualified.profile","complete":false,"inputs":[{"name":"transcript","kind":"required","declared":true,"content_type":null,"description":"","explanation":""}],"variables":[{"name":"note","kind":"required","supplied":true,"explanation":""}],"issues":[{"code":"conditional","input_name":"transcript","variable_name":"","description":"uncertain"}]}`)
os.Exit(0)
case "requirements_failed":
_, _ = os.Stdout.WriteString(`{"prompt_id":"incomplete"}`)
_, _ = os.Stderr.WriteString("failure " + os.Getenv("CUSTOM_PROVIDER_KEY"))
os.Exit(1)
case "run_success":
_, _ = os.Stdout.Write([]byte{'a', 0, 255, '\n'})
_, _ = os.Stderr.WriteString("scriptorium helper stderr\n")
os.Exit(0)
case "run_success_missing_output":
_, _ = os.Stderr.WriteString("scriptorium helper stderr missing output\n")
os.Exit(0)
case "fail_exit1":
_, _ = os.Stderr.WriteString("scriptorium helper failure\n")
_, _ = os.Stderr.WriteString(os.Getenv("CUSTOM_PROVIDER_KEY"))
os.Exit(1)
case "fail_exit2_with_output":
_, _ = os.Stdout.WriteString("partial output\n")
_, _ = os.Stderr.WriteString("scriptorium usage failure\n")
os.Exit(2)
case "fail_exit4_with_output":
_, _ = os.Stdout.WriteString("validation failed artifact\n")
_, _ = os.Stderr.WriteString("scriptorium helper validation failure\n")
os.Exit(4)
case "render_success":
_, _ = os.Stdout.WriteString("{\"prepared\":true}\n")
_, _ = os.Stderr.WriteString("scriptorium helper render stderr\n")
os.Exit(0)
case "render_invalid":
_, _ = os.Stdout.WriteString("{broken")
os.Exit(0)
case "render_failure":
_, _ = os.Stderr.WriteString("preview failed")
os.Exit(1)
default:
_, _ = os.Stderr.WriteString(fmt.Sprintf("unknown helper mode %q\n", mode))
os.Exit(2)
}
}
type scriptoriumHelperRecord struct {
Args []string `json:"args"`
Env map[string]string `json:"env"`
}
func runReqForTest(t *testing.T, binary string) RunArtifactRequest {
t.Helper()
dir := t.TempDir()
transcriptPath := filepath.Join(dir, "polished.json")
writeScriptoriumFile(t, transcriptPath, `{"segments":[]}`)
return RunArtifactRequest{
Binary: binary,
PromptID: "dnd.session_recap",
InputPaths: map[string]string{"transcript": transcriptPath},
Vars: map[string]string{"output_kind": "session_recap"},
OutputPath: filepath.Join(dir, "artifacts", "session_recap.md"),
StdoutLogPath: filepath.Join(dir, "logs", "scriptorium.run.stdout.log"),
StderrLogPath: filepath.Join(dir, "logs", "scriptorium.run.stderr.log"),
GeneratedConfigPath: filepath.Join(dir, "config", "scriptorium.generated.yml"),
Timeout: mustParseScriptoriumDuration(t, "2s"),
}
}
func writeScriptoriumHelperWrapper(t *testing.T) string {
t.Helper()
exe, err := os.Executable()
if err != nil {
t.Fatalf("os.Executable() error = %v", err)
}
path := filepath.Join(t.TempDir(), "scriptorium-helper-wrapper.sh")
content := "#!/bin/sh\nexec \"" + exe + "\" -test.run=TestScriptoriumSubprocessHelper -- \"$@\"\n"
if err := os.WriteFile(path, []byte(content), 0o755); err != nil {
t.Fatalf("WriteFile(%q) error = %v", path, err)
}
return path
}
func mustParseScriptoriumDuration(t *testing.T, v string) time.Duration {
t.Helper()
d, err := time.ParseDuration(v)
if err != nil {
t.Fatalf("time.ParseDuration(%q) error = %v", v, err)
}
return d
}
func writeScriptoriumFile(t *testing.T, path, contents string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatalf("MkdirAll(%q): %v", path, err)
}
if err := os.WriteFile(path, []byte(contents), 0o644); err != nil {
t.Fatalf("WriteFile(%q): %v", path, err)
}
}
func assertFileNonEmpty(t *testing.T, path string) {
t.Helper()
info, err := os.Stat(path)
if err != nil {
t.Fatalf("Stat(%q): %v", path, err)
}
if info.Size() <= 0 {
t.Fatalf("file %q is empty", path)
}
}
func assertFileContains(t *testing.T, path, wantSubstring string) {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("ReadFile(%q): %v", path, err)
}
if !strings.Contains(string(data), wantSubstring) {
t.Fatalf("file %q contents = %q, want substring %q", path, string(data), wantSubstring)
}
}
func readScriptoriumHelperRecord(t *testing.T, path string) scriptoriumHelperRecord {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("ReadFile(%q): %v", path, err)
}
var rec scriptoriumHelperRecord
if err := json.Unmarshal(data, &rec); err != nil {
t.Fatalf("json unmarshal helper record: %v", err)
}
return rec
}