From 1ca5011049b6e9a46165dcd6ff7752ffbc5a7eb4 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Mon, 23 Nov 2026 04:20:31 +0000 Subject: [PATCH] Bootstrap secrets for shared configuration acquisition --- docs/roadmap/implementation.md | 9 ++ internal/appconfig/config.go | 23 ++++- internal/appconfig/config_test.go | 4 +- internal/appconfig/glossary_test.go | 13 +-- internal/appconfig/secrets_test.go | 75 ++++++++++++++++ internal/appconfig/sources_test.go | 12 +-- internal/cli/app_wiring.go | 9 +- internal/cli/app_wiring_test.go | 37 ++++++++ internal/cli/bootstrap.go | 117 ++++++++++++++++++++++++ internal/cli/bootstrap_test.go | 133 ++++++++++++++++++++++++++++ internal/cli/process.go | 6 +- internal/cli/process_inputs.go | 6 +- internal/cli/process_pipeline.go | 2 +- 13 files changed, 422 insertions(+), 24 deletions(-) create mode 100644 internal/appconfig/secrets_test.go create mode 100644 internal/cli/bootstrap.go create mode 100644 internal/cli/bootstrap_test.go diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index a081bfd..be85ada 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -159,6 +159,15 @@ Exercise prepared-main reuse at this boundary without cloning upstream's full file/overwrite test matrix. Check help-only paths and representative native inspection; use existing `app_wiring_test.go` and process input tests as owners. +**Complete.** Shared loading prepares the selected main once, bootstraps secrets, +retains the native report and error, and forwards safe details through the +invocation reporter. Focused assembly and isolated native-adapter tests pass +for overwrite, failure, cancellation, help, independent comparisons, and +diagnostic write errors. Full CLI and engine handoff tests are deferred until +the runtime accepts the combined result in the next stage and the removed +PromptKit APIs are migrated. The prepared-source snapshot test confirms reuse +when an already prepared source is supplied. + ## Stage 3: Construct the Engine from the Result and Track Native Source Origins **Outcome:** The LLM runtime captures resources from the shared result without diff --git a/internal/appconfig/config.go b/internal/appconfig/config.go index 21bf23f..f5a2d3b 100644 --- a/internal/appconfig/config.go +++ b/internal/appconfig/config.go @@ -2,6 +2,8 @@ package appconfig import ( + "context" + "errors" "fmt" "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" @@ -58,10 +60,21 @@ func Definition() ck.Definition[Config] { } // Load composes built-in resources and optional companions with the selected input. -func Load(input ck.Input, overlay string, overrides ...ck.Override) (*ck.Result[Config], error) { +func Load(ctx context.Context, input ck.Input, overlay string, overrides ...ck.Override) (*ck.Result[Config], *ck.SecretsReport, error) { + if err := ctx.Err(); err != nil { + return nil, nil, err + } + report, prepared, err := ck.LoadSecretsIntoEnvironmentFromConfig(input.Source, ck.SecretsFromConfigOptions{Filesystem: input.Filesystem}) + if canceled := ctx.Err(); canceled != nil { + return nil, report, errors.Join(err, canceled) + } + if err != nil { + return nil, report, err + } + input.Source = prepared embedded, err := pk.FilesystemInputs("Audita embedded prompts", prompts.Filesystem(), prompts.AssetRoot) if err != nil { - return nil, fmt.Errorf("discover embedded prompts: %w", err) + return nil, report, fmt.Errorf("discover embedded prompts: %w", err) } for i := range embedded { embedded[i].Destination = ck.Keys("promptkit") @@ -73,7 +86,7 @@ func Load(input ck.Input, overlay string, overrides ...ck.Override) (*ck.Result[ Filesystem: &ck.FilesystemContext{FS: &schemas, Root: ".", BaseDir: "."}, }) input.Imports = true - return ck.LoadLayered(input, ck.LayeredOptions[Config]{ + result, err := ck.LoadLayered(input, ck.LayeredOptions[Config]{ Definition: Definition(), Overlay: overlay, Overrides: overrides, @@ -86,4 +99,8 @@ func Load(input ck.Input, overlay string, overrides ...ck.Override) (*ck.Result[ }}, }, }) + if canceled := ctx.Err(); canceled != nil { + return nil, report, errors.Join(err, canceled) + } + return result, report, err } diff --git a/internal/appconfig/config_test.go b/internal/appconfig/config_test.go index 45463f7..349bd8d 100644 --- a/internal/appconfig/config_test.go +++ b/internal/appconfig/config_test.go @@ -26,7 +26,7 @@ func TestLoadCombinesApplicationAndPromptSettings(t *testing.T) { t.Fatal(err) } } - result, err := Load(ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "selected") + result, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "selected") if err != nil { t.Fatal(err) } @@ -62,7 +62,7 @@ func TestLoadWithoutMainDoesNotDiscoverCompanions(t *testing.T) { t.Fatal(err) } t.Chdir(dir) - result, err := Load(ck.Input{Source: ck.NoSource()}, "") + result, _, err := Load(context.Background(), ck.Input{Source: ck.NoSource()}, "") if err != nil { t.Fatal(err) } diff --git a/internal/appconfig/glossary_test.go b/internal/appconfig/glossary_test.go index 5bb3484..3dd1e10 100644 --- a/internal/appconfig/glossary_test.go +++ b/internal/appconfig/glossary_test.go @@ -1,6 +1,7 @@ package appconfig import ( + "context" "os" "path/filepath" "slices" @@ -48,7 +49,7 @@ party: `) write("shared/extra.yml", "lore:\n entries:\n - id: hero\n name: Ancient\n category: lore\n") write("glossary/nested/spells.yaml", "spells:\n entries:\n - id: bolt\n name: Bolt\n category: spell\n aliases: [Spark]\n plural: Bolts\n extra: {rank: 2}\n") - result, err := Load(ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "") + result, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "") if err != nil { t.Fatalf("%v: %+v", err, err.(*ck.LoadError).Diagnostics()) } @@ -62,7 +63,7 @@ party: if got := result.Config.Application.GlossaryCollections["lore"].Entries; len(got) != 1 || got[0].ID != "hero" { t.Fatalf("lore=%+v", got) } - discovered, err := Load(ck.Input{Source: ck.SearchConfig("audita", ck.SearchDirectory(dir))}, "") + discovered, _, err := Load(context.Background(), ck.Input{Source: ck.SearchConfig("audita", ck.SearchDirectory(dir))}, "") if err != nil || len(discovered.Config.Application.GlossaryCollections["party"].Entries) != 2 { t.Fatalf("discovered glossary: %+v %v", discovered, err) } @@ -97,7 +98,7 @@ func TestGlossaryValidationAndPeerConflicts(t *testing.T) { "glossary_collections:\n x:\n entries:\n - {id: 'id with spaces', name: N, category: C}\n", } { write(main, data) - if _, err := Load(ck.Input{Source: ck.File(main)}, ""); err != nil { + if _, _, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, ""); err != nil { t.Fatalf("valid %q: %v", data, err) } } @@ -108,7 +109,7 @@ func TestGlossaryValidationAndPeerConflicts(t *testing.T) { "glossary_collections:\n x:\n entries:\n - {id: x, name: N, category: C, plural: ''}\n", } { write(main, data) - if _, err := Load(ck.Input{Source: ck.File(main)}, ""); err == nil { + if _, _, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, ""); err == nil { t.Fatalf("accepted %q", data) } } @@ -118,7 +119,7 @@ func TestGlossaryValidationAndPeerConflicts(t *testing.T) { t.Fatal(err) } write(filepath.Join(dir, "glossary", "other.yml"), "x:\n entries:\n - {id: same, name: Two, category: C}\n") - if _, err := Load(ck.Input{Source: ck.File(main)}, ""); err == nil { + if _, _, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, ""); err == nil { t.Fatal("peer conflict accepted") } } @@ -129,7 +130,7 @@ func TestGlossaryUnderlaySkipsAbsentMain(t *testing.T) { t.Fatal(err) } t.Chdir(dir) - result, err := Load(ck.Input{Source: ck.NoSource()}, "") + result, _, err := Load(context.Background(), ck.Input{Source: ck.NoSource()}, "") if err != nil { t.Fatal(err) } diff --git a/internal/appconfig/secrets_test.go b/internal/appconfig/secrets_test.go new file mode 100644 index 0000000..c7213e7 --- /dev/null +++ b/internal/appconfig/secrets_test.go @@ -0,0 +1,75 @@ +package appconfig + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + + ck "go.maximumdirect.net/configkit" +) + +func TestLoadBootstrapsSecrets(t *testing.T) { + dir := t.TempDir() + secrets := filepath.Join(dir, "secrets") + if err := os.Mkdir(secrets, 0700); err != nil { + t.Fatal(err) + } + t.Setenv("AUDITA_TEST_BOOTSTRAP", "original") + if err := os.WriteFile(filepath.Join(secrets, "AUDITA_TEST_BOOTSTRAP"), []byte("synthetic"), 0600); err != nil { + t.Fatal(err) + } + main := filepath.Join(dir, "config.yml") + if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: secrets\n secrets_overwrite: true\n"), 0600); err != nil { + t.Fatal(err) + } + result, report, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, "") + if err != nil { + t.Fatal(err) + } + if result == nil || os.Getenv("AUDITA_TEST_BOOTSTRAP") != "synthetic" || len(report.Entries()) != 1 || report.Entries()[0].Status != ck.SecretFileLoaded { + t.Fatalf("result=%v entries=%+v", result, report.Entries()) + } +} + +func TestLoadRetainsBootstrapErrorAndCancellation(t *testing.T) { + dir := t.TempDir() + main := filepath.Join(dir, "config.yml") + if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: missing\n"), 0600); err != nil { + t.Fatal(err) + } + result, report, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, "") + var secretsErr *ck.SecretsError + if result != nil || report == nil || !errors.As(err, &secretsErr) { + t.Fatalf("result=%v report=%v error=%v", result, report, err) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + result, _, err = Load(ctx, ck.Input{Source: ck.File(main)}, "") + if result != nil || !errors.Is(err, context.Canceled) { + t.Fatalf("result=%v error=%v", result, err) + } +} + +func TestLoadReusesPreparedMainSnapshot(t *testing.T) { + dir := t.TempDir() + main := filepath.Join(dir, "config.yml") + if err := os.WriteFile(main, []byte("version: 3\ncontext:\n description: captured\n"), 0600); err != nil { + t.Fatal(err) + } + _, prepared, err := ck.LoadSecretsIntoEnvironmentFromConfig(ck.File(main), ck.SecretsFromConfigOptions{Filesystem: &ck.FilesystemContext{Root: dir}}) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(main, []byte("version: 3\ncontext:\n description: changed\n"), 0600); err != nil { + t.Fatal(err) + } + result, _, err := Load(context.Background(), ck.Input{Source: prepared, Filesystem: &ck.FilesystemContext{Root: dir}}, "") + if err != nil { + t.Fatal(err) + } + if result.Config.Application.Context.Description != "captured" { + t.Fatalf("loaded description = %q", result.Config.Application.Context.Description) + } +} diff --git a/internal/appconfig/sources_test.go b/internal/appconfig/sources_test.go index 5b226e6..872cbf5 100644 --- a/internal/appconfig/sources_test.go +++ b/internal/appconfig/sources_test.go @@ -1,6 +1,7 @@ package appconfig import ( + "context" ck "go.maximumdirect.net/configkit" "io/fs" "os" @@ -23,7 +24,7 @@ func TestMainContextImportsAndOverlay(t *testing.T) { t.Fatal(err) } } - result, err := Load(ck.Input{Source: ck.File(filepath.Join(dir, "main.yml"))}, "selected", ck.Override{Path: ck.Keys("context", "description"), Value: "override", Flag: "--description"}) + result, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "main.yml"))}, "selected", ck.Override{Path: ck.Keys("context", "description"), Value: "override", Flag: "--description"}) if err != nil { t.Fatal(err) } @@ -50,10 +51,10 @@ func TestMainContextImportsAndOverlay(t *testing.T) { if !found { t.Fatal("main source missing") } - if _, err := Load(ck.Input{Source: ck.File(filepath.Join(dir, "main.yml"))}, "missing"); err == nil { + if _, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "main.yml"))}, "missing"); err == nil { t.Fatal("missing overlay accepted") } - if _, err := Load(ck.Input{Source: ck.NoSource()}, "selected"); err == nil { + if _, _, err := Load(context.Background(), ck.Input{Source: ck.NoSource()}, "selected"); err == nil { t.Fatal("overlay without context accepted") } } @@ -62,7 +63,8 @@ func TestDiscoveryAndSelectedFailure(t *testing.T) { first, second := t.TempDir(), t.TempDir() search := ck.Searches(ck.SearchDirectory(first), ck.SearchDirectory(second)) load := func() (*ck.Result[Config], error) { - return Load(ck.Input{Source: ck.SearchConfig("audita", search)}, "") + result, _, err := Load(context.Background(), ck.Input{Source: ck.SearchConfig("audita", search)}, "") + return result, err } result, err := load() if err != nil { @@ -103,7 +105,7 @@ func TestOverlayUsesMainDirectoryWithinWiderRoot(t *testing.T) { if err := os.WriteFile(filepath.Join(dir, "overlays", "local.yml"), []byte("context:\n description: project\n"), 0644); err != nil { t.Fatal(err) } - result, err := Load(ck.Input{Source: ck.File(filepath.Join(dir, "config.yml")), Filesystem: &ck.FilesystemContext{Root: root}}, "local") + result, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml")), Filesystem: &ck.FilesystemContext{Root: root}}, "local") if err != nil { t.Fatal(err) } diff --git a/internal/cli/app_wiring.go b/internal/cli/app_wiring.go index ac43cb1..3c18d20 100644 --- a/internal/cli/app_wiring.go +++ b/internal/cli/app_wiring.go @@ -40,7 +40,8 @@ func loadApplication(ctx context.Context, selection ckconfig.Selection, _ struct } else { source = ck.SearchConfig("audita", ck.Searches(ck.WorkingDirectory(), ck.UserConfigDirectory(), ck.UnixSystemDirectories())) } - return appconfig.Load(ck.Input{Source: source}, selection.Overlay.Value, selection.Overrides...) + loaded, report, err := appconfig.Load(ctx, ck.Input{Source: source}, selection.Overlay.Value, selection.Overrides...) + return loaded, reportBootstrap(ctx, report, err) } func loadPromptEngine(ctx context.Context, selection ckconfig.Selection, input struct{}, state *invocationState) (*pk.Engine, error) { @@ -80,7 +81,8 @@ func buildApplication(extra ...commandkit.Declaration) (*commandkit.App, error) func buildApplicationWithClient(client *http.Client, extra ...commandkit.Declaration) (*commandkit.App, error) { appScope := ckconfig.FromConfigKit("app", "Audita application settings.", loadApplication) appScope.Features.Overrides = true - promptScope := ckprompt.ConfigScope(loadPromptEngine) + appScope = withBootstrapContext(appScope) + promptScope := withBootstrapContext(ckprompt.ConfigScope(loadPromptEngine)) configCommand := ckconfig.Command(ckconfig.Suite[struct{}, *invocationState]{NewState: func() *invocationState { return &invocationState{client: client} }, Scopes: []ckconfig.Scope[struct{}, *invocationState]{appScope, promptScope}}) definitions := ckprompt.WithNamespaces(ckprompt.FromEngine(capturePromptEngine), pk.Namespaces{}) definitions.NewState = func() *invocationState { return &invocationState{client: client} } @@ -91,7 +93,8 @@ func buildApplicationWithClient(client *http.Client, extra ...commandkit.Declara return applicationPromptRequest(seed.Request, seed.Namespaces), nil }) definitions = ckprompt.WithSmokeTesting(definitions, capturePromptEngine, nil) - declarations := []commandkit.Declaration{configCommand, commandkit.Completion("audita"), processCommand()} + definitions = withPromptBootstrapContext(definitions) + declarations := []commandkit.Declaration{configCommand, commandkit.Completion("audita"), commandkit.WithInvocationFeature(processCommand(), bootstrapFeature())} declarations = append(declarations, ckprompt.Declarations(definitions)...) declarations = append(declarations, extra...) return commandkit.New(commandkit.Identity{Name: "audita", Version: buildinfo.Version()}, declarations...) diff --git a/internal/cli/app_wiring_test.go b/internal/cli/app_wiring_test.go index def6a67..66e2a88 100644 --- a/internal/cli/app_wiring_test.go +++ b/internal/cli/app_wiring_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "io" "net/http" "os" @@ -14,6 +15,7 @@ import ( "go.maximumdirect.net/ckconfig" "go.maximumdirect.net/ckprompt" commandkit "go.maximumdirect.net/commandkit" + ck "go.maximumdirect.net/configkit" pk "go.maximumdirect.net/promptkit" ) @@ -230,3 +232,38 @@ func TestRequestDefaultsRespectNamespaceAndCallerVariables(t *testing.T) { t.Fatalf("generic request changed: %v", result.Vars) } } + +func TestConfigurationBootstrapReportsAndPreservesFailure(t *testing.T) { + dir := t.TempDir() + secrets := filepath.Join(dir, "secrets") + if err := os.Mkdir(secrets, 0700); err != nil { + t.Fatal(err) + } + t.Setenv("AUDITA_BOOTSTRAP_TEST", "prior") + if err := os.WriteFile(filepath.Join(secrets, "AUDITA_BOOTSTRAP_TEST"), []byte("synthetic-secret"), 0600); err != nil { + t.Fatal(err) + } + main := filepath.Join(dir, "config.yml") + if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: secrets\n secrets_overwrite: true\n"), 0600); err != nil { + t.Fatal(err) + } + app, err := buildApplication() + if err != nil { + t.Fatal(err) + } + var out, stderr bytes.Buffer + result := app.Execute(context.Background(), []string{"config", "show", "--scope", "app", "--config", main, "--verbose"}, commandkit.Streams{Out: &out, Err: &stderr}) + if result.Status != 0 || os.Getenv("AUDITA_BOOTSTRAP_TEST") != "synthetic-secret" || !strings.Contains(stderr.String(), "AUDITA_BOOTSTRAP_TEST") || strings.Contains(stderr.String(), "synthetic-secret") { + t.Fatalf("status=%d stdout=%q stderr=%q", result.Status, out.String(), stderr.String()) + } + if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: missing\n"), 0600); err != nil { + t.Fatal(err) + } + out.Reset() + stderr.Reset() + result = app.Execute(context.Background(), []string{"config", "show", "--scope", "app", "--config", main, "--quiet"}, commandkit.Streams{Out: &out, Err: &stderr}) + var native *ck.SecretsError + if result.Status != 1 || !errors.As(result.Cause, &native) || !strings.Contains(stderr.String(), "secrets.") || strings.Contains(stderr.String(), "synthetic-secret") { + t.Fatalf("status=%d cause=%v stdout=%q stderr=%q", result.Status, result.Cause, out.String(), stderr.String()) + } +} diff --git a/internal/cli/bootstrap.go b/internal/cli/bootstrap.go new file mode 100644 index 0000000..e69ce38 --- /dev/null +++ b/internal/cli/bootstrap.go @@ -0,0 +1,117 @@ +package cli + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + + "go.maximumdirect.net/ckconfig" + "go.maximumdirect.net/ckprompt" + commandkit "go.maximumdirect.net/commandkit" + ck "go.maximumdirect.net/configkit" +) + +type bootstrapReporterKey struct{} + +func bootstrapFeature() commandkit.InvocationFeature { + return commandkit.NewInvocationFeature(commandkit.InvocationFeatureSpec[struct{}]{ + Start: func(inv commandkit.Invocation, _ struct{}) (context.Context, func() commandkit.Report) { + return context.WithValue(inv.Context, bootstrapReporterKey{}, inv.Reporter()), nil + }, + }) +} + +type bootstrapError struct { + cause error + report *ck.SecretsReport +} + +func (e *bootstrapError) Error() string { + var output bytes.Buffer + fmt.Fprintln(&output, e.cause) + var native *ck.SecretsError + if errors.As(e.cause, &native) { + for _, diagnostic := range native.Diagnostics() { + fmt.Fprintf(&output, "%s: %s\n", diagnostic.Code, diagnostic.Message) + } + } + if e.report != nil { + _, _ = e.report.WriteTo(&output) + } + return output.String() +} + +func (e *bootstrapError) Unwrap() error { return e.cause } + +func reportBootstrap(ctx context.Context, report *ck.SecretsReport, err error) error { + var native *ck.SecretsError + if errors.As(err, &native) { + return &bootstrapError{cause: err, report: report} + } + if report != nil && len(report.Entries()) > 0 { + if reporter, ok := ctx.Value(bootstrapReporterKey{}).(*commandkit.Reporter); ok { + _ = reporter.Info("Secrets bootstrap", func(w io.Writer) error { + _, writeErr := report.WriteTo(w) + return writeErr + }) + } + } + return err +} + +// withBootstrapContext retains safe bootstrap evidence in configuration outcomes. +func withBootstrapContext[I, S any](scope ckconfig.Scope[I, S]) ckconfig.Scope[I, S] { + acquire := scope.Acquire + scope.Acquire = func(ctx context.Context, request ckconfig.Request, input I, state S) (commandkit.Acquired[ckconfig.View], error) { + result, err := acquire(ctx, request, input, state) + result.Explanation = bootstrapExplanation(result.Explanation, err) + return result, err + } + compare := scope.Compare + scope.Compare = func(ctx context.Context, request ckconfig.ComparisonRequest[I], state S) (commandkit.Acquired[[]ck.Difference], error) { + result, err := compare(ctx, request, state) + result.Explanation = bootstrapExplanation(result.Explanation, err) + return result, err + } + return scope +} + +func bootstrapExplanation(explanation commandkit.Explanation, err error) commandkit.Explanation { + var failure *bootstrapError + if errors.As(err, &failure) { + explanation.Details = append(explanation.Details, func(w io.Writer) error { + _, writeErr := io.WriteString(w, failure.Error()) + return writeErr + }) + } + return explanation +} + +func withBootstrapAcquisition[R, I, S, T any](load func(context.Context, R, I, S) (commandkit.Acquired[T], error)) func(context.Context, R, I, S) (commandkit.Acquired[T], error) { + if load == nil { + return nil + } + return func(ctx context.Context, request R, input I, state S) (commandkit.Acquired[T], error) { + result, err := load(ctx, request, input, state) + result.Explanation = bootstrapExplanation(result.Explanation, err) + return result, err + } +} + +func withPromptBootstrapContext[I, S any](suite ckprompt.Suite[I, S]) ckprompt.Suite[I, S] { + suite.InspectPrompt = withBootstrapAcquisition(suite.InspectPrompt) + suite.InspectProfile = withBootstrapAcquisition(suite.InspectProfile) + suite.InspectBackend = withBootstrapAcquisition(suite.InspectBackend) + suite.InspectRequirements = withBootstrapAcquisition(suite.InspectRequirements) + suite.ValidateRequest = withBootstrapAcquisition(suite.ValidateRequest) + suite.PrepareRequest = withBootstrapAcquisition(suite.PrepareRequest) + suite.SmokeTest = withBootstrapAcquisition(suite.SmokeTest) + suite.ListPrompts = withBootstrapAcquisition(suite.ListPrompts) + suite.ListProfiles = withBootstrapAcquisition(suite.ListProfiles) + suite.ListBackends = withBootstrapAcquisition(suite.ListBackends) + suite.ListNamespaces = withBootstrapAcquisition(suite.ListNamespaces) + suite.ListCollections = withBootstrapAcquisition(suite.ListCollections) + return suite +} diff --git a/internal/cli/bootstrap_test.go b/internal/cli/bootstrap_test.go new file mode 100644 index 0000000..408d717 --- /dev/null +++ b/internal/cli/bootstrap_test.go @@ -0,0 +1,133 @@ +package cli + +import ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig" + "go.maximumdirect.net/ckconfig" + "go.maximumdirect.net/ckprompt" + commandkit "go.maximumdirect.net/commandkit" + ck "go.maximumdirect.net/configkit" + pk "go.maximumdirect.net/promptkit" +) + +func TestBootstrapConfigurationOutcomes(t *testing.T) { + dir := t.TempDir() + if err := os.Mkdir(filepath.Join(dir, "secrets"), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("AUDITA_BOOTSTRAP_OUTCOME", "previous") + if err := os.WriteFile(filepath.Join(dir, "secrets", "AUDITA_BOOTSTRAP_OUTCOME"), []byte("private-value"), 0600); err != nil { + t.Fatal(err) + } + main := filepath.Join(dir, "config.yml") + writeMain := func(directory string) { + t.Helper() + if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: "+directory+"\n secrets_overwrite: true\n"), 0600); err != nil { + t.Fatal(err) + } + } + writeMain("secrets") + loads := 0 + load := func(ctx context.Context, selection ckconfig.Selection, _, _ struct{}) (*ck.Result[appconfig.Config], error) { + loads++ + result, report, err := appconfig.Load(ctx, ck.Input{Source: ck.File(selection.Config.Value)}, "") + return result, reportBootstrap(ctx, report, err) + } + scope := withBootstrapContext(ckconfig.FromConfigKit("app", "Application settings", load)) + command := ckconfig.Command(ckconfig.Suite[struct{}, struct{}]{Scopes: []ckconfig.Scope[struct{}, struct{}]{scope}}) + app, err := commandkit.New(commandkit.Identity{Name: "test"}, commandkit.WithInvocationFeature(command, bootstrapFeature())) + if err != nil { + t.Fatal(err) + } + var stdout, stderr bytes.Buffer + for _, args := range [][]string{{"--help"}, {"version"}, {"config", "show", "--help"}, {"config", "explain"}} { + outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &stdout, Err: &stderr}) + if outcome.Status != 0 || loads != 0 || os.Getenv("AUDITA_BOOTSTRAP_OUTCOME") != "previous" { + t.Fatalf("help %v: outcome=%+v loads=%d", args, outcome, loads) + } + stdout.Reset() + stderr.Reset() + } + result := app.Execute(context.Background(), []string{"config", "show", "--scope=app", "--config", main, "--verbose"}, commandkit.Streams{Out: &stdout, Err: &stderr}) + if result.Status != 0 || os.Getenv("AUDITA_BOOTSTRAP_OUTCOME") != "private-value" || !strings.Contains(stderr.String(), "AUDITA_BOOTSTRAP_OUTCOME") || strings.Contains(stderr.String(), "private-value") { + t.Fatalf("success: status=%d stderr=%q", result.Status, stderr.String()) + } + stdout.Reset() + stderr.Reset() + before := loads + result = app.Execute(context.Background(), []string{"config", "diff", "--scope=app", "--config", main, "--against-config", main}, commandkit.Streams{Out: &stdout, Err: &stderr}) + if result.Status != 0 || loads-before != 2 { + t.Fatalf("comparison: status=%d acquisitions=%d stderr=%q", result.Status, loads-before, stderr.String()) + } + failedWrite := errors.New("diagnostic destination failed") + stdout.Reset() + result = app.Execute(context.Background(), []string{"config", "show", "--scope=app", "--config", main, "--verbose"}, commandkit.Streams{Out: &stdout, Err: bootstrapFailWriter{err: failedWrite}}) + if result.Status != 1 || !errors.Is(result.Presentation.Diagnostics.WriteError, failedWrite) { + t.Fatalf("diagnostic write failure: %+v", result) + } + writeMain("missing") + stdout.Reset() + stderr.Reset() + result = app.Execute(context.Background(), []string{"config", "show", "--scope=app", "--config", main, "--quiet"}, commandkit.Streams{Out: &stdout, Err: &stderr}) + var native *ck.SecretsError + if result.Status != 1 || !errors.As(result.Cause, &native) || !strings.Contains(stderr.String(), "secrets.") || strings.Contains(stderr.String(), "private-value") { + t.Fatalf("failure: status=%d cause=%v stderr=%q", result.Status, result.Cause, stderr.String()) + } +} + +func TestBootstrapPreservesJoinedCancellation(t *testing.T) { + main := filepath.Join(t.TempDir(), "config.yml") + if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: missing\n"), 0600); err != nil { + t.Fatal(err) + } + _, report, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(main)}, "") + joined := errors.Join(err, context.Canceled) + wrapped := reportBootstrap(context.Background(), report, joined) + var native *ck.SecretsError + if !errors.As(wrapped, &native) || !errors.Is(wrapped, context.Canceled) { + t.Fatalf("cause = %v", wrapped) + } + explanation := bootstrapExplanation(commandkit.Explanation{}, wrapped) + var detail bytes.Buffer + if len(explanation.Details) != 1 { + t.Fatalf("details = %d", len(explanation.Details)) + } + if err := explanation.Details[0](&detail); err != nil || !strings.Contains(detail.String(), "secrets.") { + t.Fatalf("detail = %q error = %v", detail.String(), err) + } +} + +func TestPromptBootstrapFailureReportsTerminalDetails(t *testing.T) { + main := filepath.Join(t.TempDir(), "config.yml") + if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: missing\n"), 0600); err != nil { + t.Fatal(err) + } + load := func(ctx context.Context, selection ckconfig.Selection, _, _ struct{}) (*pk.Engine, error) { + _, report, err := appconfig.Load(ctx, ck.Input{Source: ck.File(selection.Config.Value)}, "") + return nil, reportBootstrap(ctx, report, err) + } + suite := withPromptBootstrapContext(ckprompt.FromEngine(load)) + commands := ckprompt.Declarations(suite) + commands = append(commands, commandkit.WithInvocationFeature(commandkit.Group("auxiliary", ""), bootstrapFeature())) + app, err := commandkit.New(commandkit.Identity{Name: "test"}, commands...) + if err != nil { + t.Fatal(err) + } + var stdout, stderr bytes.Buffer + outcome := app.Execute(context.Background(), []string{"promptkit", "list", "prompts", "--config", main, "--quiet"}, commandkit.Streams{Out: &stdout, Err: &stderr}) + var native *ck.SecretsError + if outcome.Status != 1 || !errors.As(outcome.Cause, &native) || !strings.Contains(stderr.String(), "secrets.") { + t.Fatalf("outcome=%+v stderr=%q", outcome, stderr.String()) + } +} + +type bootstrapFailWriter struct{ err error } + +func (w bootstrapFailWriter) Write([]byte) (int, error) { return 0, w.err } diff --git a/internal/cli/process.go b/internal/cli/process.go index 5a3c32d..25331da 100644 --- a/internal/cli/process.go +++ b/internal/cli/process.go @@ -37,6 +37,10 @@ func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcom } return commandkit.Failure(loadErr.Error(), explanation.Details...).WithCause(err) } + var secretsErr *bootstrapError + if errors.As(err, &secretsErr) { + return commandkit.Failure(secretsErr.Error()).WithCause(err) + } if inv.Context.Err() != nil || llm.IsAssetError(err) { return commandkit.Failure("Could not prepare processing.").WithCause(err) } @@ -65,7 +69,7 @@ func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcom warn(debug.WriteSourceTranscript(loaded.Source, loaded.RawTranscript)) } loaded.RawTranscript = nil - cfg := &loaded.Configuration.Config + cfg := &loaded.Configuration.Config.Application normalizer := normalization.NewNormalizer(normalization.NormalizationConfig{ MaxSegmentGap: cfg.Normalization.MaxSegmentGap, EllipsisGap: cfg.Normalization.EllipsisGap, MaxSegmentDuration: cfg.Normalization.MaxSegmentDuration, MaxSegmentTokens: cfg.Normalization.MaxSegmentTokens, diff --git a/internal/cli/process_inputs.go b/internal/cli/process_inputs.go index c476eea..621f8e6 100644 --- a/internal/cli/process_inputs.go +++ b/internal/cli/process_inputs.go @@ -11,7 +11,7 @@ import ( "path/filepath" "time" - "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" + "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig" "gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics" coreio "gitea.maximumdirect.net/eric/audita/v4/internal/core/io" "gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting" @@ -26,7 +26,7 @@ import ( ) type processInputs struct { - Configuration *ck.Result[config.Config] + Configuration *ck.Result[appconfig.Config] Runtime *llm.Runtime Source *schema.SourceTranscript RawTranscript []byte @@ -80,7 +80,7 @@ type preparedProcess struct { } func prepareProcess(ctx context.Context, input processInput, loaded *processInputs, stdout io.Writer) (*preparedProcess, error) { - cfg := &loaded.Configuration.Config + cfg := &loaded.Configuration.Config.Application reportDir := "" reportDirSet := false for _, override := range input.Overrides { diff --git a/internal/cli/process_pipeline.go b/internal/cli/process_pipeline.go index f56fb02..96d82f1 100644 --- a/internal/cli/process_pipeline.go +++ b/internal/cli/process_pipeline.go @@ -16,7 +16,7 @@ import ( ) func executePipeline(ctx context.Context, loaded *processInputs, prepared *preparedProcess, normalized *schema.Transcript, warn func(error), progress func(string)) (processResult, error) { - cfg := &loaded.Configuration.Config + cfg := &loaded.Configuration.Config.Application specs := prepared.Prepared.Specs debug := prepared.Prepared.Debug evidence := runner.EvidenceSelection{Reports: cfg.Reporting.Enabled, Debug: debug != nil}