Add Scriptorium prompt requirements inspection
This commit is contained in:
@@ -11,6 +11,13 @@ import (
|
||||
// NoopRunner is a deterministic no-op scriptorium adapter.
|
||||
type NoopRunner struct{}
|
||||
|
||||
func (n *NoopRunner) InspectRequirements(ctx context.Context, req RequirementsRequest) (RequirementsReport, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return RequirementsReport{}, err
|
||||
}
|
||||
return emptyRequirementsReport(req.PromptID), nil
|
||||
}
|
||||
|
||||
// RunArtifact returns requested output path with placeholder metadata.
|
||||
func (n *NoopRunner) RunArtifact(ctx context.Context, req RunArtifactRequest) (ArtifactResult, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
@@ -51,12 +58,35 @@ func (n *NoopRunner) RenderArtifact(ctx context.Context, req RenderArtifactReque
|
||||
|
||||
// FakeRunner captures requests and returns deterministic responses.
|
||||
type FakeRunner struct {
|
||||
RunRequests []RunArtifactRequest
|
||||
RenderRequests []RenderArtifactRequest
|
||||
RunErr error
|
||||
RenderErr error
|
||||
RunResult ArtifactResult
|
||||
RenderResult ArtifactResult
|
||||
RunRequests []RunArtifactRequest
|
||||
RenderRequests []RenderArtifactRequest
|
||||
RunErr error
|
||||
RenderErr error
|
||||
RunResult ArtifactResult
|
||||
RenderResult ArtifactResult
|
||||
RequirementsRequests []RequirementsRequest
|
||||
RequirementsResult *RequirementsReport
|
||||
RequirementsErr error
|
||||
}
|
||||
|
||||
func (f *FakeRunner) InspectRequirements(ctx context.Context, req RequirementsRequest) (RequirementsReport, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return RequirementsReport{}, err
|
||||
}
|
||||
req.Credentials = slices.Clone(req.Credentials)
|
||||
req.Vars = cloneStringMap(req.Vars)
|
||||
f.RequirementsRequests = append(f.RequirementsRequests, req)
|
||||
if f.RequirementsErr != nil {
|
||||
return RequirementsReport{}, f.RequirementsErr
|
||||
}
|
||||
if f.RequirementsResult != nil {
|
||||
return *f.RequirementsResult, nil
|
||||
}
|
||||
return emptyRequirementsReport(req.PromptID), nil
|
||||
}
|
||||
|
||||
func emptyRequirementsReport(prompt string) RequirementsReport {
|
||||
return RequirementsReport{PromptID: prompt, Complete: true, Inputs: []RequirementInput{}, Variables: []RequirementVariable{}, Issues: []RequirementIssue{}}
|
||||
}
|
||||
|
||||
// RunArtifact records request and returns configured response.
|
||||
|
||||
@@ -75,3 +75,21 @@ func TestFakeRunnerError(t *testing.T) {
|
||||
t.Fatal("expected render error, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFakeRunnerInspectsWithoutGenerating(t *testing.T) {
|
||||
report := RequirementsReport{PromptID: "example", Complete: false, Issues: []RequirementIssue{{Code: "partial"}}}
|
||||
fake := &FakeRunner{RequirementsResult: &report}
|
||||
req := RequirementsRequest{PromptID: "example", Vars: map[string]string{"note": ""}}
|
||||
got, err := fake.InspectRequirements(context.Background(), req)
|
||||
if err != nil || got.Complete || len(got.Issues) != 1 || len(fake.RequirementsRequests) != 1 || len(fake.RunRequests) != 0 || len(fake.RenderRequests) != 0 {
|
||||
t.Fatalf("report = %+v, error = %v, requests = %+v", got, err, fake.RequirementsRequests)
|
||||
}
|
||||
req.Vars["note"] = "changed"
|
||||
if fake.RequirementsRequests[0].Vars["note"] != "" {
|
||||
t.Fatal("captured variables changed")
|
||||
}
|
||||
fake.RequirementsErr = errors.New("inspection failed")
|
||||
if _, err := fake.InspectRequirements(context.Background(), req); err == nil {
|
||||
t.Fatal("expected inspection failure")
|
||||
}
|
||||
}
|
||||
|
||||
81
internal/adapters/scriptorium/requirements.go
Normal file
81
internal/adapters/scriptorium/requirements.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package scriptorium
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/subprocess"
|
||||
)
|
||||
|
||||
// InspectRequirements discovers prompt requirements without materializing inputs.
|
||||
func (r *SubprocessRunner) InspectRequirements(ctx context.Context, req RequirementsRequest) (RequirementsReport, error) {
|
||||
if r == nil {
|
||||
return RequirementsReport{}, fmt.Errorf("scriptorium subprocess runner is nil")
|
||||
}
|
||||
if strings.TrimSpace(req.Binary) == "" || strings.TrimSpace(req.PromptID) == "" || req.Timeout <= 0 {
|
||||
return RequirementsReport{}, fmt.Errorf("scriptorium binary, prompt id, and positive timeout are required")
|
||||
}
|
||||
if req.ConfigPath != "" && strings.TrimSpace(req.ConfigPath) == "" {
|
||||
return RequirementsReport{}, fmt.Errorf("scriptorium config path must be non-empty when provided")
|
||||
}
|
||||
for name := range req.Vars {
|
||||
if strings.TrimSpace(name) == "" {
|
||||
return RequirementsReport{}, fmt.Errorf("scriptorium variable names must be non-empty")
|
||||
}
|
||||
}
|
||||
env, sensitive, err := subprocess.CredentialEnvironment(req.Credentials)
|
||||
if err != nil {
|
||||
return RequirementsReport{}, err
|
||||
}
|
||||
args := []string{"promptkit", "requirements", "show", strings.TrimSpace(req.PromptID)}
|
||||
if path := strings.TrimSpace(req.ConfigPath); path != "" {
|
||||
args = append(args, "--config", path)
|
||||
}
|
||||
if profile := strings.TrimSpace(req.ProfileID); profile != "" {
|
||||
args = append(args, "--profile", profile)
|
||||
}
|
||||
for _, kv := range sortedKeyValues(req.Vars) {
|
||||
args = append(args, "--var", kv)
|
||||
}
|
||||
args = append(args, "--format", "json")
|
||||
var output bytes.Buffer
|
||||
_, err = subprocess.Run(ctx, subprocess.RunRequest{Executable: req.Binary, Args: args, WorkingDir: req.WorkingDir, Timeout: req.Timeout, EnvOverrides: env, SensitiveEnvNames: sensitive, DiagnosticOwner: "scriptorium", StdoutResult: &output, StdoutResultLimit: MaxOutputFileBytes})
|
||||
if err != nil {
|
||||
return RequirementsReport{}, fmt.Errorf("inspect scriptorium requirements for %q: %w", req.PromptID, err)
|
||||
}
|
||||
report, err := decodeRequirements(output.Bytes())
|
||||
if err != nil {
|
||||
return RequirementsReport{}, fmt.Errorf("decode scriptorium requirements for %q: %w", req.PromptID, err)
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func decodeRequirements(data []byte) (RequirementsReport, error) {
|
||||
var raw struct {
|
||||
PromptID *string `json:"prompt_id"`
|
||||
ProfileID string `json:"profile_id"`
|
||||
Complete *bool `json:"complete"`
|
||||
Inputs []RequirementInput `json:"inputs"`
|
||||
Variables []RequirementVariable `json:"variables"`
|
||||
Issues []RequirementIssue `json:"issues"`
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
if err := decoder.Decode(&raw); err != nil {
|
||||
return RequirementsReport{}, err
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); err != io.EOF {
|
||||
if err == nil {
|
||||
return RequirementsReport{}, fmt.Errorf("multiple JSON values")
|
||||
}
|
||||
return RequirementsReport{}, err
|
||||
}
|
||||
if raw.PromptID == nil || raw.Complete == nil || raw.Inputs == nil || raw.Variables == nil || raw.Issues == nil {
|
||||
return RequirementsReport{}, fmt.Errorf("requirements report is missing required fields")
|
||||
}
|
||||
return RequirementsReport{PromptID: *raw.PromptID, ProfileID: raw.ProfileID, Complete: *raw.Complete, Inputs: raw.Inputs, Variables: raw.Variables, Issues: raw.Issues}, nil
|
||||
}
|
||||
67
internal/adapters/scriptorium/requirements_test.go
Normal file
67
internal/adapters/scriptorium/requirements_test.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package scriptorium
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestInspectRequirementsForwardsContextAndDecodesPartialReport(t *testing.T) {
|
||||
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
|
||||
t.Setenv("SCRIPTORIUM_HELPER_MODE", "requirements")
|
||||
t.Setenv("CUSTOM_PROVIDER_KEY", "synthetic-secret")
|
||||
record := filepath.Join(t.TempDir(), "args.json")
|
||||
t.Setenv("SCRIPTORIUM_HELPER_RECORD_PATH", record)
|
||||
loaded, err := configkit.Load[struct {
|
||||
Credentials []configkit.Secret `yaml:"credentials"`
|
||||
}](configkit.Bytes("test.yml", []byte("credentials: [CUSTOM_PROVIDER_KEY]\n")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := RequirementsRequest{Binary: writeScriptoriumHelperWrapper(t), ConfigPath: "/native.yml", PromptID: "qualified.prompt", ProfileID: "qualified.profile", Vars: map[string]string{"note": "", "mode": "full,more=yes"}, Credentials: loaded.Config.Credentials, WorkingDir: t.TempDir(), Timeout: 2 * time.Second}
|
||||
report, err := NewSubprocessRunner().InspectRequirements(context.Background(), req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if report.PromptID != req.PromptID || report.ProfileID != req.ProfileID || report.Complete || len(report.Inputs) != 1 || report.Inputs[0].ContentType != nil || report.Inputs[0].Description == nil || *report.Inputs[0].Description != "" || len(report.Variables) != 1 || !report.Variables[0].Supplied || len(report.Issues) != 1 {
|
||||
t.Fatalf("report = %+v", report)
|
||||
}
|
||||
rec := readScriptoriumHelperRecord(t, record)
|
||||
want := []string{"promptkit", "requirements", "show", "qualified.prompt", "--config", "/native.yml", "--profile", "qualified.profile", "--var", "mode=full,more=yes", "--var", "note=", "--format", "json"}
|
||||
if !reflect.DeepEqual(rec.Args, want) || rec.Env["CUSTOM_PROVIDER_KEY"] != "synthetic-secret" {
|
||||
t.Fatalf("invocation = %+v", rec)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectRequirementsRejectsFailedProcessAndRedactsStderr(t *testing.T) {
|
||||
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
|
||||
t.Setenv("SCRIPTORIUM_HELPER_MODE", "requirements_failed")
|
||||
t.Setenv("CUSTOM_PROVIDER_KEY", "synthetic-secret")
|
||||
loaded, err := configkit.Load[struct {
|
||||
Credentials []configkit.Secret `yaml:"credentials"`
|
||||
}](configkit.Bytes("test.yml", []byte("credentials: [CUSTOM_PROVIDER_KEY]\n")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = NewSubprocessRunner().InspectRequirements(context.Background(), RequirementsRequest{Binary: writeScriptoriumHelperWrapper(t), PromptID: "example", Credentials: loaded.Config.Credentials, Timeout: 2 * time.Second})
|
||||
if err == nil || strings.Contains(err.Error(), "synthetic-secret") || !strings.Contains(err.Error(), "<redacted>") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeRequirementsRequiresOneCompleteReportShape(t *testing.T) {
|
||||
valid := `{"prompt_id":"x","complete":true,"inputs":[],"variables":[],"issues":[],"future_field":true}`
|
||||
if report, err := decodeRequirements([]byte(valid)); err != nil || !report.Complete || report.Inputs == nil {
|
||||
t.Fatalf("report = %+v, error = %v", report, err)
|
||||
}
|
||||
for _, data := range []string{"", "null", "[]", `{}`, `{"prompt_id":null,"complete":true,"inputs":[],"variables":[],"issues":[]}`, `{"prompt_id":"x","complete":null,"inputs":[],"variables":[],"issues":[]}`, `{"prompt_id":"x","complete":true,"inputs":null,"variables":[],"issues":[]}`, valid + ` {}`, valid[:len(valid)-1]} {
|
||||
if _, err := decodeRequirements([]byte(data)); err == nil {
|
||||
t.Errorf("accepted %q", data)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,51 @@ const (
|
||||
type Runner interface {
|
||||
RunArtifact(ctx context.Context, req RunArtifactRequest) (ArtifactResult, error)
|
||||
RenderArtifact(ctx context.Context, req RenderArtifactRequest) (ArtifactResult, error)
|
||||
InspectRequirements(ctx context.Context, req RequirementsRequest) (RequirementsReport, error)
|
||||
}
|
||||
|
||||
// RequirementsRequest selects a prompt and variables for read-only discovery.
|
||||
type RequirementsRequest struct {
|
||||
Binary string
|
||||
ConfigPath string
|
||||
PromptID string
|
||||
ProfileID string
|
||||
Vars map[string]string
|
||||
Credentials []configkit.Secret
|
||||
WorkingDir string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
type RequirementsReport struct {
|
||||
PromptID string `json:"prompt_id"`
|
||||
ProfileID string `json:"profile_id"`
|
||||
Complete bool `json:"complete"`
|
||||
Inputs []RequirementInput `json:"inputs"`
|
||||
Variables []RequirementVariable `json:"variables"`
|
||||
Issues []RequirementIssue `json:"issues"`
|
||||
}
|
||||
|
||||
type RequirementInput struct {
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
Declared bool `json:"declared"`
|
||||
ContentType *string `json:"content_type"`
|
||||
Description *string `json:"description"`
|
||||
Explanation string `json:"explanation"`
|
||||
}
|
||||
|
||||
type RequirementVariable struct {
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
Supplied bool `json:"supplied"`
|
||||
Explanation string `json:"explanation"`
|
||||
}
|
||||
|
||||
type RequirementIssue struct {
|
||||
Code string `json:"code"`
|
||||
InputName string `json:"input_name"`
|
||||
VariableName string `json:"variable_name"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// RunArtifactRequest describes a production artifact-generation invocation.
|
||||
|
||||
@@ -307,7 +307,8 @@ func TestScriptoriumSubprocessHelper(t *testing.T) {
|
||||
rec := scriptoriumHelperRecord{
|
||||
Args: cliArgs,
|
||||
Env: map[string]string{
|
||||
"OPENAI_KEY_SOURCE": os.Getenv("OPENAI_KEY_SOURCE"),
|
||||
"OPENAI_KEY_SOURCE": os.Getenv("OPENAI_KEY_SOURCE"),
|
||||
"CUSTOM_PROVIDER_KEY": os.Getenv("CUSTOM_PROVIDER_KEY"),
|
||||
},
|
||||
}
|
||||
data, _ := json.Marshal(rec)
|
||||
@@ -317,6 +318,13 @@ func TestScriptoriumSubprocessHelper(t *testing.T) {
|
||||
|
||||
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")
|
||||
|
||||
Reference in New Issue
Block a user