diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 9497d81..ecaad94 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -84,6 +84,8 @@ Check: `go test ./internal/adapters/subprocess`. ## 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 capture while retaining existing success and failure rules. diff --git a/internal/adapters/scriptorium/subprocess.go b/internal/adapters/scriptorium/subprocess.go index eb7751f..650e524 100644 --- a/internal/adapters/scriptorium/subprocess.go +++ b/internal/adapters/scriptorium/subprocess.go @@ -2,8 +2,10 @@ package scriptorium import ( "context" + "errors" "fmt" "os" + "path/filepath" "sort" "strings" "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{ Executable: req.Binary, Args: args, @@ -68,13 +74,17 @@ func (r *SubprocessRunner) RunArtifact(ctx context.Context, req RunArtifactReque EnvOverrides: envOverrides, SensitiveEnvNames: sensitiveNames, DiagnosticOwner: "scriptorium", - StdoutLogPath: req.StdoutLogPath, + StdoutResult: output, + StdoutResultLimit: MaxOutputFileBytes, 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{ OutputPath: req.OutputPath, - StdoutLogPath: req.StdoutLogPath, + StdoutLogPath: runRes.StdoutLogPath, StderrLogPath: req.StderrLogPath, GeneratedConfigPath: req.GeneratedConfigPath, ExitCode: runRes.ExitCode, @@ -92,14 +102,14 @@ func (r *SubprocessRunner) RunArtifact(ctx context.Context, req RunArtifactReque } if runErr != nil { - if runRes.ExitCode == 2 { + if runRes.ExitCode == 4 { result.ValidationFailed = true exists, size, statErr := fileExistsWithSize(req.OutputPath) if statErr == nil { result.Metadata["output_exists"] = exists 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) } @@ -231,7 +241,7 @@ func validateCommonRunRequest( } 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 != "" { args = append(args, "--config", cfgPath) } @@ -239,16 +249,37 @@ func buildRunArgs(req RunArtifactRequest) []string { args = append(args, "--profile", profileID) } for _, kv := range sortedKeyValues(req.InputPaths) { - args = append(args, "--input", kv) + args = append(args, "--input-file", kv) } for _, kv := range sortedKeyValues(req.Vars) { args = append(args, "--var", kv) } - args = append(args, "--timeout", req.Timeout.String()) - args = append(args, "--out", req.OutputPath) + args = append(args, "--run-timeout", req.Timeout.String(), "--format", "text") 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 { args := []string{"render", "--prompt", strings.TrimSpace(req.PromptID)} if cfgPath := strings.TrimSpace(req.ConfigPath); cfgPath != "" { @@ -320,6 +351,9 @@ func writeInvocationConfig(path string, payload invocationPayload) error { "render_format": payload.RenderFormat, "render_prompt_logged": payload.RenderPromptStore, } + if payload.Mode == CommandModeRun { + data["stdout_destination"] = payload.OutputPath + } return writeGeneratedYAML(path, data) } diff --git a/internal/adapters/scriptorium/subprocess_test.go b/internal/adapters/scriptorium/subprocess_test.go index 333cbde..c4a01bb 100644 --- a/internal/adapters/scriptorium/subprocess_test.go +++ b/internal/adapters/scriptorium/subprocess_test.go @@ -1,6 +1,7 @@ package scriptorium import ( + "bytes" "context" "encoding/json" "fmt" @@ -36,8 +37,8 @@ func TestSubprocessRunnerRunSuccessBuildsDeterministicArgsAndCapturesLogs(t *tes 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.md")}, - Vars: map[string]string{"session_id": "2026-05-03", "campaign_name": "Icewind Dale"}, + 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"), @@ -65,22 +66,30 @@ func TestSubprocessRunnerRunSuccessBuildsDeterministicArgsAndCapturesLogs(t *tes t.Fatalf("Duration = %s, want > 0", res.Duration) } - assertFileNonEmpty(t, req.OutputPath) - assertFileContains(t, req.StdoutLogPath, "scriptorium helper stdout") + 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", - "--prompt", "dnd.session_recap", + "dnd.session_recap", "--config", "/etc/scriptorium/config.yml", "--profile", "local-quality", - "--input", "other=" + req.InputPaths["other"], - "--input", "transcript=" + req.InputPaths["transcript"], - "--var", "campaign_name=Icewind Dale", + "--input-file", "other=" + req.InputPaths["other"], + "--input-file", "transcript=" + req.InputPaths["transcript"], + "--var", "campaign_name=Icewind,Dale=North", "--var", "session_id=2026-05-03", - "--timeout", "2s", - "--out", req.OutputPath, + "--run-timeout", "2s", + "--format", "text", } if strings.Join(rec.Args, "\n") != strings.Join(wantArgs, "\n") { t.Fatalf("args = %#v, want %#v", rec.Args, wantArgs) @@ -96,6 +105,20 @@ func TestSubprocessRunnerRunSuccessBuildsDeterministicArgsAndCapturesLogs(t *tes 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) { @@ -136,9 +159,9 @@ func TestSubprocessRunnerRunExitCodeOneFails(t *testing.T) { 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("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")) runner := NewSubprocessRunner() @@ -147,8 +170,8 @@ func TestSubprocessRunnerRunExitCodeTwoReturnsValidationFailureAndPreservesOutpu if err == nil { t.Fatal("RunArtifact() error = nil, want non-nil") } - if res.ExitCode != 2 { - t.Fatalf("ExitCode = %d, want 2", res.ExitCode) + if res.ExitCode != 4 { + t.Fatalf("ExitCode = %d, want 4", res.ExitCode) } if !res.ValidationFailed { t.Fatalf("ValidationFailed = false, want true") @@ -159,6 +182,18 @@ func TestSubprocessRunnerRunExitCodeTwoReturnsValidationFailureAndPreservesOutpu 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) { t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1") t.Setenv("SCRIPTORIUM_HELPER_MODE", "run_success_missing_output") @@ -261,12 +296,10 @@ func TestScriptoriumSubprocessHelper(t *testing.T) { mode := os.Getenv("SCRIPTORIUM_HELPER_MODE") switch mode { case "run_success": - writeScriptoriumHelperFile(outputPath, "generated artifact\n") - _, _ = os.Stdout.WriteString("scriptorium helper stdout\n") + _, _ = os.Stdout.Write([]byte{'a', 0, 255, '\n'}) _, _ = os.Stderr.WriteString("scriptorium helper stderr\n") os.Exit(0) case "run_success_missing_output": - _, _ = os.Stdout.WriteString("scriptorium helper stdout missing output\n") _, _ = os.Stderr.WriteString("scriptorium helper stderr missing output\n") os.Exit(0) case "fail_exit1": @@ -274,9 +307,13 @@ func TestScriptoriumSubprocessHelper(t *testing.T) { _, _ = os.Stderr.WriteString(os.Getenv("CUSTOM_PROVIDER_KEY")) os.Exit(1) case "fail_exit2_with_output": - writeScriptoriumHelperFile(outputPath, "validation failed artifact\n") - _, _ = os.Stderr.WriteString("scriptorium helper validation failure\n") + _, _ = 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": writeScriptoriumHelperFile(outputPath, "{\"rendered\":true}\n") _, _ = os.Stdout.WriteString("scriptorium helper render stdout\n")