Use native Scriptorium generation and capture its output
This commit is contained in:
@@ -84,6 +84,8 @@ Check: `go test ./internal/adapters/subprocess`.
|
|||||||
|
|
||||||
## Stage 2: Migrate Scriptorium generation
|
## Stage 2: Migrate Scriptorium generation
|
||||||
|
|
||||||
|
**Status: Complete.** Trim/analyze diagnostic bookkeeping remains for Stage 3.
|
||||||
|
|
||||||
**Purpose:** Make native `run` deliver the artifact through Narratio's result
|
**Purpose:** Make native `run` deliver the artifact through Narratio's result
|
||||||
capture while retaining existing success and failure rules.
|
capture while retaining existing success and failure rules.
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ package scriptorium
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -60,6 +62,10 @@ func (r *SubprocessRunner) RunArtifact(ctx context.Context, req RunArtifactReque
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
output, err := openResultFile(req.OutputPath)
|
||||||
|
if err != nil {
|
||||||
|
return ArtifactResult{}, fmt.Errorf("open scriptorium output %q: %w", req.OutputPath, err)
|
||||||
|
}
|
||||||
runRes, runErr := subprocess.Run(ctx, subprocess.RunRequest{
|
runRes, runErr := subprocess.Run(ctx, subprocess.RunRequest{
|
||||||
Executable: req.Binary,
|
Executable: req.Binary,
|
||||||
Args: args,
|
Args: args,
|
||||||
@@ -68,13 +74,17 @@ func (r *SubprocessRunner) RunArtifact(ctx context.Context, req RunArtifactReque
|
|||||||
EnvOverrides: envOverrides,
|
EnvOverrides: envOverrides,
|
||||||
SensitiveEnvNames: sensitiveNames,
|
SensitiveEnvNames: sensitiveNames,
|
||||||
DiagnosticOwner: "scriptorium",
|
DiagnosticOwner: "scriptorium",
|
||||||
StdoutLogPath: req.StdoutLogPath,
|
StdoutResult: output,
|
||||||
|
StdoutResultLimit: MaxOutputFileBytes,
|
||||||
StderrLogPath: req.StderrLogPath,
|
StderrLogPath: req.StderrLogPath,
|
||||||
})
|
})
|
||||||
|
if closeErr := output.Close(); closeErr != nil {
|
||||||
|
runErr = errors.Join(runErr, fmt.Errorf("close scriptorium output %q: %w", req.OutputPath, closeErr))
|
||||||
|
}
|
||||||
|
|
||||||
result := ArtifactResult{
|
result := ArtifactResult{
|
||||||
OutputPath: req.OutputPath,
|
OutputPath: req.OutputPath,
|
||||||
StdoutLogPath: req.StdoutLogPath,
|
StdoutLogPath: runRes.StdoutLogPath,
|
||||||
StderrLogPath: req.StderrLogPath,
|
StderrLogPath: req.StderrLogPath,
|
||||||
GeneratedConfigPath: req.GeneratedConfigPath,
|
GeneratedConfigPath: req.GeneratedConfigPath,
|
||||||
ExitCode: runRes.ExitCode,
|
ExitCode: runRes.ExitCode,
|
||||||
@@ -92,14 +102,14 @@ func (r *SubprocessRunner) RunArtifact(ctx context.Context, req RunArtifactReque
|
|||||||
}
|
}
|
||||||
|
|
||||||
if runErr != nil {
|
if runErr != nil {
|
||||||
if runRes.ExitCode == 2 {
|
if runRes.ExitCode == 4 {
|
||||||
result.ValidationFailed = true
|
result.ValidationFailed = true
|
||||||
exists, size, statErr := fileExistsWithSize(req.OutputPath)
|
exists, size, statErr := fileExistsWithSize(req.OutputPath)
|
||||||
if statErr == nil {
|
if statErr == nil {
|
||||||
result.Metadata["output_exists"] = exists
|
result.Metadata["output_exists"] = exists
|
||||||
result.Metadata["output_size_bytes"] = size
|
result.Metadata["output_size_bytes"] = size
|
||||||
}
|
}
|
||||||
return result, fmt.Errorf("scriptorium run exited with validation failure (exit code 2): %w", runErr)
|
return result, fmt.Errorf("scriptorium run exited with validation failure (exit code 4): %w", runErr)
|
||||||
}
|
}
|
||||||
return result, fmt.Errorf("run scriptorium artifact (binary=%q): %w", req.Binary, runErr)
|
return result, fmt.Errorf("run scriptorium artifact (binary=%q): %w", req.Binary, runErr)
|
||||||
}
|
}
|
||||||
@@ -231,7 +241,7 @@ func validateCommonRunRequest(
|
|||||||
}
|
}
|
||||||
|
|
||||||
func buildRunArgs(req RunArtifactRequest) []string {
|
func buildRunArgs(req RunArtifactRequest) []string {
|
||||||
args := []string{"run", "--prompt", strings.TrimSpace(req.PromptID)}
|
args := []string{"run", strings.TrimSpace(req.PromptID)}
|
||||||
if cfgPath := strings.TrimSpace(req.ConfigPath); cfgPath != "" {
|
if cfgPath := strings.TrimSpace(req.ConfigPath); cfgPath != "" {
|
||||||
args = append(args, "--config", cfgPath)
|
args = append(args, "--config", cfgPath)
|
||||||
}
|
}
|
||||||
@@ -239,16 +249,37 @@ func buildRunArgs(req RunArtifactRequest) []string {
|
|||||||
args = append(args, "--profile", profileID)
|
args = append(args, "--profile", profileID)
|
||||||
}
|
}
|
||||||
for _, kv := range sortedKeyValues(req.InputPaths) {
|
for _, kv := range sortedKeyValues(req.InputPaths) {
|
||||||
args = append(args, "--input", kv)
|
args = append(args, "--input-file", kv)
|
||||||
}
|
}
|
||||||
for _, kv := range sortedKeyValues(req.Vars) {
|
for _, kv := range sortedKeyValues(req.Vars) {
|
||||||
args = append(args, "--var", kv)
|
args = append(args, "--var", kv)
|
||||||
}
|
}
|
||||||
args = append(args, "--timeout", req.Timeout.String())
|
args = append(args, "--run-timeout", req.Timeout.String(), "--format", "text")
|
||||||
args = append(args, "--out", req.OutputPath)
|
|
||||||
return args
|
return args
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func openResultFile(path string) (*os.File, error) {
|
||||||
|
if err := fileops.EnsureWorkspaceDirectory(filepath.Dir(path)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
info, err := os.Lstat(path)
|
||||||
|
if err == nil && !info.Mode().IsRegular() {
|
||||||
|
return nil, fmt.Errorf("output is not a regular file")
|
||||||
|
}
|
||||||
|
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fileops.WorkspaceFileMode)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := file.Chmod(fileops.WorkspaceFileMode); err != nil {
|
||||||
|
_ = file.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return file, nil
|
||||||
|
}
|
||||||
|
|
||||||
func buildRenderArgs(req RenderArtifactRequest) []string {
|
func buildRenderArgs(req RenderArtifactRequest) []string {
|
||||||
args := []string{"render", "--prompt", strings.TrimSpace(req.PromptID)}
|
args := []string{"render", "--prompt", strings.TrimSpace(req.PromptID)}
|
||||||
if cfgPath := strings.TrimSpace(req.ConfigPath); cfgPath != "" {
|
if cfgPath := strings.TrimSpace(req.ConfigPath); cfgPath != "" {
|
||||||
@@ -320,6 +351,9 @@ func writeInvocationConfig(path string, payload invocationPayload) error {
|
|||||||
"render_format": payload.RenderFormat,
|
"render_format": payload.RenderFormat,
|
||||||
"render_prompt_logged": payload.RenderPromptStore,
|
"render_prompt_logged": payload.RenderPromptStore,
|
||||||
}
|
}
|
||||||
|
if payload.Mode == CommandModeRun {
|
||||||
|
data["stdout_destination"] = payload.OutputPath
|
||||||
|
}
|
||||||
return writeGeneratedYAML(path, data)
|
return writeGeneratedYAML(path, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package scriptorium
|
package scriptorium
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -36,8 +37,8 @@ func TestSubprocessRunnerRunSuccessBuildsDeterministicArgsAndCapturesLogs(t *tes
|
|||||||
ConfigPath: "/etc/scriptorium/config.yml",
|
ConfigPath: "/etc/scriptorium/config.yml",
|
||||||
PromptID: "dnd.session_recap",
|
PromptID: "dnd.session_recap",
|
||||||
ProfileID: "local-quality",
|
ProfileID: "local-quality",
|
||||||
InputPaths: map[string]string{"transcript": filepath.Join(dir, "polished.json"), "other": filepath.Join(dir, "other.md")},
|
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"},
|
Vars: map[string]string{"session_id": "2026-05-03", "campaign_name": "Icewind,Dale=North"},
|
||||||
OutputPath: filepath.Join(dir, "artifacts", "session_recap.md"),
|
OutputPath: filepath.Join(dir, "artifacts", "session_recap.md"),
|
||||||
StdoutLogPath: filepath.Join(dir, "logs", "scriptorium.run.stdout.log"),
|
StdoutLogPath: filepath.Join(dir, "logs", "scriptorium.run.stdout.log"),
|
||||||
StderrLogPath: filepath.Join(dir, "logs", "scriptorium.run.stderr.log"),
|
StderrLogPath: filepath.Join(dir, "logs", "scriptorium.run.stderr.log"),
|
||||||
@@ -65,22 +66,30 @@ func TestSubprocessRunnerRunSuccessBuildsDeterministicArgsAndCapturesLogs(t *tes
|
|||||||
t.Fatalf("Duration = %s, want > 0", res.Duration)
|
t.Fatalf("Duration = %s, want > 0", res.Duration)
|
||||||
}
|
}
|
||||||
|
|
||||||
assertFileNonEmpty(t, req.OutputPath)
|
data, err := os.ReadFile(req.OutputPath)
|
||||||
assertFileContains(t, req.StdoutLogPath, "scriptorium helper stdout")
|
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")
|
assertFileContains(t, req.StderrLogPath, "scriptorium helper stderr")
|
||||||
|
|
||||||
rec := readScriptoriumHelperRecord(t, recordPath)
|
rec := readScriptoriumHelperRecord(t, recordPath)
|
||||||
wantArgs := []string{
|
wantArgs := []string{
|
||||||
"run",
|
"run",
|
||||||
"--prompt", "dnd.session_recap",
|
"dnd.session_recap",
|
||||||
"--config", "/etc/scriptorium/config.yml",
|
"--config", "/etc/scriptorium/config.yml",
|
||||||
"--profile", "local-quality",
|
"--profile", "local-quality",
|
||||||
"--input", "other=" + req.InputPaths["other"],
|
"--input-file", "other=" + req.InputPaths["other"],
|
||||||
"--input", "transcript=" + req.InputPaths["transcript"],
|
"--input-file", "transcript=" + req.InputPaths["transcript"],
|
||||||
"--var", "campaign_name=Icewind Dale",
|
"--var", "campaign_name=Icewind,Dale=North",
|
||||||
"--var", "session_id=2026-05-03",
|
"--var", "session_id=2026-05-03",
|
||||||
"--timeout", "2s",
|
"--run-timeout", "2s",
|
||||||
"--out", req.OutputPath,
|
"--format", "text",
|
||||||
}
|
}
|
||||||
if strings.Join(rec.Args, "\n") != strings.Join(wantArgs, "\n") {
|
if strings.Join(rec.Args, "\n") != strings.Join(wantArgs, "\n") {
|
||||||
t.Fatalf("args = %#v, want %#v", rec.Args, wantArgs)
|
t.Fatalf("args = %#v, want %#v", rec.Args, wantArgs)
|
||||||
@@ -96,6 +105,20 @@ func TestSubprocessRunnerRunSuccessBuildsDeterministicArgsAndCapturesLogs(t *tes
|
|||||||
if strings.Contains(string(cfgData), "super-secret") {
|
if strings.Contains(string(cfgData), "super-secret") {
|
||||||
t.Fatalf("generated config must not include credential value")
|
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) {
|
func TestSubprocessRunnerRunExitCodeOneFails(t *testing.T) {
|
||||||
@@ -136,9 +159,9 @@ func TestSubprocessRunnerRunExitCodeOneFails(t *testing.T) {
|
|||||||
assertFileContains(t, req.StderrLogPath, "scriptorium helper failure")
|
assertFileContains(t, req.StderrLogPath, "scriptorium helper failure")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSubprocessRunnerRunExitCodeTwoReturnsValidationFailureAndPreservesOutput(t *testing.T) {
|
func TestSubprocessRunnerRunExitCodeFourReturnsValidationFailureAndPreservesOutput(t *testing.T) {
|
||||||
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
|
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
|
||||||
t.Setenv("SCRIPTORIUM_HELPER_MODE", "fail_exit2_with_output")
|
t.Setenv("SCRIPTORIUM_HELPER_MODE", "fail_exit4_with_output")
|
||||||
t.Setenv("SCRIPTORIUM_HELPER_RECORD_PATH", filepath.Join(t.TempDir(), "record.json"))
|
t.Setenv("SCRIPTORIUM_HELPER_RECORD_PATH", filepath.Join(t.TempDir(), "record.json"))
|
||||||
|
|
||||||
runner := NewSubprocessRunner()
|
runner := NewSubprocessRunner()
|
||||||
@@ -147,8 +170,8 @@ func TestSubprocessRunnerRunExitCodeTwoReturnsValidationFailureAndPreservesOutpu
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("RunArtifact() error = nil, want non-nil")
|
t.Fatal("RunArtifact() error = nil, want non-nil")
|
||||||
}
|
}
|
||||||
if res.ExitCode != 2 {
|
if res.ExitCode != 4 {
|
||||||
t.Fatalf("ExitCode = %d, want 2", res.ExitCode)
|
t.Fatalf("ExitCode = %d, want 4", res.ExitCode)
|
||||||
}
|
}
|
||||||
if !res.ValidationFailed {
|
if !res.ValidationFailed {
|
||||||
t.Fatalf("ValidationFailed = false, want true")
|
t.Fatalf("ValidationFailed = false, want true")
|
||||||
@@ -159,6 +182,18 @@ func TestSubprocessRunnerRunExitCodeTwoReturnsValidationFailureAndPreservesOutpu
|
|||||||
assertFileNonEmpty(t, req.OutputPath)
|
assertFileNonEmpty(t, req.OutputPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
func TestSubprocessRunnerRunMissingOutputOnSuccessFails(t *testing.T) {
|
||||||
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
|
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
|
||||||
t.Setenv("SCRIPTORIUM_HELPER_MODE", "run_success_missing_output")
|
t.Setenv("SCRIPTORIUM_HELPER_MODE", "run_success_missing_output")
|
||||||
@@ -261,12 +296,10 @@ func TestScriptoriumSubprocessHelper(t *testing.T) {
|
|||||||
mode := os.Getenv("SCRIPTORIUM_HELPER_MODE")
|
mode := os.Getenv("SCRIPTORIUM_HELPER_MODE")
|
||||||
switch mode {
|
switch mode {
|
||||||
case "run_success":
|
case "run_success":
|
||||||
writeScriptoriumHelperFile(outputPath, "generated artifact\n")
|
_, _ = os.Stdout.Write([]byte{'a', 0, 255, '\n'})
|
||||||
_, _ = 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)
|
||||||
case "run_success_missing_output":
|
case "run_success_missing_output":
|
||||||
_, _ = os.Stdout.WriteString("scriptorium helper stdout missing output\n")
|
|
||||||
_, _ = os.Stderr.WriteString("scriptorium helper stderr missing output\n")
|
_, _ = os.Stderr.WriteString("scriptorium helper stderr missing output\n")
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
case "fail_exit1":
|
case "fail_exit1":
|
||||||
@@ -274,9 +307,13 @@ func TestScriptoriumSubprocessHelper(t *testing.T) {
|
|||||||
_, _ = os.Stderr.WriteString(os.Getenv("CUSTOM_PROVIDER_KEY"))
|
_, _ = os.Stderr.WriteString(os.Getenv("CUSTOM_PROVIDER_KEY"))
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
case "fail_exit2_with_output":
|
case "fail_exit2_with_output":
|
||||||
writeScriptoriumHelperFile(outputPath, "validation failed artifact\n")
|
_, _ = os.Stdout.WriteString("partial output\n")
|
||||||
_, _ = os.Stderr.WriteString("scriptorium helper validation failure\n")
|
_, _ = os.Stderr.WriteString("scriptorium usage failure\n")
|
||||||
os.Exit(2)
|
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":
|
case "render_success":
|
||||||
writeScriptoriumHelperFile(outputPath, "{\"rendered\":true}\n")
|
writeScriptoriumHelperFile(outputPath, "{\"rendered\":true}\n")
|
||||||
_, _ = os.Stdout.WriteString("scriptorium helper render stdout\n")
|
_, _ = os.Stdout.WriteString("scriptorium helper render stdout\n")
|
||||||
|
|||||||
Reference in New Issue
Block a user