Connect shared configuration to CLI and server startup

This commit is contained in:
2026-11-23 03:27:17 +00:00
parent 69ef533d7e
commit b6693fde73
11 changed files with 206 additions and 67 deletions

View File

@@ -160,6 +160,19 @@ validation participates in the load.
## Stage 3 — Wire Shared Acquisition, Engine Handoff, And Bootstrap Diagnostics ## Stage 3 — Wire Shared Acquisition, Engine Handoff, And Bootstrap Diagnostics
**Status: Complete.** CLI acquisition forwards native bootstrap reports through
an invocation-local reporting feature, and run/server construct engines directly
from the completed application result. Server settings are consumed directly;
obsolete conversion types and schema defaults are removed. The process and HTTP
behavior remain unchanged. The former prompt/config adapter evidence machinery
is still present until its replacement in the next stage.
Go 1.27.4 offline build and configuration tests pass. Focused tests against the
production CLI files verify a controlled provider receives a bootstrapped dummy
credential without exposing it, and server bootstrap occurs before listening
and is not repeated for requests. Full CLI test compilation remains deferred
until old two-load fixtures are migrated as planned.
**Files:** `internal/adapter/cli/app.go`, `selection.go`, `engine.go`, **Files:** `internal/adapter/cli/app.go`, `selection.go`, `engine.go`,
`native_run.go`, `server.go`, `outcomes.go`; a small CLI bootstrap-report helper. `native_run.go`, `server.go`, `outcomes.go`; a small CLI bootstrap-report helper.

View File

