Adopt native configuration discovery and a single PromptKit entry file
This commit is contained in:
@@ -2,15 +2,11 @@ package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
appconfig "gitea.maximumdirect.net/eric/scriptorium/internal/config"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
"go.maximumdirect.net/ckprompt"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
"go.maximumdirect.net/configkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
// Execute composes the native CLI and returns its finalized outcome. The caller
|
||||
@@ -26,13 +22,16 @@ func Execute(ctx context.Context, identity commandkit.Identity, args []string, s
|
||||
func newApp(identity commandkit.Identity) (*commandkit.App, error) {
|
||||
application := ckconfig.FromConfigKit("app", "Scriptorium application configuration.", loadApplication)
|
||||
framework := ckprompt.ConfigScope(loadEngine)
|
||||
configuration := ckconfig.Command(ckconfig.Suite[struct{}, struct{}]{
|
||||
Scopes: []ckconfig.Scope[struct{}, struct{}]{application, framework},
|
||||
configuration := ckconfig.Command(ckconfig.Suite[applicationInput, struct{}]{
|
||||
NewInput: func() applicationInput { return applicationInput{} },
|
||||
Scopes: []ckconfig.Scope[applicationInput, struct{}]{application, framework},
|
||||
})
|
||||
definitions := ckprompt.FromEngine(loadEngine)
|
||||
declarations := []commandkit.Declaration{
|
||||
commandkit.NewCommand(commandkit.CommandSpec[struct{}]{Name: "run", Summary: "Run a stored prompt.", Run: commandNotImplemented}),
|
||||
commandkit.NewCommand(commandkit.CommandSpec[struct{}]{Name: "serve", Summary: "Serve the HTTP API.", Run: commandNotImplemented}),
|
||||
commandkit.NewCommand(commandkit.CommandSpec[serveInput]{Name: "serve", Summary: "Serve the HTTP API.", Flags: serveFlags(), Run: func(commandkit.Invocation, serveInput) commandkit.Outcome {
|
||||
return commandkit.Failure("Server startup is not implemented.")
|
||||
}}),
|
||||
configuration,
|
||||
commandkit.Completion("scriptorium"),
|
||||
}
|
||||
@@ -40,14 +39,14 @@ func newApp(identity commandkit.Identity) (*commandkit.App, error) {
|
||||
return commandkit.New(identity, declarations...)
|
||||
}
|
||||
|
||||
// Application acquisition and effects are filled in independently of command
|
||||
// declaration construction; metadata operations must never reach these callbacks.
|
||||
func loadApplication(context.Context, ckconfig.Selection, struct{}, struct{}) (*configkit.Result[appconfig.Document], error) {
|
||||
return nil, errors.New("application configuration acquisition is not implemented")
|
||||
type serveInput struct {
|
||||
Selection ckconfig.Selection
|
||||
Application applicationInput
|
||||
}
|
||||
|
||||
func loadEngine(context.Context, ckconfig.Selection, struct{}, struct{}) (*promptkit.Engine, error) {
|
||||
return nil, errors.New("engine acquisition is not implemented")
|
||||
func serveFlags() []commandkit.Flag[serveInput] {
|
||||
flags := configurationSelectors(func(input *serveInput) *ckconfig.Selection { return &input.Selection })
|
||||
return append(flags, serverSelectors(func(input *serveInput) *applicationInput { return &input.Application })...)
|
||||
}
|
||||
|
||||
func commandNotImplemented(commandkit.Invocation, struct{}) commandkit.Outcome {
|
||||
|
||||
@@ -29,3 +29,16 @@ func TestNativeMetadataWithoutConfiguration(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemovedSourceAndSchemaFlagsAreRejected(t *testing.T) {
|
||||
for _, command := range [][]string{{"run"}, {"serve"}, {"config", "show"}, {"promptkit", "list", "prompts"}} {
|
||||
for _, flag := range []string{"--promptkit-source=missing.yml", "--schema-dir=schemas"} {
|
||||
args := append(append([]string{}, command...), flag)
|
||||
var output, diagnostics bytes.Buffer
|
||||
outcome := Execute(context.Background(), commandkit.Identity{Name: "scriptorium"}, args, &output, &diagnostics)
|
||||
if outcome.Kind != commandkit.OutcomeUsage || outcome.Status != 2 {
|
||||
t.Fatalf("%v: %+v", args, outcome)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
@@ -10,36 +9,6 @@ import (
|
||||
"go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
// applicationOverrides keeps explicit application flags separate from invocation state.
|
||||
func applicationOverrides(fs *flag.FlagSet) []configkit.Override {
|
||||
var overrides []configkit.Override
|
||||
fs.Visit(func(selected *flag.Flag) {
|
||||
var path configkit.Path
|
||||
switch selected.Name {
|
||||
case "promptkit-source":
|
||||
path = configkit.Keys("promptkit_sources")
|
||||
case "schema-dir":
|
||||
path = configkit.Keys("schema_dir")
|
||||
case "addr":
|
||||
path = configkit.Keys("server", "addr")
|
||||
case "artifact-root":
|
||||
path = configkit.Keys("server", "artifact_root")
|
||||
case "max-request-bytes":
|
||||
path = configkit.Keys("server", "max_request_bytes")
|
||||
case "max-artifact-bytes":
|
||||
path = configkit.Keys("server", "max_artifact_bytes")
|
||||
case "max-response-bytes":
|
||||
path = configkit.Keys("server", "max_response_bytes")
|
||||
default:
|
||||
return
|
||||
}
|
||||
overrides = append(overrides, configkit.Override{
|
||||
Path: path, Value: selected.Value.(flag.Getter).Get(), Flag: "--" + selected.Name,
|
||||
})
|
||||
})
|
||||
return overrides
|
||||
}
|
||||
|
||||
func loadApplicationSettings(configPath, overlay string, explicit bool, overrides []configkit.Override) (appconfig.AppSettings, []configkit.Diagnostic, error) {
|
||||
result, err := appconfig.Load(appconfig.LoadOptions{
|
||||
Path: configPath, Overlay: overlay, Explicit: explicit, Overrides: overrides,
|
||||
|
||||
@@ -93,7 +93,6 @@ func configCommand(args []string, stdout, stderr io.Writer) int {
|
||||
}
|
||||
|
||||
func registerConfigurationOverrides(fs *flag.FlagSet) {
|
||||
fs.String("schema-dir", "", "schema directory override")
|
||||
fs.String("addr", "", "HTTP listen address override")
|
||||
fs.String("artifact-root", "", "HTTP artifact root override")
|
||||
fs.Int64("max-request-bytes", 0, "HTTP request byte limit override")
|
||||
|
||||
24
internal/adapter/cli/engine.go
Normal file
24
internal/adapter/cli/engine.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
appconfig "gitea.maximumdirect.net/eric/scriptorium/internal/config"
|
||||
"go.maximumdirect.net/configkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
func newEngine(settings appconfig.AppSettings, options ...promptkit.Option) (*promptkit.Engine, error) {
|
||||
var main *configkit.Input
|
||||
if settings.PromptKitConfiguration != "" {
|
||||
main = &configkit.Input{Source: configkit.File(settings.PromptKitConfiguration), Imports: true}
|
||||
}
|
||||
engine, err := promptkit.NewEngine(promptkit.Config{
|
||||
Sources: promptkit.ConfigurationSources{Main: main},
|
||||
SchemaDir: settings.SchemaDir, TransientRetries: settings.TransientRetries,
|
||||
}, options...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("engine initialization from application configuration: %w", err)
|
||||
}
|
||||
return engine, nil
|
||||
}
|
||||
@@ -110,9 +110,6 @@ func parseFrameworkConfigurationArgs(args []string) (*frameworkConfigurationConf
|
||||
fs := flag.NewFlagSet("inspect configuration "+cfg.mode, flag.ContinueOnError)
|
||||
fs.SetOutput(io.Discard)
|
||||
registerConfigSelectionFlags(fs, &cfg.configPath, &cfg.configOverlay)
|
||||
var promptkitSources promptKitSourceFlagValue
|
||||
fs.Var(&promptkitSources, "promptkit-source", "selected PromptKit source path (repeatable)")
|
||||
fs.StringVar(&cfg.schemaDir, "schema-dir", "", "base directory for validation schemas")
|
||||
fs.StringVar(&cfg.path, "path", "", "JSON Pointer to explain (required for explain)")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -1,71 +1,13 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"go.maximumdirect.net/configkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
type promptKitSourceFlagEntry struct {
|
||||
selector string
|
||||
path string
|
||||
}
|
||||
|
||||
// promptKitSourceFlagValue treats each occurrence as one selected source path.
|
||||
type promptKitSourceFlagValue struct {
|
||||
entries []promptKitSourceFlagEntry
|
||||
}
|
||||
|
||||
func (value *promptKitSourceFlagValue) Set(path string) error {
|
||||
trimmed := strings.TrimSpace(path)
|
||||
if trimmed == "" {
|
||||
return errors.New("--promptkit-source requires a nonblank path")
|
||||
}
|
||||
|
||||
info, err := os.Stat(filepath.Clean(trimmed))
|
||||
if err != nil {
|
||||
reason := "unavailable"
|
||||
if errors.Is(err, os.ErrPermission) {
|
||||
reason = "permission denied"
|
||||
}
|
||||
return fmt.Errorf("--promptkit-source %q: %s", path, reason)
|
||||
}
|
||||
|
||||
selector := ""
|
||||
switch {
|
||||
case info.IsDir():
|
||||
selector = "directory"
|
||||
case info.Mode().IsRegular():
|
||||
selector = "file"
|
||||
default:
|
||||
return fmt.Errorf("--promptkit-source %q must be a regular file or directory", path)
|
||||
}
|
||||
value.entries = append(value.entries, promptKitSourceFlagEntry{selector: selector, path: path})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (value *promptKitSourceFlagValue) Get() any {
|
||||
selections := make([]any, 0, len(value.entries))
|
||||
for _, entry := range value.entries {
|
||||
selections = append(selections, map[string]any{entry.selector: entry.path})
|
||||
}
|
||||
return selections
|
||||
}
|
||||
|
||||
func (value *promptKitSourceFlagValue) String() string {
|
||||
paths := make([]string, 0, len(value.entries))
|
||||
for _, entry := range value.entries {
|
||||
paths = append(paths, entry.path)
|
||||
}
|
||||
return fmt.Sprint(paths)
|
||||
}
|
||||
|
||||
func writeFrameworkDiagnostics(output io.Writer, engine *promptkit.Engine) error {
|
||||
view, err := engine.InspectConfiguration()
|
||||
if err != nil {
|
||||
|
||||
@@ -288,7 +288,6 @@ func parseRunArgs(args []string) (*runConfig, error) {
|
||||
|
||||
registerConfigSelectionFlags(fs, &cfg.configPath, &cfg.configOverlay)
|
||||
registerExecutionRequestFlags(fs, cfg)
|
||||
fs.StringVar(&cfg.schemaDir, "schema-dir", "", "base directory for validation schemas")
|
||||
fs.DurationVar(&cfg.runTimeout, "run-timeout", 0, "whole-run execution deadline")
|
||||
fs.StringVar(&cfg.executionReportPath, "execution-report", "", "JSON execution report file path")
|
||||
|
||||
@@ -345,7 +344,6 @@ func parseRenderArgs(args []string) (*renderConfig, error) {
|
||||
|
||||
registerConfigSelectionFlags(fs, &cfg.configPath, &cfg.configOverlay)
|
||||
registerExecutionRequestFlags(fs, &cfg.runConfig)
|
||||
fs.StringVar(&cfg.schemaDir, "schema-dir", "", "base directory for validation schemas")
|
||||
|
||||
var rawFormat string
|
||||
fs.StringVar(&rawFormat, "format", "", "render output format (text|json)")
|
||||
@@ -376,9 +374,6 @@ func parseServeArgs(args []string) (*serveConfig, error) {
|
||||
|
||||
registerConfigSelectionFlags(fs, &cfg.configPath, &cfg.configOverlay)
|
||||
fs.StringVar(&cfg.addr, "addr", "", "HTTP listen address")
|
||||
var promptkitSources promptKitSourceFlagValue
|
||||
fs.Var(&promptkitSources, "promptkit-source", "selected PromptKit source path (repeatable)")
|
||||
fs.StringVar(&cfg.schemaDir, "schema-dir", "", "base directory for validation schemas")
|
||||
fs.StringVar(&cfg.artifactRoot, "artifact-root", "", "base directory for HTTP file input artifacts")
|
||||
fs.Int64Var(&cfg.maxRequestBytes, "max-request-bytes", 0, "maximum HTTP request body bytes; 0 disables the limit")
|
||||
fs.Int64Var(&cfg.maxArtifactBytes, "max-artifact-bytes", 0, "maximum HTTP file artifact bytes; 0 disables the limit")
|
||||
@@ -410,8 +405,6 @@ func parseServeArgs(args []string) (*serveConfig, error) {
|
||||
}
|
||||
|
||||
func registerExecutionRequestFlags(fs *flag.FlagSet, cfg *runConfig) {
|
||||
var promptkitSources promptKitSourceFlagValue
|
||||
fs.Var(&promptkitSources, "promptkit-source", "selected PromptKit source path (repeatable)")
|
||||
fs.StringVar(&cfg.promptID, "prompt", "", "prompt ID to run")
|
||||
fs.StringVar(&cfg.profileID, "profile", "", "optional execution profile ID; if omitted, prompt default_profile is used")
|
||||
fs.StringVar(&cfg.sessionID, "session-id", "", "optional session ID")
|
||||
@@ -495,7 +488,7 @@ func resolveCommonSettings(fs *flag.FlagSet, configPath, overlay string) (common
|
||||
maxRequestBytes: settings.MaxRequestBytes,
|
||||
maxArtifactBytes: settings.MaxArtifactBytes,
|
||||
maxResponseBytes: settings.MaxResponseBytes,
|
||||
defaultRenderFormat: settings.DefaultRenderFormat,
|
||||
defaultRenderFormat: renderformat.DefaultPreparedRunOutputFormat,
|
||||
transientRetries: settings.TransientRetries,
|
||||
diagnostics: diagnostics,
|
||||
}, nil
|
||||
@@ -515,36 +508,6 @@ func (c serveConfig) engineSettings() engineSettings {
|
||||
return engineSettings{promptkitSources: c.promptkitSources, schemaDir: c.schemaDir, transientRetries: c.transientRetries}
|
||||
}
|
||||
|
||||
func newEngine(settings engineSettings, options ...promptkit.Option) (*promptkit.Engine, error) {
|
||||
underlays := make([]configkit.Underlay, 0, len(settings.promptkitSources))
|
||||
for index, selection := range settings.promptkitSources {
|
||||
var inputs []configkit.Input
|
||||
switch {
|
||||
case selection.File != "" && selection.Directory == "":
|
||||
inputs = []configkit.Input{{Source: configkit.File(selection.File), Imports: true}}
|
||||
case selection.Directory != "" && selection.File == "":
|
||||
var err error
|
||||
inputs, err = promptkit.DirectoryInputs(selection.Directory)
|
||||
if err != nil {
|
||||
cause := fmt.Errorf("PromptKit source %d directory %q: %w", index+1, selection.Directory, err)
|
||||
return nil, fmt.Errorf("engine initialization from application configuration: %w", errors.Join(promptkit.ErrInvalidConfig, cause))
|
||||
}
|
||||
default:
|
||||
cause := fmt.Errorf("PromptKit source %d must select exactly one file or directory", index+1)
|
||||
return nil, fmt.Errorf("engine initialization from application configuration: %w", errors.Join(promptkit.ErrInvalidConfig, cause))
|
||||
}
|
||||
underlays = append(underlays, configkit.Underlay{Inputs: inputs})
|
||||
}
|
||||
engine, err := promptkit.NewEngine(promptkit.Config{
|
||||
Sources: promptkit.ConfigurationSources{Underlays: underlays},
|
||||
SchemaDir: settings.schemaDir,
|
||||
TransientRetries: settings.transientRetries,
|
||||
}, options...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("engine initialization from application configuration: %w", err)
|
||||
}
|
||||
return engine, nil
|
||||
}
|
||||
|
||||
func buildRunRequestFromConfig(cfg *runConfig) (promptkit.RunRequest, error) {
|
||||
var inputMappings map[string]string
|
||||
|
||||
97
internal/adapter/cli/selection.go
Normal file
97
internal/adapter/cli/selection.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
appconfig "gitea.maximumdirect.net/eric/scriptorium/internal/config"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
"go.maximumdirect.net/configkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
// applicationInput holds only application-owned selectors. Supplied retains the
|
||||
// distinction between omission and a caller's empty or zero value.
|
||||
type applicationInput struct {
|
||||
Addr commandkit.Supplied[string]
|
||||
ArtifactRoot commandkit.Supplied[string]
|
||||
MaxRequestBytes commandkit.Supplied[int64]
|
||||
MaxArtifactBytes commandkit.Supplied[int64]
|
||||
MaxResponseBytes commandkit.Supplied[int64]
|
||||
}
|
||||
|
||||
func configurationSelectors[I any](target func(*I) *ckconfig.Selection) []commandkit.Flag[I] {
|
||||
return []commandkit.Flag[I]{
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "config", Usage: "Select the application configuration file.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseString,
|
||||
func(input *I, value commandkit.Supplied[string]) { target(input).Config = value }),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "overlay", Usage: "Select an application overlay by name."}, (*string)(nil), parseString,
|
||||
func(input *I, value commandkit.Supplied[string]) { target(input).Overlay = value }),
|
||||
}
|
||||
}
|
||||
|
||||
func serverSelectors[I any](target func(*I) *applicationInput) []commandkit.Flag[I] {
|
||||
stringFlag := func(name, usage string, completion commandkit.CompletionHint, field func(*applicationInput) *commandkit.Supplied[string]) commandkit.Flag[I] {
|
||||
return commandkit.ValueFlag(commandkit.FlagMeta{Name: name, Usage: usage, Completion: completion}, (*string)(nil), parseString,
|
||||
func(input *I, value commandkit.Supplied[string]) { *field(target(input)) = value })
|
||||
}
|
||||
limitFlag := func(name, usage string, field func(*applicationInput) *commandkit.Supplied[int64]) commandkit.Flag[I] {
|
||||
return commandkit.ValueFlag(commandkit.FlagMeta{Name: name, Usage: usage}, (*int64)(nil), func(raw string) (int64, error) { return strconv.ParseInt(raw, 10, 64) },
|
||||
func(input *I, value commandkit.Supplied[int64]) { *field(target(input)) = value })
|
||||
}
|
||||
return []commandkit.Flag[I]{
|
||||
stringFlag("addr", "HTTP listen address.", commandkit.NoCompletion(), func(input *applicationInput) *commandkit.Supplied[string] { return &input.Addr }),
|
||||
stringFlag("artifact-root", "HTTP artifact root.", commandkit.CompleteDirectories(), func(input *applicationInput) *commandkit.Supplied[string] { return &input.ArtifactRoot }),
|
||||
limitFlag("max-request-bytes", "HTTP request byte limit (zero is unlimited).", func(input *applicationInput) *commandkit.Supplied[int64] { return &input.MaxRequestBytes }),
|
||||
limitFlag("max-artifact-bytes", "HTTP artifact byte limit (zero is unlimited).", func(input *applicationInput) *commandkit.Supplied[int64] { return &input.MaxArtifactBytes }),
|
||||
limitFlag("max-response-bytes", "HTTP response byte limit (zero is unlimited).", func(input *applicationInput) *commandkit.Supplied[int64] { return &input.MaxResponseBytes }),
|
||||
}
|
||||
}
|
||||
|
||||
func parseString(raw string) (string, error) { return raw, nil }
|
||||
|
||||
func namedApplicationOverrides(input applicationInput) []configkit.Override {
|
||||
var records []configkit.Override
|
||||
appendString := func(path configkit.Path, flag string, value commandkit.Supplied[string]) {
|
||||
if value.Set {
|
||||
records = append(records, configkit.Override{Path: path, Value: value.Value, Flag: flag})
|
||||
}
|
||||
}
|
||||
appendLimit := func(key, flag string, value commandkit.Supplied[int64]) {
|
||||
if value.Set {
|
||||
records = append(records, configkit.Override{Path: configkit.Keys("server", key), Value: value.Value, Flag: flag})
|
||||
}
|
||||
}
|
||||
appendString(configkit.Keys("server", "addr"), "--addr", input.Addr)
|
||||
appendString(configkit.Keys("server", "artifact_root"), "--artifact-root", input.ArtifactRoot)
|
||||
appendLimit("max_request_bytes", "--max-request-bytes", input.MaxRequestBytes)
|
||||
appendLimit("max_artifact_bytes", "--max-artifact-bytes", input.MaxArtifactBytes)
|
||||
appendLimit("max_response_bytes", "--max-response-bytes", input.MaxResponseBytes)
|
||||
return records
|
||||
}
|
||||
|
||||
func loadApplication(ctx context.Context, selection ckconfig.Selection, input applicationInput, _ struct{}) (*configkit.Result[appconfig.Document], error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := appconfig.Load(appconfig.LoadOptions{
|
||||
Path: selection.Config.Value, Explicit: selection.Config.Set, Overlay: selection.Overlay.Value,
|
||||
Overrides: append(namedApplicationOverrides(input), selection.Overrides...),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func loadEngine(ctx context.Context, selection ckconfig.Selection, input applicationInput, state struct{}) (*promptkit.Engine, error) {
|
||||
result, err := loadApplication(ctx, selection, input, state)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
settings := appconfig.Settings(result.Config)
|
||||
return newEngine(settings)
|
||||
}
|
||||
155
internal/adapter/cli/selection_test.go
Normal file
155
internal/adapter/cli/selection_test.go
Normal file
@@ -0,0 +1,155 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
appconfig "gitea.maximumdirect.net/eric/scriptorium/internal/config"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
"go.maximumdirect.net/configkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
func TestServerSelectorsPreservePresenceAndEvidence(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "app.yml")
|
||||
if err := os.WriteFile(path, []byte("server:\n addr: :1234\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var result *configkit.Result[appconfig.Document]
|
||||
var loadErr error
|
||||
var captured serveInput
|
||||
app, err := commandkit.New(commandkit.Identity{Name: "selectors"}, commandkit.NewCommand(commandkit.CommandSpec[serveInput]{
|
||||
Name: "serve", Flags: serveFlags(),
|
||||
Run: func(inv commandkit.Invocation, input serveInput) commandkit.Outcome {
|
||||
captured = input
|
||||
result, loadErr = loadApplication(inv.Context, input.Selection, input.Application, struct{}{})
|
||||
if loadErr != nil {
|
||||
return commandkit.Failure("load failed").WithCause(loadErr)
|
||||
}
|
||||
return commandkit.Success()
|
||||
},
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args := []string{"serve", "--config", path, "--overlay=", "--addr=", "--artifact-root", " ./a/../artifacts ", "--max-request-bytes=0", "--max-artifact-bytes=9223372036854775807", "--max-response-bytes=4294967296"}
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if outcome.Status != 0 {
|
||||
t.Fatalf("outcome=%+v err=%v", outcome, loadErr)
|
||||
}
|
||||
if !captured.Selection.Config.Set || !captured.Selection.Overlay.Set || !captured.Application.Addr.Set || !captured.Application.MaxRequestBytes.Set {
|
||||
t.Fatalf("presence lost: %+v", captured)
|
||||
}
|
||||
if result.Config.Server.Addr != "" || result.Config.Server.MaxRequestBytes != 0 || result.Config.Server.MaxArtifactBytes != math.MaxInt64 || result.Config.Server.MaxResponseBytes != 4294967296 || result.Config.Server.ArtifactRoot != "artifacts" {
|
||||
t.Fatal(result.Config)
|
||||
}
|
||||
explanation, ok := result.Explain(configkit.Keys("server", "artifact_root"))
|
||||
var cli, normalized bool
|
||||
for _, entry := range explanation.History {
|
||||
cli = cli || entry.Origin.Layer == configkit.LayerCLI
|
||||
normalized = normalized || entry.Origin.Operation == configkit.ChangeNormalization
|
||||
}
|
||||
if !ok || !cli || !normalized {
|
||||
t.Fatalf("evidence lost: %+v", explanation)
|
||||
}
|
||||
if len(namedApplicationOverrides(applicationInput{})) != 0 {
|
||||
t.Fatal("omitted HTTP flags became overrides")
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("transient_retries: 7\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fresh, err := loadApplication(context.Background(), captured.Selection, captured.Application, struct{}{})
|
||||
if err != nil || fresh.Config.TransientRetries == nil || *fresh.Config.TransientRetries != 7 || fresh == result {
|
||||
t.Fatalf("fresh load: %+v %v", fresh, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationSelectionErrorsAndCancellation(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "app.yml")
|
||||
if err := os.WriteFile(path, []byte("{}\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
selection := ckconfig.Selection{Config: commandkit.Supplied[string]{Set: true, Value: path}}
|
||||
for _, overlay := range []commandkit.Supplied[string]{{}, {Set: true}, {Set: true, Value: "default"}} {
|
||||
selection.Overlay = overlay
|
||||
if _, err := loadApplication(context.Background(), selection, applicationInput{}, struct{}{}); err != nil {
|
||||
t.Fatalf("overlay=%+v: %v", overlay, err)
|
||||
}
|
||||
}
|
||||
selection.Overlay = commandkit.Supplied[string]{Set: true, Value: "missing"}
|
||||
_, err := loadApplication(context.Background(), selection, applicationInput{}, struct{}{})
|
||||
var native *configkit.LoadError
|
||||
if !errors.As(err, &native) {
|
||||
t.Fatalf("missing overlay lost typed error: %v", err)
|
||||
}
|
||||
selection = ckconfig.Selection{Config: commandkit.Supplied[string]{Set: true}}
|
||||
if _, err := loadApplication(context.Background(), selection, applicationInput{}, struct{}{}); !errors.As(err, &native) {
|
||||
t.Fatalf("empty config lost typed error: %v", err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := loadApplication(ctx, ckconfig.Selection{}, applicationInput{}, struct{}{}); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancellation lost: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineUsesOptionalMainAndNativeResourceContexts(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
t.Chdir(root)
|
||||
write := func(path, body string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(body), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
settings := appconfig.Settings(appconfig.Document{})
|
||||
engine, err := newEngine(settings)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := engine.InspectProfile(context.Background(), "auto"); err != nil {
|
||||
t.Fatalf("bundle missing without external main: %v", err)
|
||||
}
|
||||
settings.PromptKitConfiguration = "missing.yml"
|
||||
if _, err := newEngine(settings); err == nil {
|
||||
t.Fatal("missing selected main accepted")
|
||||
}
|
||||
write("framework/main.yml", "config:\n imports:\n - glob: collections/*/collection.yml\n - glob: collections/*/collection.yaml\n")
|
||||
write("framework/collections/example/collection.yaml", "config:\n imports:\n - path: definitions.yml\ncollections:\n review:\n release_version: '1'\n")
|
||||
write("framework/collections/example/definitions.yml", "collections:\n review:\n prompts:\n - id: summary\n messages:\n - role: user\n content_file: message.txt\n output:\n format: text\n validation_mode: none\n")
|
||||
write("framework/collections/example/message.txt", "source-relative body")
|
||||
settings.PromptKitConfiguration = "framework/main.yml"
|
||||
engine, err = newEngine(settings)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = engine.InspectPrompt(context.Background(), "review/summary")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Native preparation uses the captured source-relative message resource,
|
||||
// not the process cwd or application configuration's directory.
|
||||
prepared, err := engine.Prepare(context.Background(), promptkit.RunRequest{PromptID: "review/summary", ProfileID: "auto"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(prepared.Messages) != 1 || prepared.Messages[0].Content != "source-relative body" {
|
||||
t.Fatalf("resource context lost: %+v", prepared)
|
||||
}
|
||||
view, err := engine.InspectConfiguration()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(view.Sources()) < 3 {
|
||||
t.Fatalf("native source evidence missing: %+v", view.Sources())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user