@@ -23,7 +23,7 @@ func newApp(identity commandkit.Identity) (*commandkit.App, error) {
definitions := promptSuite() definitions := promptSuite()
declarations := []commandkit.Declaration{ declarations := []commandkit.Declaration{
commandkit.NewCommand(commandkit.CommandSpec[serveInput]{Name: "serve", Summary: "Serve the HTTP API.", Flags: serveFlags(), Run: serveHTTP}), commandkit.NewCommand(commandkit.CommandSpec[serveInput]{Name: "serve", Summary: "Serve the HTTP API.", Flags: serveFlags(), Run: serveHTTP}),
configurationCommand(), commandkit.WithInvocationFeature(configurationCommand(), bootstrapFeature()),
commandkit.Completion("scriptorium"), commandkit.Completion("scriptorium"),
} }
declarations = append(declarations, runDeclarations()...) declarations = append(declarations, runDeclarations()...)

View File

@@ -0,0 +1,43 @@
package cli
import (
"context"
"errors"
"io"
"go.maximumdirect.net/ckconfig"
"go.maximumdirect.net/commandkit"
"go.maximumdirect.net/configkit"
)
type bootstrapSinkKey struct{}
type bootstrapSink func(*configkit.SecretsReport, error)
func bootstrapFeature() commandkit.InvocationFeature {
return commandkit.NewInvocationFeature(commandkit.InvocationFeatureSpec[struct{}]{Start: func(inv commandkit.Invocation, _ struct{}) (context.Context, func() commandkit.Report) {
sink := bootstrapSink(func(report *configkit.SecretsReport, err error) {
var failure *configkit.SecretsError
if errors.As(err, &failure) && failure != nil {
diagnostics, explanation := ckconfig.AdaptDiagnostics("Secrets bootstrap:\n", nil, failure.Diagnostics())
queueDiagnostics(inv.Reporter(), diagnostics)
for _, detail := range explanation.Details {
_ = inv.Reporter().AtEnd().Warn("", detail)
}
}
if report == nil || len(report.Entries()) == 0 {
return
}
write := func(w io.Writer) error { _, err := report.WriteTo(w); return err }
failed := false
for _, entry := range report.Entries() {
failed = failed || entry.Status == configkit.SecretFileFailed || entry.Status == configkit.SecretFileNotApplied
}
if failed {
_ = inv.Reporter().AtEnd().Warn("", write)
} else {
_ = inv.Reporter().AtEnd().Info("", write)
}
})
return context.WithValue(inv.Context, bootstrapSinkKey{}, sink), nil
}})
}

View File

@@ -0,0 +1,119 @@
package cli
import (
"bytes"
"context"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"go.maximumdirect.net/commandkit"
)
func TestRunUsesConfiguredSecretsWithoutExposingValue(t *testing.T) {
const name = "SCRIPTORIUM_TEST_RUN_CREDENTIAL"
t.Setenv(name, "")
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "secrets"), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "secrets", name), []byte("synthetic-secret"), 0600); err != nil {
t.Fatal(err)
}
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer synthetic-secret" {
t.Errorf("credential not forwarded")
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"choices":[{"message":{"content":"artifact"}}]}`)
}))
defer provider.Close()
path := filepath.Join(root, "app.yml")
body := fmt.Sprintf("config: {secrets_dir: secrets, secrets_overwrite: true}\npromptkit:\n profiles:\n - id: local\n endpoint: %q\n model: controlled\n api_key_env: %s\n prompts:\n - id: selected\n default_profile: local\n messages:\n - {role: user, content: test}\n output: {format: text, validation_mode: none}\n", provider.URL+"/v1", name)
if err := os.WriteFile(path, []byte(body), 0600); err != nil {
t.Fatal(err)
}
var out, diagnostics bytes.Buffer
result := Execute(context.Background(), commandkit.Identity{Name: "scriptorium"}, []string{"run", "selected", "--config=" + path, "--verbose"}, &out, &diagnostics)
if result.Status != 0 || out.String() != "artifact" || !strings.Contains(diagnostics.String(), name) || strings.Contains(out.String()+diagnostics.String(), "synthetic-secret") {
t.Fatalf("outcome=%+v stdout=%q stderr=%q", result, out.String(), diagnostics.String())
}
}
func TestServerBootstrapsBeforeListening(t *testing.T) {
const name = "SCRIPTORIUM_TEST_SERVER_CREDENTIAL"
t.Setenv(name, "")
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "secrets"), 0700); err != nil {
t.Fatal(err)
}
secret := filepath.Join(root, "secrets", name)
if err := os.WriteFile(secret, []byte("initial"), 0600); err != nil {
t.Fatal(err)
}
path := filepath.Join(root, "app.yml")
if err := os.WriteFile(path, []byte("config: {secrets_dir: secrets, secrets_overwrite: true}\n"), 0600); err != nil {
t.Fatal(err)
}
ready := make(chan string, 1)
listen := func(ctx context.Context, network, addr string) (net.Listener, error) {
listener, err := (&net.ListenConfig{}).Listen(ctx, network, addr)
if err == nil {
ready <- listener.Addr().String()
}
return listener, err
}
cmd := commandkit.NewCommand(commandkit.CommandSpec[serveInput]{Name: "serve", Flags: serveFlags(), Run: func(inv commandkit.Invocation, input serveInput) commandkit.Outcome {
return serveWithListener(inv, input, listen)
}})
app, err := commandkit.New(commandkit.Identity{Name: "scriptorium"}, commandkit.WithInvocationFeature(cmd, bootstrapFeature()))
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var out, diagnostics bytes.Buffer
finished := make(chan commandkit.Outcome, 1)
go func() {
finished <- app.Execute(ctx, []string{"serve", "--config=" + path, "--addr=127.0.0.1:0", "--verbose"}, commandkit.Streams{Out: &out, Err: &diagnostics})
}()
var addr string
select {
case addr = <-ready:
case result := <-finished:
t.Fatalf("startup: %+v", result)
case <-time.After(5 * time.Second):
t.Fatal("listen timeout")
}
if os.Getenv(name) != "initial" {
t.Fatal("bootstrap did not precede listening")
}
if err := os.WriteFile(secret, []byte("replacement"), 0600); err != nil {
t.Fatal(err)
}
response, err := (&http.Client{Timeout: 5 * time.Second}).Get("http://" + addr + "/not-found")
if err != nil {
t.Fatal(err)
}
body, err := io.ReadAll(response.Body)
response.Body.Close()
if err != nil {
t.Fatal(err)
}
cancel()
select {
case <-finished:
case <-time.After(5 * time.Second):
t.Fatal("shutdown timeout")
}
if os.Getenv(name) != "initial" || strings.Contains(string(body)+out.String()+diagnostics.String(), "initial") || !strings.Contains(diagnostics.String(), name) {
t.Fatalf("bootstrap repeated or leaked: response=%q stdout=%q stderr=%q", body, out.String(), diagnostics.String())
}
}

View File

@@ -8,15 +8,8 @@ import (
"go.maximumdirect.net/promptkit" "go.maximumdirect.net/promptkit"
) )
func newEngine(settings appconfig.AppSettings, options ...promptkit.Option) (*promptkit.Engine, error) { func newEngine(result *configkit.Result[appconfig.Document], options ...promptkit.Option) (*promptkit.Engine, error) {
var main *configkit.Input engine, err := promptkit.NewFromConfig(result, promptkit.RuntimeConfig{TransientRetries: result.Config.TransientRetries}, options...)
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 { if err != nil {
return nil, fmt.Errorf("engine initialization from application configuration: %w", err) return nil, fmt.Errorf("engine initialization from application configuration: %w", err)
} }

View File

@@ -8,6 +8,7 @@ import (
"go.maximumdirect.net/ckconfig" "go.maximumdirect.net/ckconfig"
"go.maximumdirect.net/ckprompt" "go.maximumdirect.net/ckprompt"
"go.maximumdirect.net/commandkit" "go.maximumdirect.net/commandkit"
"go.maximumdirect.net/configkit"
"go.maximumdirect.net/promptkit" "go.maximumdirect.net/promptkit"
) )
@@ -73,30 +74,32 @@ func requestFromRunInput(input runInput) promptkit.RunRequest {
} }
func runPrompt(invocation commandkit.Invocation, input runInput) commandkit.Outcome { func runPrompt(invocation commandkit.Invocation, input runInput) commandkit.Outcome {
state := &acquisitionState{} result, err := loadApplication(invocation.Context, input.Selection, applicationInput{}, struct{}{})
engine, err := loadEngine(invocation.Context, input.Selection, applicationInput{}, state) var sources []configkit.SourceInfo
applicationFailed := errors.Is(err, errApplicationAcquisition) var records []configkit.Diagnostic
acquired, err := attachApplicationEvidence(commandkit.Acquired[*promptkit.Engine]{Value: engine}, err, state, 0, false) if result != nil {
queueDiagnostics(invocation.Reporter(), acquired.Diagnostics) sources, records = result.Sources(), result.Diagnostics()
if err != nil {
if !applicationFailed {
return frameworkFailure(invocation.Reporter(), err, acquired.Explanation)
}
return requestFailure(err, acquired.Explanation)
} }
inspection, err := engine.InspectConfiguration() var native *configkit.LoadError
if err != nil { if errors.As(err, &native) && native != nil {
return requestFailure(err, acquired.Explanation) sources, records = native.Sources(), native.Diagnostics()
} }
diagnostics, explanation := ckconfig.AdaptDiagnostics("PromptKit configuration:\n", inspection.Sources(), inspection.Diagnostics()) diagnostics, explanation := ckconfig.AdaptDiagnostics("Application configuration:\n", sources, records)
queueDiagnostics(invocation.Reporter(), diagnostics) queueDiagnostics(invocation.Reporter(), diagnostics)
if err != nil {
return requestFailure(err, explanation)
}
engine, err := newEngine(result)
if err != nil {
return requestFailure(err, explanation)
}
engine, err = engine.WithNamespaces(input.Namespaces) engine, err = engine.WithNamespaces(input.Namespaces)
if err != nil { if err != nil {
return requestFailure(err, explanation) return requestFailure(err, explanation)
} }
result, err := engine.Run(invocation.Context, requestFromRunInput(input)) runResult, err := engine.Run(invocation.Context, requestFromRunInput(input))
if err != nil { if err != nil {
return requestFailure(err, explanation) return requestFailure(err, explanation)
} }
return deliverRunResult(invocation, input, result) return deliverRunResult(invocation, input, runResult)
} }

View File

@@ -75,10 +75,13 @@ func loadApplication(ctx context.Context, selection ckconfig.Selection, input ap
if err := ctx.Err(); err != nil { if err := ctx.Err(); err != nil {
return nil, err return nil, err
} }
result, err := appconfig.Load(appconfig.LoadOptions{ result, report, err := appconfig.Load(appconfig.LoadOptions{
Path: selection.Config.Value, Explicit: selection.Config.Set, Overlay: selection.Overlay.Value, Path: selection.Config.Value, Explicit: selection.Config.Set, Overlay: selection.Overlay.Value,
Overrides: append(namedApplicationOverrides(input), selection.Overrides...), Overrides: append(namedApplicationOverrides(input), selection.Overrides...),
}) })
if sink, ok := ctx.Value(bootstrapSinkKey{}).(bootstrapSink); ok {
sink(report, err)
}
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -107,6 +110,5 @@ func loadEngine(ctx context.Context, selection ckconfig.Selection, input applica
if err != nil { if err != nil {
return nil, err return nil, err
} }
settings := appconfig.Settings(result.Config) return newEngine(result)
return newEngine(settings)
} }

View File

@@ -8,7 +8,6 @@ import (
"net/http" "net/http"
httpadapter "gitea.maximumdirect.net/eric/scriptorium/internal/adapter/http" httpadapter "gitea.maximumdirect.net/eric/scriptorium/internal/adapter/http"
appconfig "gitea.maximumdirect.net/eric/scriptorium/internal/config"
"gitea.maximumdirect.net/eric/scriptorium/internal/defaults" "gitea.maximumdirect.net/eric/scriptorium/internal/defaults"
"go.maximumdirect.net/ckconfig" "go.maximumdirect.net/ckconfig"
"go.maximumdirect.net/commandkit" "go.maximumdirect.net/commandkit"
@@ -36,27 +35,21 @@ func serveWithListener(invocation commandkit.Invocation, input serveInput, liste
if err != nil { if err != nil {
return requestFailure(err, explanation) return requestFailure(err, explanation)
} }
settings := appconfig.Settings(result.Config) settings := result.Config.Server
reader, err := httpadapter.NewRestrictedArtifactReader(settings.ArtifactRoot, settings.MaxArtifactBytes) reader, err := httpadapter.NewRestrictedArtifactReader(settings.ArtifactRoot, settings.MaxArtifactBytes)
if err != nil { if err != nil {
return commandkit.Failure("Could not initialize the HTTP artifact reader.").WithCause(err) return commandkit.Failure("Could not initialize the HTTP artifact reader.").WithCause(err)
} }
engine, err := newEngine(settings, promptkit.WithArtifactReader(reader)) engine, err := newEngine(result, promptkit.WithArtifactReader(reader))
if err != nil { if err != nil {
return frameworkFailure(invocation.Reporter(), err, explanation) return frameworkFailure(invocation.Reporter(), err, explanation)
} }
inspection, err := engine.InspectConfiguration()
if err != nil {
return requestFailure(err, explanation)
}
diagnostics, explanation = ckconfig.AdaptDiagnostics("PromptKit configuration:\n", inspection.Sources(), inspection.Diagnostics())
queueDiagnostics(invocation.Reporter(), diagnostics)
server := &http.Server{ server := &http.Server{
Addr: settings.ServerAddr, Addr: settings.Addr,
Handler: httpadapter.NewHandlerWithOptions(engine, httpadapter.HandlerOptions{MaxRequestBytes: settings.MaxRequestBytes, MaxResponseBytes: settings.MaxResponseBytes}), Handler: httpadapter.NewHandlerWithOptions(engine, httpadapter.HandlerOptions{MaxRequestBytes: settings.MaxRequestBytes, MaxResponseBytes: settings.MaxResponseBytes}),
ReadHeaderTimeout: defaults.HTTPReadHeaderTimeoutDefault, ReadHeaderTimeout: defaults.HTTPReadHeaderTimeoutDefault,
} }
listener, err := listen(invocation.Context, "tcp", settings.ServerAddr) listener, err := listen(invocation.Context, "tcp", settings.Addr)
if err != nil { if err != nil {
return commandkit.Failure("Could not listen for HTTP requests.").WithCause(err) return commandkit.Failure("Could not listen for HTTP requests.").WithCause(err)
} }

View File

@@ -44,16 +44,3 @@ func Load(options LoadOptions) (*configkit.Result[Document], *configkit.SecretsR
} }
return result, report, nil return result, report, nil
} }
// Settings converts a validated document without another merge or normalization.
func Settings(document Document) AppSettings {
settings := AppSettings{
ServerAddr: document.Server.Addr,
ArtifactRoot: document.Server.ArtifactRoot,
MaxRequestBytes: document.Server.MaxRequestBytes,
MaxArtifactBytes: document.Server.MaxArtifactBytes,
MaxResponseBytes: document.Server.MaxResponseBytes,
TransientRetries: document.TransientRetries,
}
return settings
}

View File

@@ -1,13 +0,0 @@
package config
// AppSettings holds the validated application values used by executable adapters.
type AppSettings struct {
PromptKitConfiguration string
SchemaDir string
ServerAddr string
ArtifactRoot string
MaxRequestBytes int64
MaxArtifactBytes int64
MaxResponseBytes int64
TransientRetries *int
}

View File

@@ -4,7 +4,6 @@ import "time"
const ( const (
HTTPAddrDefault = ":8080" HTTPAddrDefault = ":8080"
SchemaDirDefault = "."
HTTPMaxRequestBytesDefault = 16 * 1024 * 1024 HTTPMaxRequestBytesDefault = 16 * 1024 * 1024
HTTPMaxArtifactBytesDefault = 16 * 1024 * 1024 HTTPMaxArtifactBytesDefault = 16 * 1024 * 1024
HTTPMaxResponseBytesDefault = 16 * 1024 * 1024 HTTPMaxResponseBytesDefault = 16 * 1024 * 1024