Compare commits
73 Commits
integratio
...
v0.4.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 7416bf6fdc | |||
| d14fa366f5 | |||
| 1289868ed0 | |||
| 42af1da142 | |||
| 0b70f37267 | |||
| 1986c44f49 | |||
| 65b454b2ab | |||
| b38130548e | |||
| aeb70e5873 | |||
| 85ae55bf42 | |||
| da120c2dd4 | |||
| 0183022a28 | |||
| 644e6c365b | |||
| 8e5e64c6e9 | |||
| c3d5f551c3 | |||
| 6378ceb3c5 | |||
| 5ff0dd4ea2 | |||
| 6c35da3ab6 | |||
| 7159f52f4d | |||
| d748056652 | |||
| 924692b541 | |||
| 3a6c66f550 | |||
| 190bfbd77b | |||
| 7693482a8b | |||
| 105bb741cc | |||
| cb7e05284c | |||
| 022055dc26 | |||
| e908213318 | |||
| 5d90d59996 | |||
| 76c00e32d0 | |||
| 9b85c7cf60 | |||
| ee3cb21ebc | |||
| 93c16bd57e | |||
| ca454624cc | |||
| 90d9706f6d | |||
| f494088124 | |||
| 5010f9a102 | |||
| 3b6614605a | |||
| e7b00efc07 | |||
| 647a9d5372 | |||
| c52034f3fe | |||
| 408383db60 | |||
| e82101434f | |||
| ffe568b6f0 | |||
| 756954f056 | |||
| b6a8f1f2cc | |||
| d15926a878 | |||
| 7f2fdce8e7 | |||
| 491f0b49f4 | |||
| 61bcd80171 | |||
| 9076cb2c9c | |||
| f63af12097 | |||
| 111f963c67 | |||
| 66a33756c3 | |||
| ff9f840edd | |||
| f6f41ee6aa | |||
| df33e8aefc | |||
| 6830b96821 | |||
| 42af12cb0e | |||
| 0b4e47c420 | |||
| ad16bfc521 | |||
| 540e2359d6 | |||
| e28ba63b59 | |||
| 7f327758d8 | |||
| 1e3879e880 | |||
| 33cc36ff3b | |||
| 983c22be77 | |||
| f933f056d7 | |||
| cf50b135f2 | |||
| ee0debe4fb | |||
| 4f851371da | |||
| 69cc6429ff | |||
| eeae10fa05 |
12
README.md
12
README.md
@@ -9,7 +9,7 @@ The core captures reusable command declarations, validates installation batches
|
||||
before changing an application's registry, converts typed inputs before
|
||||
constructing them, and returns outcomes without exiting the process. Its
|
||||
[consumer guide](docs/consumers/guide.md) covers declaration, invocation
|
||||
reporting, and migration. Each handler receives one invocation reporter for
|
||||
and reporting. Each handler receives one invocation reporter for
|
||||
substantive output, categorized messages, and terminal explanations; `Execute`
|
||||
returns delivery observations with the outcome. The [CLI reference](docs/cli.md)
|
||||
defines the shared visibility policy.
|
||||
@@ -23,10 +23,12 @@ defines the shared visibility policy.
|
||||
| `go.maximumdirect.net/ckprompt` | `ckprompt` | PromptKit engine configuration/comparison, five catalogs, named inspection, requirements discovery, concrete request validation, and native smoke tests. |
|
||||
|
||||
Importing an integration does not install commands. The published ckconfig and
|
||||
ckprompt v0.2.0 modules use core v0.3.0. The local
|
||||
ckconfig v0.3.0 candidate uses ConfigKit v1.1.0 and does not compose with
|
||||
ckprompt v0.2.0; the published v0.2.0 pair remains matched. See the
|
||||
[consumer guide](docs/consumers/guide.md#module-selection) for migration details.
|
||||
ckprompt v0.2.0 modules use core v0.3.0. The published
|
||||
ckconfig v0.3.0 uses ConfigKit v1.1.0 and does not compose with
|
||||
ckprompt v0.2.0; the published v0.2.0 pair remains matched. Current integration
|
||||
sources use new core and ckconfig APIs and are developed in an aligned workspace
|
||||
until their release dependencies are available. See the
|
||||
[consumer guide](docs/consumers/guide.md#module-selection) for dependency details.
|
||||
|
||||
## Examples
|
||||
|
||||
|
||||
76
binding.go
76
binding.go
@@ -3,6 +3,7 @@ package commandkit
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
|
||||
commandmeta "go.maximumdirect.net/commandkit/internal/commandmeta"
|
||||
@@ -38,6 +39,48 @@ func ValueFlag[I, V any](meta FlagMeta, defaultValue *V, parse func(string) (V,
|
||||
return Flag[I]{binding: binding}
|
||||
}
|
||||
|
||||
// OccurrenceFlag declares a repeatable flag whose setter runs once for each
|
||||
// supplied occurrence. Occurrence setters run in command-line order across
|
||||
// participating bindings; an omitted flag does not call its setter.
|
||||
func OccurrenceFlag[I, V any](meta FlagMeta, parse func(string) (V, error), set func(*I, Supplied[V])) Flag[I] {
|
||||
binding := flagBinding[I]{identity: newBindingIdentity(), meta: meta, repeated: true}
|
||||
if parse == nil || set == nil {
|
||||
return Flag[I]{binding: binding}
|
||||
}
|
||||
binding.valid = true
|
||||
binding.prepare = func(values []string) (preparedValue[I], error) {
|
||||
result := preparedValue[I]{identity: binding.identity, supplied: len(values) > 0}
|
||||
for index, raw := range values {
|
||||
value, err := parse(raw)
|
||||
if err != nil {
|
||||
return preparedValue[I]{}, &flagOccurrenceError{index: index, cause: err}
|
||||
}
|
||||
ordinal := index
|
||||
result.ordered = append(result.ordered, preparedOccurrence[I]{ordinal: &ordinal, apply: func(input *I) { set(input, Supplied[V]{Value: value, Set: true}) }})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
return Flag[I]{binding: binding}
|
||||
}
|
||||
|
||||
// RenameFlag returns an independent binding with a new long name and no short
|
||||
// spelling. Parsing, defaults, completion, requiredness, and setters are retained.
|
||||
func RenameFlag[I any](flag Flag[I], name string) Flag[I] {
|
||||
binding := flag.binding
|
||||
binding.meta.Name = name
|
||||
binding.meta.Short = ""
|
||||
binding.identity = newBindingIdentity()
|
||||
if prepare := binding.prepare; prepare != nil {
|
||||
identity := binding.identity
|
||||
binding.prepare = func(values []string) (preparedValue[I], error) {
|
||||
value, err := prepare(values)
|
||||
value.identity = identity
|
||||
return value, err
|
||||
}
|
||||
}
|
||||
return Flag[I]{binding: binding}
|
||||
}
|
||||
|
||||
// BoolFlag declares a boolean flag. A bare flag is supplied by the parser as
|
||||
// "true"; explicit values are converted with strconv.ParseBool. Set distinguishes
|
||||
// an omitted flag from an explicit false value.
|
||||
@@ -189,7 +232,9 @@ func (p preparedInput[I]) build() I {
|
||||
input = p.newInput()
|
||||
}
|
||||
for _, value := range p.values {
|
||||
value.apply(&input)
|
||||
if value.apply != nil {
|
||||
value.apply(&input)
|
||||
}
|
||||
}
|
||||
return input
|
||||
}
|
||||
@@ -202,6 +247,10 @@ func prepareInput[I any](spec CommandSpec[I], flagValues [][]string, operands []
|
||||
}
|
||||
|
||||
func prepareInputWithSpellings[I any](spec CommandSpec[I], flagValues, flagSpellings [][]string, operands []string, enforceRequired bool) (preparedInput[I], error) {
|
||||
return prepareInputWithOccurrences(spec, flagValues, flagSpellings, nil, operands, enforceRequired)
|
||||
}
|
||||
|
||||
func prepareInputWithOccurrences[I any](spec CommandSpec[I], flagValues, flagSpellings [][]string, occurrences []commandmeta.FlagOccurrence, operands []string, enforceRequired bool) (preparedInput[I], error) {
|
||||
if len(flagValues) != len(spec.Flags) {
|
||||
return preparedInput[I]{}, fmt.Errorf("received %d flag value sets for %d bindings", len(flagValues), len(spec.Flags))
|
||||
}
|
||||
@@ -212,6 +261,12 @@ func prepareInputWithSpellings[I any](spec CommandSpec[I], flagValues, flagSpell
|
||||
return preparedInput[I]{}, fmt.Errorf("received %d flag spelling sets for %d bindings", len(flagSpellings), len(spec.Flags))
|
||||
}
|
||||
preparedFlags := make([]preparedValue[I], len(spec.Flags))
|
||||
ordinals := make(map[string][]int)
|
||||
for index, occurrence := range occurrences {
|
||||
ordinals[occurrence.Name] = append(ordinals[occurrence.Name], index)
|
||||
}
|
||||
var ordered []preparedOccurrence[I]
|
||||
fallbackOrdinal := 0
|
||||
missingRequired := ""
|
||||
for i, flag := range spec.Flags {
|
||||
binding := flag.binding
|
||||
@@ -231,6 +286,21 @@ func prepareInputWithSpellings[I any](spec CommandSpec[I], flagValues, flagSpell
|
||||
return preparedInput[I]{}, fmt.Errorf("flag --%s: %w", binding.meta.Name, err)
|
||||
}
|
||||
preparedFlags[i] = value
|
||||
for index, occurrence := range value.ordered {
|
||||
if occurrences != nil {
|
||||
positions := ordinals[binding.meta.Name]
|
||||
if index >= len(positions) {
|
||||
return preparedInput[I]{}, fmt.Errorf("missing occurrence position for flag --%s", binding.meta.Name)
|
||||
}
|
||||
*occurrence.ordinal = positions[index]
|
||||
} else {
|
||||
*occurrence.ordinal = fallbackOrdinal
|
||||
fallbackOrdinal++
|
||||
}
|
||||
if occurrence.apply != nil {
|
||||
ordered = append(ordered, occurrence)
|
||||
}
|
||||
}
|
||||
if enforceRequired && binding.meta.Required && !binding.deferredRequired && !value.supplied && missingRequired == "" {
|
||||
missingRequired = binding.meta.Name
|
||||
}
|
||||
@@ -243,6 +313,10 @@ func prepareInputWithSpellings[I any](spec CommandSpec[I], flagValues, flagSpell
|
||||
return preparedInput[I]{}, err
|
||||
}
|
||||
preparedValues := append([]preparedValue[I](nil), preparedFlags...)
|
||||
sort.SliceStable(ordered, func(i, j int) bool { return *ordered[i].ordinal < *ordered[j].ordinal })
|
||||
for _, occurrence := range ordered {
|
||||
preparedValues = append(preparedValues, preparedValue[I]{apply: occurrence.apply})
|
||||
}
|
||||
for i, argument := range spec.Arguments {
|
||||
binding := argument.binding
|
||||
value, err := binding.prepare(argumentValues[i])
|
||||
|
||||
50
builtins.go
50
builtins.go
@@ -4,10 +4,10 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"runtime/debug"
|
||||
"text/template"
|
||||
|
||||
internalcobra "go.maximumdirect.net/commandkit/internal/cobra"
|
||||
commandmeta "go.maximumdirect.net/commandkit/internal/commandmeta"
|
||||
yaml "go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
const commandKitModulePath = "go.maximumdirect.net/commandkit"
|
||||
@@ -17,16 +17,17 @@ type helpInput struct {
|
||||
}
|
||||
|
||||
type versionInput struct {
|
||||
Scope string
|
||||
Format string
|
||||
Scope string
|
||||
}
|
||||
|
||||
type versionDocument struct {
|
||||
Name string `yaml:"name"`
|
||||
Version string `yaml:"version"`
|
||||
Revision string `yaml:"revision"`
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
Revision string `json:"revision"`
|
||||
}
|
||||
|
||||
var versionTextTemplate = template.Must(ParseTextTemplate("version", "{{.Name}} {{.Version}}{{if .Revision}} ({{.Revision}}){{end}}\n", nil))
|
||||
|
||||
func (a *App) builtinCommands() []Declaration {
|
||||
help := captureCommand(CommandSpec[helpInput]{
|
||||
Name: "help",
|
||||
@@ -39,14 +40,12 @@ func (a *App) builtinCommands() []Declaration {
|
||||
return current.renderHelpTargets(input.Targets.Value)
|
||||
})
|
||||
scopeDefault := "app"
|
||||
formatDefault := "text"
|
||||
version := NewCommand(CommandSpec[versionInput]{
|
||||
Name: "version",
|
||||
Summary: "Show application or CommandKit version.",
|
||||
Description: "Report identity and build metadata without loading application configuration.",
|
||||
Flags: []Flag[versionInput]{
|
||||
ValueFlag(FlagMeta{Name: "scope", Usage: "version subject", Completion: CompleteChoices(CompletionChoice{Value: "app"}, CompletionChoice{Value: "commandkit"})}, &scopeDefault, parseVersionScope, func(input *versionInput, value Supplied[string]) { input.Scope = value.Value }),
|
||||
ValueFlag(FlagMeta{Name: "format", Usage: "output format", Completion: CompleteChoices(CompletionChoice{Value: "text"}, CompletionChoice{Value: "yaml"})}, &formatDefault, parseVersionFormat, func(input *versionInput, value Supplied[string]) { input.Format = value.Value }),
|
||||
},
|
||||
Run: func(invocation Invocation, input versionInput) Outcome {
|
||||
identity := a.identity
|
||||
@@ -56,7 +55,7 @@ func (a *App) builtinCommands() []Declaration {
|
||||
if identity.Version == "" {
|
||||
identity.Version = "dev"
|
||||
}
|
||||
return renderVersionOutcome(identity, input.Format, invocation.Reporter())
|
||||
return renderVersionOutcome(identity, invocation.Reporter())
|
||||
},
|
||||
})
|
||||
return []Declaration{help, version}
|
||||
@@ -69,13 +68,6 @@ func parseVersionScope(value string) (string, error) {
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func parseVersionFormat(value string) (string, error) {
|
||||
if value != "text" && value != "yaml" {
|
||||
return "", fmt.Errorf("format must be text or yaml, got %q", value)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (a *App) renderHelpViewOutcomeWithSession(view commandmeta.HelpView, reporter *Reporter, session *internalcobra.Session) Outcome {
|
||||
content, failure := session.RenderHelpView(view)
|
||||
if failure != nil {
|
||||
@@ -91,36 +83,14 @@ func (a *App) renderHelpViewOutcomeWithSession(view commandmeta.HelpView, report
|
||||
return Success()
|
||||
}
|
||||
|
||||
func renderVersionOutcome(identity Identity, format string, reporter *Reporter) Outcome {
|
||||
func renderVersionOutcome(identity Identity, reporter *Reporter) Outcome {
|
||||
if identity.Version == "" {
|
||||
identity.Version = "dev"
|
||||
}
|
||||
switch format {
|
||||
case "text":
|
||||
line := identity.Name + " " + identity.Version
|
||||
if identity.Revision != "" {
|
||||
line += " (" + identity.Revision + ")"
|
||||
}
|
||||
_ = reporter.RenderOutput(func(w io.Writer) error {
|
||||
_, err := io.WriteString(w, line+"\n")
|
||||
return err
|
||||
})
|
||||
case "yaml":
|
||||
_ = reporter.RenderOutput(func(w io.Writer) error {
|
||||
return encodeYAML(w, versionDocument{Name: identity.Name, Version: identity.Version, Revision: identity.Revision})
|
||||
})
|
||||
default:
|
||||
return Usage(fmt.Sprintf("unsupported version format %q", format))
|
||||
}
|
||||
_ = reporter.Report(Report{Value: versionDocument{Name: identity.Name, Version: identity.Version, Revision: identity.Revision}, TextTemplate: versionTextTemplate})
|
||||
return Success()
|
||||
}
|
||||
|
||||
func encodeYAML(writer io.Writer, document any) error {
|
||||
encoder := yaml.NewEncoder(writer)
|
||||
encoder.SetIndent(2)
|
||||
return encoder.Encode(document)
|
||||
}
|
||||
|
||||
func readBuildInfo() *debug.BuildInfo {
|
||||
info, ok := debug.ReadBuildInfo()
|
||||
if !ok {
|
||||
|
||||
76
cli_json.go
Normal file
76
cli_json.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package commandkit
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ParseCLIJSON parses exactly one JSON value for use in CLI inputs. Integer
|
||||
// tokens become int64, or uint64 for larger nonnegative integers; decimal and
|
||||
// exponent tokens become float64. Nested values follow the same rules. Syntax
|
||||
// errors and numbers outside the selected Go types' ranges are returned.
|
||||
func ParseCLIJSON(input string) (any, error) {
|
||||
decoder := json.NewDecoder(strings.NewReader(input))
|
||||
decoder.UseNumber()
|
||||
var value any
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); err != io.EOF {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected additional JSON value")
|
||||
}
|
||||
return convertCLIJSON(value)
|
||||
}
|
||||
|
||||
// CLI inputs use ordinary Go numbers for upstream consumers. Classification
|
||||
// follows the token's syntax, so 1.0 and 1e0 remain float64. Unlike report
|
||||
// serialization, this boundary deliberately accepts float64 approximation.
|
||||
func convertCLIJSON(value any) (any, error) {
|
||||
switch v := value.(type) {
|
||||
case json.Number:
|
||||
token := string(v)
|
||||
if strings.ContainsAny(token, ".eE") {
|
||||
result, err := strconv.ParseFloat(token, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("JSON number %q: %w", token, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
result, err := strconv.ParseInt(token, 10, 64)
|
||||
if err == nil {
|
||||
return result, nil
|
||||
}
|
||||
if !strings.HasPrefix(token, "-") {
|
||||
unsigned, unsignedErr := strconv.ParseUint(token, 10, 64)
|
||||
if unsignedErr == nil {
|
||||
return unsigned, nil
|
||||
}
|
||||
return nil, fmt.Errorf("JSON integer %q: %w", token, unsignedErr)
|
||||
}
|
||||
return nil, fmt.Errorf("JSON integer %q: %w", token, err)
|
||||
case []any:
|
||||
for index, item := range v {
|
||||
converted, err := convertCLIJSON(item)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v[index] = converted
|
||||
}
|
||||
case map[string]any:
|
||||
for key, item := range v {
|
||||
converted, err := convertCLIJSON(item)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v[key] = converted
|
||||
}
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
44
cli_json_test.go
Normal file
44
cli_json_test.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package commandkit
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseCLIJSONValues(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
input string
|
||||
want any
|
||||
}{
|
||||
{`{"a":[null,true,"x",-9223372036854775808,9223372036854775807,9223372036854775808,18446744073709551615],"b":{"n":1.0,"exp":1e3}}`, map[string]any{
|
||||
"a": []any{nil, true, "x", int64(math.MinInt64), int64(math.MaxInt64), uint64(1 << 63), uint64(math.MaxUint64)},
|
||||
"b": map[string]any{"n": float64(1), "exp": float64(1000)},
|
||||
}},
|
||||
{`0`, int64(0)}, {`-0`, int64(0)}, {`42.0`, float64(42)}, {`1e0`, float64(1)},
|
||||
{`0.1`, float64(0.1)}, {`"1"`, "1"}, {`false`, false}, {`null`, nil},
|
||||
} {
|
||||
t.Run(tc.input, func(t *testing.T) {
|
||||
got, err := ParseCLIJSON(tc.input)
|
||||
if err != nil || !reflect.DeepEqual(got, tc.want) {
|
||||
t.Fatalf("got %#v, %v; want %#v", got, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseCLIJSONRejectsInvalidInput(t *testing.T) {
|
||||
for _, input := range []string{"", "[", "01", `1 2`, `true false`, `{} garbage`, `-9223372036854775809`, `18446744073709551616`, `1e400`, `[-1e400]`} {
|
||||
t.Run(input, func(t *testing.T) {
|
||||
if _, err := ParseCLIJSON(input); err == nil {
|
||||
t.Fatalf("accepted %q", input)
|
||||
}
|
||||
})
|
||||
}
|
||||
_, err := ParseCLIJSON(`18446744073709551616`)
|
||||
if !errors.Is(err, strconv.ErrRange) {
|
||||
t.Fatalf("range error = %v", err)
|
||||
}
|
||||
}
|
||||
13
command.go
13
command.go
@@ -127,6 +127,13 @@ type preparedValue[I any] struct {
|
||||
identity *bindingIdentity
|
||||
supplied bool
|
||||
apply func(*I)
|
||||
ordered []preparedOccurrence[I]
|
||||
}
|
||||
|
||||
type preparedOccurrence[I any] struct {
|
||||
// Captured bindings share this position with the outer prepared occurrence.
|
||||
ordinal *int
|
||||
apply func(*I)
|
||||
}
|
||||
|
||||
type flagBinding[I any] struct {
|
||||
@@ -186,7 +193,7 @@ type commandPayload interface {
|
||||
hasRun() bool
|
||||
bridgeFlags() []commandmeta.Flag
|
||||
bridgeArguments() []commandmeta.Argument
|
||||
prepare([][]string, [][]string, []string, bool) (func(*execution) Outcome, error)
|
||||
prepare([][]string, [][]string, []commandmeta.FlagOccurrence, []string, bool) (func(*execution) Outcome, error)
|
||||
}
|
||||
|
||||
type typedCommand[I any] struct {
|
||||
@@ -235,8 +242,8 @@ func (c typedCommand[I]) bridgeArguments() []commandmeta.Argument {
|
||||
return arguments
|
||||
}
|
||||
|
||||
func (c typedCommand[I]) prepare(flagValues, flagSpellings [][]string, operands []string, enforceRequired bool) (func(*execution) Outcome, error) {
|
||||
prepared, err := prepareInputWithSpellings(c.spec, flagValues, flagSpellings, operands, enforceRequired)
|
||||
func (c typedCommand[I]) prepare(flagValues, flagSpellings [][]string, occurrences []commandmeta.FlagOccurrence, operands []string, enforceRequired bool) (func(*execution) Outcome, error) {
|
||||
prepared, err := prepareInputWithOccurrences(c.spec, flagValues, flagSpellings, occurrences, operands, enforceRequired)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@ func TestCompletionQueryDispatch(t *testing.T) {
|
||||
{"alias value", []string{"__complete", "shortcut", "--colour=bl"}, "blue\tcool color\n", false},
|
||||
{"quiet is data", []string{"__complete", "run", "--quiet", "--color=bl"}, "blue\tcool color\n", false},
|
||||
{"debug is data", []string{"__complete", "run", "--debug", "--color=bl"}, "blue\tcool color\n", false},
|
||||
{"format value", []string{"__complete", "run", "--format", "j"}, "json\n", false},
|
||||
{"short attached choice", []string{"__complete", "run", "-cfoo=ba"}, "foo=bar\n", false},
|
||||
{"unknown route", []string{"__complete", "missing", ""}, emptyReply, true},
|
||||
} {
|
||||
|
||||
@@ -54,7 +54,7 @@ func TestCompletionHintsFollowCapturedBindings(t *testing.T) {
|
||||
t.Fatalf("no completion: %#v", got)
|
||||
}
|
||||
for _, flag := range append(commandmeta.ReportingFlags(), commandmeta.HelpFlag()) {
|
||||
if !reflect.DeepEqual(flag.Completion.Choices, []commandmeta.CompletionChoice{{Value: "true"}, {Value: "false"}}) {
|
||||
if flag.Boolean && !reflect.DeepEqual(flag.Completion.Choices, []commandmeta.CompletionChoice{{Value: "true"}, {Value: "false"}}) {
|
||||
t.Fatalf("reporting flag choices: %#v", flag)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,15 +18,15 @@ func TestPublicInstallationAcceptsMixedDeclarations(t *testing.T) {
|
||||
Name: "show",
|
||||
Summary: "Show a value.",
|
||||
Flags: []commandkit.Flag[struct{}]{
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "format"}, (*string)(nil), func(value string) (string, error) { return value, nil }, func(*struct{}, commandkit.Supplied[string]) {}),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "style"}, (*string)(nil), func(value string) (string, error) { return value, nil }, func(*struct{}, commandkit.Supplied[string]) {}),
|
||||
},
|
||||
Run: func(commandkit.Invocation, struct{}) commandkit.Outcome { return commandkit.Success() },
|
||||
})
|
||||
declarations := []commandkit.Declaration{
|
||||
command,
|
||||
commandkit.Alias("inspect", "show"),
|
||||
commandkit.FlagAlias("--fmt", "--format"),
|
||||
commandkit.FlagAliasFor("show", "-f", "--format"),
|
||||
commandkit.FlagAlias("--fmt", "--style"),
|
||||
commandkit.FlagAliasFor("show", "-f", "--style"),
|
||||
}
|
||||
app, err := commandkit.New(commandkit.Identity{Name: "Example"}, declarations...)
|
||||
if err != nil {
|
||||
@@ -84,7 +84,7 @@ func TestPublicAliasesPreserveCommandsAcrossDeclarationOrders(t *testing.T) {
|
||||
func(value string) (string, error) { optionalParses++; return value, nil },
|
||||
func(target *showInput, value commandkit.Supplied[string]) { target.profile = value },
|
||||
)},
|
||||
Flags: []commandkit.Flag[showInput]{commandkit.ValueFlag(commandkit.FlagMeta{Name: "format"}, (*string)(nil),
|
||||
Flags: []commandkit.Flag[showInput]{commandkit.ValueFlag(commandkit.FlagMeta{Name: "style"}, (*string)(nil),
|
||||
func(value string) (string, error) { return value, nil },
|
||||
func(target *showInput, value commandkit.Supplied[string]) { target.format = value },
|
||||
)},
|
||||
@@ -99,7 +99,7 @@ func TestPublicAliasesPreserveCommandsAcrossDeclarationOrders(t *testing.T) {
|
||||
commandkit.Alias("r full", "inspect"),
|
||||
commandkit.Alias("inspect-shortcut", "inspect"),
|
||||
commandkit.Alias("i", "inspect-shortcut"),
|
||||
commandkit.FlagAlias("--fmt", "--format"),
|
||||
commandkit.FlagAlias("--fmt", "--style"),
|
||||
}
|
||||
declarations := append([]commandkit.Declaration(nil), commands...)
|
||||
if test.rulesFirst {
|
||||
@@ -154,7 +154,7 @@ func TestPublicRootGroupRegistrationAndFailedBatchRecovery(t *testing.T) {
|
||||
var formats []string
|
||||
show := commandkit.NewCommand(commandkit.CommandSpec[showInput]{
|
||||
Name: "show",
|
||||
Flags: []commandkit.Flag[showInput]{commandkit.ValueFlag(commandkit.FlagMeta{Name: "format"}, (*string)(nil),
|
||||
Flags: []commandkit.Flag[showInput]{commandkit.ValueFlag(commandkit.FlagMeta{Name: "style"}, (*string)(nil),
|
||||
func(value string) (string, error) { formatParses++; return value, nil },
|
||||
func(target *showInput, value commandkit.Supplied[string]) { target.format = value },
|
||||
)},
|
||||
@@ -181,7 +181,7 @@ func TestPublicRootGroupRegistrationAndFailedBatchRecovery(t *testing.T) {
|
||||
if err := app.Register(family,
|
||||
commandkit.Alias("cfg-show", "config show"),
|
||||
commandkit.Alias("cs", "cfg-show"),
|
||||
commandkit.FlagAlias("--fmt", "--format"),
|
||||
commandkit.FlagAlias("--fmt", "--style"),
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1,209 +1,78 @@
|
||||
# ADR 0001: Own dispatch through an explicit registry and typed inputs
|
||||
# ADR 0001: Own dispatch through captured declarations and typed inputs
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
[ADR 0011](0011-captured-declarations-and-installation.md) refines
|
||||
declaration construction, installation, optional-family namespace reservation,
|
||||
and integration input/state lifetimes.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-06
|
||||
2026-11-07; consolidates decisions made on 2026-10-06 and 2026-10-10.
|
||||
|
||||
## Context
|
||||
|
||||
Several downstream consumers of the ConfigKit and PromptKit libraries include
|
||||
duplicated or near-duplicated code relating to configuration inspection,
|
||||
routing, parsing, help, and error handling. However, their command vocabulary
|
||||
and syntax have diverged. CommandKit aims to provide a single, unified CLI
|
||||
implementation that will reduce duplication, provide consistent vocabulary and
|
||||
grammar, and reduce the amount of code each individual application must own.
|
||||
|
||||
Applications have genuine domain commands, such as Narratio's `session restore`,
|
||||
that remain outside the standard suite. Merely forwarding standard families from
|
||||
separate application dispatchers would leave custom-command mechanics and root
|
||||
help dependent on each application's implementation.
|
||||
|
||||
Input handling also needs a common boundary. Raw argv handlers or string-based
|
||||
flag retrieval leave repeated parsing and input assembly with applications.
|
||||
Presence matters for configuration overrides: omitted values differ from
|
||||
explicitly supplied empty strings, false, and zero.
|
||||
Applications repeat routing, flag parsing, help, and inspection commands while
|
||||
also needing their own domain commands. Sharing only isolated command handlers
|
||||
would leave much of that infrastructure and its inconsistent behavior with each
|
||||
application. Optional integrations also need to assemble commands through the
|
||||
same public mechanisms as applications.
|
||||
|
||||
## Decision
|
||||
|
||||
### Ownership and namespace structure
|
||||
CommandKit owns dispatch, shared parsing, presence tracking, help, syntax
|
||||
failures, and standard command mechanics. Applications own their domain commands,
|
||||
validation, effects, runtime construction, and executable lifecycle. CommandKit
|
||||
accepts caller context and streams and returns outcomes rather than terminating
|
||||
the process.
|
||||
|
||||
CommandKit owns the dispatcher, shared parsing and presence tracking, help,
|
||||
syntax diagnostics, and standard-family handlers and outcomes. Applications own
|
||||
custom command names, domain meaning, validation, effects, artifacts, and
|
||||
operational outcomes.
|
||||
Use an explicitly constructed, per-instance registry. Applications and
|
||||
integrations supply captured declarations containing routing, parsing, help
|
||||
metadata, and callback references. One declaration supplies those views of the
|
||||
command. Captured metadata is insulated from later edits to its source;
|
||||
application objects referenced by callbacks remain caller-owned.
|
||||
|
||||
Use namespace-first syntax for the standard suite, which provides a clear
|
||||
family ownership boundary. The initial standard command families are `config`
|
||||
for ConfigKit inspection and validation, and `promptkit` for PromptKit inspection
|
||||
and utilities. CommandKit integrates these libraries through their supported public
|
||||
semantics.
|
||||
Declarations share one installation boundary. Construction issues are retained
|
||||
for installation, and each installation batch is validated before registry
|
||||
mutation. Collisions are errors rather than order-dependent replacement.
|
||||
Optional standard families claim their namespaces when installed, not when
|
||||
imported. Their canonical operations remain integration-owned; application
|
||||
commands live outside installed standard families.
|
||||
|
||||
CommandKit accepts custom commands outside its reserved standard families and
|
||||
reports registration errors for attempts to replace standard handlers or add
|
||||
private operations beneath them. Its input extension mechanism accepts context
|
||||
selectors and typed overrides for standard operations.
|
||||
Handlers receive typed inputs through explicit flag and operand bindings.
|
||||
Presence is separate from value so omission differs from supplied empty, false,
|
||||
or zero values. Domain parsers and validation remain application-owned. Core
|
||||
provides typed composition for integrations without exposing parser state or
|
||||
requiring a second argument parser.
|
||||
|
||||
CommandKit accepts caller-supplied context, streams, handlers, and inspection
|
||||
providers and returns invocation outcomes. It leaves process termination to the
|
||||
caller. Executable startup, signals, runtime construction, schemas, acquisition,
|
||||
and domain resolution remain application choices.
|
||||
Parsed state is independent between invocations. Integration inputs for selected
|
||||
scopes or comparison sides are distinct from invocation-wide acquisition state.
|
||||
Applications own the objects and caches returned by their factories. CommandKit
|
||||
coordinates its own preparation and calls without promising arbitrary deep copies
|
||||
or concurrent dispatch.
|
||||
|
||||
### Explicit registry and capability installation
|
||||
|
||||
Each explicitly constructed CommandKit instance owns a registry. Its API accepts
|
||||
individual commands and composable groups. Registration uses explicit instance
|
||||
state with caller-controlled construction and composition.
|
||||
|
||||
Definitions provide paths, descriptions, flags and defaults, repetition and
|
||||
presence metadata, operand requirements, and execution handlers. One definition
|
||||
supplies routing, parsing, and help. Duplicate paths and attempts to replace
|
||||
reserved commands return registration errors; order does not select a winner.
|
||||
|
||||
Help and version are installed automatically using supplied application identity
|
||||
and build metadata. CommandKit assembles standard families from declared provider
|
||||
capabilities, installing their supported handlers and metadata together. Each
|
||||
family defines its own resource model, supported verbs, and per-operation data
|
||||
contracts. Configuration scopes declare their available inspection operations.
|
||||
|
||||
The API allows supported capabilities to be integrated independently. Adding
|
||||
comparison, catalogs, or other inspection features extends the installed surface
|
||||
according to the supplied providers. Shared verbs have consistent purposes across
|
||||
families, while the available subsets reflect their resources and capabilities.
|
||||
Help and discovery expose those subsets. Registration validates the wiring of
|
||||
declared capabilities and reports unsupported selections before acquisition.
|
||||
|
||||
CommandKit registration validates declarations with acquisition callbacks left
|
||||
uninvoked. Its construction, help, and version paths use metadata. The selected
|
||||
handler requests dependencies when its operation needs them. Invalid configuration
|
||||
returned by an acquisition callback is an invocation-time failure. Caller code
|
||||
executed before registration and effects inside callbacks remain caller-owned.
|
||||
|
||||
CommandKit installs handlers for supplied capabilities and describes actual
|
||||
availability. Each enabled operation retains its standard meaning and output
|
||||
contract. The exact operation inventory and remaining command contracts are
|
||||
separate design decisions.
|
||||
|
||||
### Typed inputs with explicit bindings
|
||||
|
||||
The public binding contract accepts application-defined input structs for custom
|
||||
commands and uses CommandKit-defined inputs for standard handlers. Explicit
|
||||
registration binds flags and operands to fields and supplies parsing and help
|
||||
metadata. CommandKit delivers parsed typed inputs to registered handlers.
|
||||
|
||||
Bindings support ordinary typed fields and presence-aware fields where omission
|
||||
has a separate meaning. CommandKit records supplied state independently of values
|
||||
and defaults, preserving explicitly supplied empty, false, and zero values.
|
||||
|
||||
CommandKit keeps parsed values, collections, and presence from one invocation out
|
||||
of subsequent invocations. Storage allocation and reuse are implementation
|
||||
choices. Handler closures and application state retain their own lifecycle;
|
||||
concurrent dispatch is a separate contract.
|
||||
|
||||
The invocation API supplies context and streams separately from CLI inputs.
|
||||
CommandKit creates its declarations and bindings from metadata and defers its
|
||||
acquisition calls to the selected handler. The binding system accepts domain value
|
||||
parsers; domain interpretation and validation belong to registered callbacks.
|
||||
|
||||
The public factory, binding, registration, and handler signatures and presence
|
||||
type names remain API design choices. No illustrative declaration establishes
|
||||
an exact public API.
|
||||
|
||||
### Outcomes and domain behavior
|
||||
|
||||
Resolve the command and handle help/version before loading application state.
|
||||
For execution, prepare independent invocation inputs, apply shared parsing and
|
||||
operand checks, then invoke the typed handler. Return its invocation outcome to
|
||||
the application.
|
||||
|
||||
CommandKit classifies shared usage errors and standard-family outcomes. Its
|
||||
handler result contract accepts application-specific outcomes and preserves their
|
||||
supplied classification. Scriptorium output validation and Notarius artifact
|
||||
outcomes, for example, remain domain results. CommandKit translates results from
|
||||
explicit classification and emits usage guidance for usage failures.
|
||||
|
||||
Common mechanics do not require a common success-report format for custom
|
||||
commands. The application owns its artifact and operational output contracts.
|
||||
Exact result/error interfaces and unresolved grammar choices are separate design
|
||||
work, not approvals implied by this decision.
|
||||
|
||||
### Contract scope and consumer guidance
|
||||
|
||||
This decision governs CommandKit's public contracts and implemented behavior.
|
||||
Each operation specifies the inputs, result semantics, callback lifetimes, and
|
||||
metadata its provider supplies. Consumers choose how to implement those callbacks
|
||||
and how to structure loading, execution, startup, and process status mapping.
|
||||
|
||||
Sharing acquisition and resolution between inspection and execution, and keeping
|
||||
acquisition focused on producing inspection views, are recommended practices.
|
||||
CommandKit supports those patterns through reusable inputs and lazy provider
|
||||
hooks. Its API preserves declared results and coordinates its own calls; arbitrary
|
||||
application internals remain application-owned.
|
||||
|
||||
Cobra isolation applies to CommandKit's exports and internal adapter. Independent
|
||||
consumer use of another CLI library remains an application choice. Additional
|
||||
families and source models can use capability contracts appropriate to their
|
||||
resources, with standard meanings preserved for operations that are installed.
|
||||
Construction, installation, help, version, and capability discovery use metadata
|
||||
without acquiring application state. The selected operation acquires what it
|
||||
needs after applicable input checks. Caller startup and callback effects retain
|
||||
their own lifecycle.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
### Dispatcher and ownership
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| Application-owned dispatcher forwarding standard families | Small integration surface and convenient migration, but custom syntax, root help, and errors still need cross-dispatcher coordination; removes less infrastructure. |
|
||||
| Standard definitions mounted into an application's framework | Reuses routing infrastructure, but application configuration can preserve inconsistent behavior outside mounted families. Internal framework reuse remains compatible with this decision. |
|
||||
| Shared metadata/help with separate routing | Unifies discovery but adds synchronization among metadata, routing, and parsing. One dispatcher avoids it. |
|
||||
| Both full dispatch and embeddable family handlers | Serves established external CLI architectures but adds integration surfaces and maintenance. Add embedding only for a concrete need. |
|
||||
| Raw-argument handlers for custom commands | Eases migration but leaves parsing and help responsibilities with applications. A future transition adapter would need to describe its separate parsing and help contract. |
|
||||
| Universal application runtime framework | Could absorb startup and operational services, but expands beyond the demonstrated CLI boundary and domain ownership. |
|
||||
| Verb-first standard paths | Groups actions, but distributes namespace ownership among individual routes. Namespace/resource-first paths keep family ownership clear. |
|
||||
| Reserve root `prompt` and `profile` for PromptKit | Provides short resource paths but consumes application namespaces. A single `promptkit` family gives the library one ownership boundary. |
|
||||
|
||||
### Registration
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| Declarative tree passed to construction | Makes assembly visible together; larger applications still need group composition. May become a convenience over the same registry. |
|
||||
| Constructor options for every command/group | Compact setup, but excessive options can obscure commands versus application settings. Option conventions remain API design work. |
|
||||
| Global registry populated by `init` | Less entry-point code, but hidden import effects, shared mutable state, and unclear ownership. Explicit instances avoid those costs. |
|
||||
|
||||
### Handler inputs
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| Parsed-value accessor object | Uniform handlers, but string-based lookup, runtime type errors, and repeated assembly remain. |
|
||||
| Individual typed parameters | Clear for small commands; grows into long signatures and adapter machinery. Typed structs scale more naturally. |
|
||||
| Reflection and struct tags | Compact declarations, but adds a tag language, field-discovery rules, and runtime declaration validation. Explicit bindings keep declarations visible. |
|
||||
| Typed command objects | Can organize complex handlers. CommandKit's invocation-state contract remains separate from caller-owned object lifetimes; objects are an application option. |
|
||||
| Generated bindings/adapters | Can combine compact authoring and typing, but adds tooling and generated-file maintenance without demonstrated need. |
|
||||
| Raw arguments | Simple routing integration, but returns common parsing and help to applications. |
|
||||
- Application dispatchers forwarding standard families would share handlers but
|
||||
leave custom-command parsing, root help, and diagnostics duplicated.
|
||||
- Raw-argument handlers or string-keyed input access would leave typed input
|
||||
assembly and presence handling with every consumer.
|
||||
- Reflection, struct tags, or generated bindings could shorten declarations but
|
||||
add another declaration language or toolchain.
|
||||
- Import-time registries or a separate integration registration framework would
|
||||
introduce hidden state or parallel assembly conventions.
|
||||
|
||||
## Consequences
|
||||
|
||||
One command system removes repeated routing, parser setup, help assembly, and
|
||||
shared error plumbing as well as standard inspection handlers. Domain handlers
|
||||
and their declarations remain recognizable application code.
|
||||
Applications use one command system while retaining domain ownership. Explicit
|
||||
bindings and captured declarations require deliberate assembly, but integrations
|
||||
can supply complete families through the same public contracts.
|
||||
|
||||
The public registration surface is larger than family delegation, and explicit
|
||||
bindings require connecting declarations to the correct fields. Those costs
|
||||
support consistent mechanics without requiring reflection or generated code.
|
||||
|
||||
Shared parsing defects can affect every adopter. Consumer and backend integration
|
||||
evidence must protect selected semantics, including ownership conflicts, help
|
||||
without configuration, presence, independent invocation inputs, cancellation,
|
||||
and domain outcomes.
|
||||
CommandKit releases document intentional compatibility changes. Coordinated
|
||||
application documentation and subprocess-caller updates are recommended migration
|
||||
practices.
|
||||
|
||||
The [architecture policy](../policy/architecture.md) owns normative boundaries.
|
||||
[ADR 0002](0002-cobra-backend.md) selects the backend, and
|
||||
[ADR 0003](0003-public-facade.md) defines its public/internal boundary.
|
||||
[GoDoc](../../command.go) owns declaration, installation, and callback contracts;
|
||||
the [consumer guide](../consumers/guide.md) explains their use. Exact grammar,
|
||||
commands, and outcomes belong in the [CLI reference](../cli.md). Binding identity,
|
||||
absence handling, factory defaults, and operation-specific preparation timing
|
||||
can evolve within this architecture through deliberate API changes.
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
# ADR 0002: Use Cobra and pflag as the initial internal CLI backend
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-06
|
||||
|
||||
## Context
|
||||
|
||||
CommandKit's selected dispatcher model needs nested routing, flags and operands,
|
||||
generated help, usage diagnostics, and invocation execution. Reimplementing this
|
||||
generic infrastructure would add work beyond the suite-specific inspection and
|
||||
consistency behavior that motivates the library.
|
||||
|
||||
## Decision
|
||||
|
||||
Use Cobra with pflag as the sole initial CLI backend. CommandKit translates its
|
||||
registrations into backend command trees, flag bindings, and execution callbacks.
|
||||
Reuse their routing, option parsing, help, context, and stream mechanisms and add
|
||||
adaptation where selected CommandKit semantics require it.
|
||||
|
||||
CommandKit retains its own public registration API, typed inputs, standard
|
||||
families, and observable contracts. Its public registration and handler APIs
|
||||
use CommandKit-owned definitions and typed inputs. Cobra commands and pflag
|
||||
getters stay within CommandKit's internal adapter. Independent consumer framework
|
||||
use remains application-owned. [ADR 0003](0003-public-facade.md) records the
|
||||
adapter and root-owned public contracts.
|
||||
|
||||
Invocations do not inherit parsed values or presence from previous invocations.
|
||||
Rebuilding the backend command tree and input storage from registered definitions
|
||||
is the initial implementation strategy; safe reuse remains an implementation
|
||||
choice. CommandKit's tree construction uses registered metadata and leaves
|
||||
acquisition callbacks uninvoked. Application startup and callback effects retain
|
||||
their own lifecycle.
|
||||
|
||||
Implement one concrete backend. There is no initial public backend selector or
|
||||
pluggable framework. A future replacement can change internal implementation
|
||||
while preserving the public API and selected behavioral contracts.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Alternative | Advantages | Reason not selected |
|
||||
| --- | --- | --- |
|
||||
| urfave/cli v3 | Destination bindings for flags and named operands, presence queries, and duplicate controls fit the chosen input model closely. | Credible alternative; Cobra's broader adoption is the preferred maintenance tradeoff. |
|
||||
| pflag alone | Established parsing with a smaller integration surface. | Leaves more routing, help integration, and command infrastructure to implement. |
|
||||
| Kong | Compact typed-struct and tag-driven declarations. | Its main declaration model differs from the explicit-binding API; adaptation reduces its benefit. |
|
||||
| Standard `flag` alone | Familiar variable binding and custom value parsing. | First-operand stopping requires adaptation for the intended syntax, with more custom command infrastructure. |
|
||||
| Expose Cobra as the public API | Less adapter code and the full framework surface. | Couples consumers to backend structures and framework-specific configuration. |
|
||||
| Interchangeable backends immediately | Future integration flexibility. | Adds abstraction and behavior surfaces without a current requirement. |
|
||||
|
||||
## Consequences
|
||||
|
||||
The framework supplies established generic CLI machinery. CommandKit still owns
|
||||
registration conflicts, reserved families, typed bindings and presence, standard
|
||||
help and diagnostics, provider integration, and selected reports and outcomes.
|
||||
|
||||
The adapter must accommodate explicit empty/false/zero values, independent parsed
|
||||
state, selected repetition and operand rules, and help without configuration.
|
||||
Backend features do not expand the standard automatically: for example,
|
||||
completion commands remain deferred unless deliberately selected.
|
||||
|
||||
Backend error handling must preserve application outcomes, avoid duplicate
|
||||
diagnostics, and return control to the application's entry point.
|
||||
|
||||
The [architecture policy](../policy/architecture.md) owns normative boundaries.
|
||||
[ADR 0001](0001-command-dispatch-and-inputs.md) records the dispatcher and input
|
||||
model.
|
||||
|
||||
Reviewed primary references from the selection:
|
||||
|
||||
- [Cobra API](https://pkg.go.dev/github.com/spf13/cobra).
|
||||
- [Cobra command and help guide](https://github.com/spf13/cobra/blob/main/site/content/user_guide.md).
|
||||
- [Cobra flag bindings](https://cobra.dev/docs/how-to-guides/working-with-flags/).
|
||||
- [pflag syntax and extension points](https://github.com/spf13/pflag).
|
||||
- [urfave/cli v3 API](https://pkg.go.dev/github.com/urfave/cli/v3).
|
||||
68
docs/adr/0002-public-facade-and-cli-backend.md
Normal file
68
docs/adr/0002-public-facade-and-cli-backend.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# ADR 0002: Own public contracts behind an internal CLI backend
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
## Date
|
||||
|
||||
2026-11-07; consolidates decisions made on 2026-10-06 and 2026-10-09.
|
||||
|
||||
## Context
|
||||
|
||||
CommandKit needs established routing, parsing, and help machinery while retaining
|
||||
control of its consumer contracts. Exposing a backend framework directly would
|
||||
couple applications and integration handlers to that framework's objects and
|
||||
configuration model.
|
||||
|
||||
## Decision
|
||||
|
||||
Use the root `commandkit` package as the core module's public facade. Optional
|
||||
integrations own their public contracts in separate modules under
|
||||
[ADR 0004](0004-optional-integration-modules.md).
|
||||
|
||||
Use Cobra with pflag as the internal CLI backend. Confine their types and
|
||||
operations to an internal adapter that translates CommandKit declarations and
|
||||
selected semantics into backend machinery. Registry logic, shared definitions,
|
||||
and standard handlers remain independent of backend structures. Do not mirror
|
||||
the complete backend API through renamed wrappers.
|
||||
|
||||
Public types and handles expose deliberate contracts and keep implementation
|
||||
state private. Exports must not reveal internal or backend types through aliases,
|
||||
embedding, signatures, method sets, loosely typed values, or backend-owned
|
||||
syntax errors. Translate those syntax failures into CommandKit diagnostics and
|
||||
outcomes. Caller-supplied objects and errors retain their documented handling;
|
||||
this boundary does not require transforming arbitrary application content.
|
||||
|
||||
Standard Go contracts remain appropriate. Deliberate upstream public types may
|
||||
be exposed by integrations that own those dependencies. Implementation may live
|
||||
in the owning public package; introduce internal layers and conversions where
|
||||
they simplify the code or protect the backend boundary.
|
||||
|
||||
There is one concrete backend, without a public backend-selection framework.
|
||||
A replacement must preserve public contracts or accompany deliberate
|
||||
compatibility changes. Backend defaults do not independently define CommandKit
|
||||
behavior.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- Exposing Cobra directly would reduce adapter work but make the framework part
|
||||
of the consumer contract.
|
||||
- A forwarding-only facade with duplicate internal representations would enforce
|
||||
layering at the cost of conversions without a demonstrated need.
|
||||
- pflag alone or the standard flag package would leave more routing and help
|
||||
machinery to implement. Other full CLI frameworks are credible alternatives;
|
||||
Cobra's adoption was the preferred maintenance tradeoff.
|
||||
- Interchangeable backends would add public assembly and behavior contracts
|
||||
before a concrete need exists.
|
||||
|
||||
## Consequences
|
||||
|
||||
Consumers depend on CommandKit's selected contracts while internal implementation
|
||||
can evolve. The adapter still needs to preserve typed inputs, presence, public
|
||||
error identity, and invocation lifetimes; package placement alone is insufficient.
|
||||
|
||||
The [architecture policy](../policy/architecture.md) owns dependency constraints,
|
||||
GoDoc owns exact exports, and the [internal overview](../internal/overview.md)
|
||||
owns package mechanics. Backend construction and reuse strategies are
|
||||
implementation choices within the invocation-isolation contract.
|
||||
61
docs/adr/0003-configuration-scopes.md
Normal file
61
docs/adr/0003-configuration-scopes.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# ADR 0003: Expose configuration scopes through declared capabilities
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
## Date
|
||||
|
||||
2026-11-07; consolidates decisions made on 2026-10-06.
|
||||
|
||||
## Context
|
||||
|
||||
An application may expose its own configuration and configurations belonging to
|
||||
integrated libraries. Repeating a configuration command tree for each one would
|
||||
duplicate operator mechanics. Requiring identical inspection capabilities would
|
||||
exclude useful integrations whose upstream APIs provide only a subset.
|
||||
|
||||
## Decision
|
||||
|
||||
Expose independently meaningful configurations as named scopes through a shared
|
||||
configuration command family. A scope identifies the configuration being
|
||||
inspected; a command family defines operations on its resources. An integration
|
||||
may expose either or both without requiring the other.
|
||||
|
||||
Each scope declares its supported operations and providers. Assemble standard
|
||||
commands from the available capabilities and describe actual availability through
|
||||
metadata-driven help and discovery. An unavailable capability does not prevent
|
||||
using the scope's other operations.
|
||||
|
||||
Validate required provider wiring against declared capabilities. Check selected
|
||||
operation availability before acquisition. Aggregate inspection must account for
|
||||
its requested coverage rather than silently dropping unsupported scopes.
|
||||
|
||||
Use narrow integration contracts, reusing upstream public types where useful.
|
||||
Applications supply acquisition and domain context; integrations adapt supported
|
||||
inspection APIs under [ADR 0004](0004-optional-integration-modules.md). Scope and
|
||||
comparison inputs follow the input/state separation in
|
||||
[ADR 0001](0001-command-dispatch-and-inputs.md).
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- A separate command tree per configuration would make the target part of the
|
||||
path but repeat shared operations and help.
|
||||
- Requiring every operation for every scope would make one missing capability
|
||||
block otherwise useful inspection.
|
||||
- One universal operation set across library families would assign operations
|
||||
to resources for which they have little meaning.
|
||||
|
||||
## Consequences
|
||||
|
||||
Operators use a common configuration family while providers can expose supported
|
||||
features incrementally. Capability declarations and help must describe actual
|
||||
coverage, and provider abstractions must remain proportionate to integration
|
||||
needs.
|
||||
|
||||
The [CLI reference](../cli.md#configuration-scopes) owns command inventory, scope
|
||||
names and defaults, selector syntax, aggregate applicability, and report ordering.
|
||||
The [consumer guide](../consumers/guide.md#configkit-scopes) and
|
||||
[GoDoc](../../integrations/ckconfig/contracts.go) own provider wiring and precise
|
||||
input/acquisition lifetimes. Those details do not require separate ADRs merely
|
||||
because they are public contracts.
|
||||
@@ -1,104 +0,0 @@
|
||||
# ADR 0003: Own public contracts through a root facade and internal CLI adapter
|
||||
|
||||
## Status
|
||||
|
||||
Partially superseded by [ADR 0010](0010-optional-integration-modules.md).
|
||||
|
||||
ADR 0010 narrows the root facade and public-type ownership decision to the core
|
||||
module and places optional library dependencies in integration modules. The
|
||||
remaining principles continue to apply; this record's decision text is retained.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-06
|
||||
|
||||
## Context
|
||||
|
||||
CommandKit needs room to change its internal implementation details while
|
||||
consumers retain access to a stable external API. Exposing backend assembly or
|
||||
extension structures would let applications ossify around implementation
|
||||
details that maintainers may later decide to replace.
|
||||
|
||||
ConfigKit, PromptKit, and ReleaseKit demonstrate facades that own public types
|
||||
and delegate through private state and explicit conversion. ConfigKit also
|
||||
translates upstream YAML parser structures into an independent internal document
|
||||
model.
|
||||
|
||||
The selection of Cobra as an internal dependency is compatible with this
|
||||
decision. Public API independence needs a genuine contract boundary, and
|
||||
keeping backend structures out of shared internal representations also makes
|
||||
future replacement easier.
|
||||
|
||||
## Decision
|
||||
|
||||
Use the module root `commandkit` as the sole initial supported public facade.
|
||||
Define CommandKit's public named types there and expose only selected operations,
|
||||
extension contracts, and documented methods. Handles keep implementation state in
|
||||
private fields.
|
||||
|
||||
Straightforward implementation may live in the root package without expanding
|
||||
its exports. Introduce internal packages, interfaces, and conversions where they
|
||||
simplify implementation or protect the backend boundary. Package organization and
|
||||
the amount of internal layering follow implementation needs. Additional public
|
||||
packages require a deliberate decision based on a durable consumer responsibility.
|
||||
|
||||
Do not alias public types to internal or backend types, anonymously embed those
|
||||
types to promote methods, or expose implementation bridge methods. Exported
|
||||
fields, signatures, variables, callbacks, interface methods, constraints, and
|
||||
method sets must not reveal internal or Cobra/pflag structures. CommandKit does
|
||||
not expose its internal backend objects or backend-specific syntax errors through
|
||||
its public API, including through loosely typed values or returned errors.
|
||||
Caller-supplied values and errors retain their documented handling; this boundary
|
||||
does not require inspecting or transforming arbitrary application objects.
|
||||
|
||||
Standard contracts such as `context.Context` and `io.Writer` remain appropriate.
|
||||
Public types from integration libraries, such as ConfigKit and PromptKit, may
|
||||
be selected as deliberate dependencies. Application input types remain
|
||||
application-owned. Go declarations and GoDoc own exact exported contracts.
|
||||
|
||||
Confine Cobra/pflag types and operations to an internal adapter. Registry logic,
|
||||
standard handlers, and shared definitions remain independent of backend structures.
|
||||
The adapter translates paths, descriptions, bindings, presence, callbacks, and
|
||||
selected help/outcome semantics into backend machinery. Do not reproduce Cobra's
|
||||
complete API through renamed wrappers.
|
||||
|
||||
Preserve independent parsed state per invocation under
|
||||
[ADR 0001](0001-command-dispatch-and-inputs.md). Factories, callbacks, and shared
|
||||
representations remain API and implementation design choices.
|
||||
|
||||
Translate backend-owned syntax failures into CommandKit diagnostics and outcomes.
|
||||
Preserve useful public identity for application handler errors and cancellation
|
||||
according to the invocation contract. Any conversions must preserve value
|
||||
ownership, callback lifetime, presence, and supported error semantics.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| Keep all machinery in the public root | Less forwarding, but harder consumer navigation and easier accidental public expansion. |
|
||||
| Require a forwarding-only root and separate internal representations | Enforces a uniform layering scheme. It can add duplicate types and callback plumbing before those mechanisms simplify implementation. |
|
||||
| Alias or embed implementation types | Less conversion code, but couples public type identity, fields, or method sets to internal choices. |
|
||||
| Hide Cobra only behind the public facade | Hides types from applications but allows backend structures to spread through internal logic, complicating replacement. |
|
||||
| Mirror Cobra's API with wrappers | Removes dependency names while preserving its conceptual coupling and compatibility surface. |
|
||||
| Public packages for registry, bindings, backend, and other mechanisms | Adds supported imports and assembly contracts without a distinct consumer responsibility. |
|
||||
| Selectable/pluggable backends immediately | Adds selection and extension machinery before a concrete need exists. |
|
||||
|
||||
## Consequences
|
||||
|
||||
Consumers depend on deliberate root contracts while internal algorithms,
|
||||
collaborators, and package boundaries can evolve. Useful application registration
|
||||
capabilities still need a proportionate API; minimizing accidental exports must
|
||||
not recreate repetitive consumer infrastructure.
|
||||
|
||||
Forwarding and conversion add maintenance where used. Proportionate checks should
|
||||
protect the public surface, backend isolation, and consumer behavior through the
|
||||
real adapter. The implementation determines which checks provide useful evidence;
|
||||
package relocation alone does not establish those properties.
|
||||
|
||||
Backend replacement can preserve the public Go API but must also preserve selected
|
||||
CLI behavior or follow the release policy for intentional incompatibilities.
|
||||
Backend defaults do not independently establish new CommandKit contracts.
|
||||
|
||||
The [architecture policy](../policy/architecture.md) owns normative boundaries.
|
||||
[ADR 0001](0001-command-dispatch-and-inputs.md) records the dispatcher/input model,
|
||||
and [ADR 0002](0002-cobra-backend.md) selects the initial backend.
|
||||
71
docs/adr/0004-optional-integration-modules.md
Normal file
71
docs/adr/0004-optional-integration-modules.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# ADR 0004: Separate optional CLI integrations from the core
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
## Date
|
||||
|
||||
2026-11-07; consolidates decisions made on 2026-10-09 and 2026-10-11.
|
||||
|
||||
## Context
|
||||
|
||||
Applications need CommandKit with different combinations of library integrations,
|
||||
including none. A core-only consumer should not acquire optional libraries in its
|
||||
module graph. Integrations also need a clear boundary between exposing operator
|
||||
tasks and taking over the upstream libraries' domain functionality.
|
||||
|
||||
## Decision
|
||||
|
||||
Keep the core and optional integrations in separate Go modules with their own
|
||||
public package contracts. Core owns shared CLI infrastructure. Integrations own
|
||||
standard operator-facing commands, provider contracts, content projections, and
|
||||
adapters for their libraries. They are not convenience libraries for
|
||||
application-internal use of upstream APIs.
|
||||
|
||||
Dependencies point from integrations toward core. Core's API, implementation,
|
||||
tests, examples, tools, and module requirements remain independent of optional
|
||||
integration libraries. An integration may depend on another integration when
|
||||
its responsibility requires it; document that dependency for consumers.
|
||||
|
||||
Applications explicitly install integration declarations through public core
|
||||
contracts. Importing a module installs nothing. Integrations supply convenient
|
||||
complete-family assembly and supported composition without accessing private
|
||||
core state or backend structures. Add narrow public core capabilities for actual
|
||||
integration needs rather than a universal provider or plugin framework.
|
||||
|
||||
The integrated libraries own configuration resolution, prompt preparation,
|
||||
comparison, validation, and other domain algorithms. CommandKit invokes their
|
||||
supported public APIs and preserves returned meaning, supported error identity,
|
||||
and safe-disclosure rules. The adopted upstream version governs those semantics;
|
||||
CommandKit does not maintain a parallel domain specification or reconstruct
|
||||
comparison from rendered text or redacted snapshots.
|
||||
|
||||
Integrations choose report content from suitable inspection evidence, preserving
|
||||
upstream confidentiality and presence distinctions. CommandKit may summarize or
|
||||
project that safe evidence for operator needs. Applications retain ownership of
|
||||
schemas, loading, engine construction, credentials, domain execution, and startup.
|
||||
Arbitrary application content is not implicitly safe for disclosure.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- Keeping integrations in core, or in packages within its module, would retain
|
||||
their dependencies in the core module graph.
|
||||
- Requiring applications to implement standard integration handlers would repeat
|
||||
command and reporting infrastructure.
|
||||
- Universal core provider types would introduce abstraction and conversion work
|
||||
before concrete integrations justify it.
|
||||
- Reimplementing upstream algorithms would duplicate domain ownership and could
|
||||
lose evidence already withheld from safe inspection values.
|
||||
|
||||
## Consequences
|
||||
|
||||
Consumers can adopt core independently and add integrations as needed. Separate
|
||||
modules require coordinated dependency, validation, and release work. Integrations
|
||||
remain maintained parts of CommandKit with shared CLI conventions.
|
||||
|
||||
Upstream changes require adapter and documentation updates against the adopted
|
||||
public contract. The [CLI reference](../cli.md) owns operator behavior, GoDoc owns
|
||||
provider contracts, and [ADR 0006](0006-invocation-reporting.md) owns the shared
|
||||
presentation boundary. Report formats, comparison statuses, and individual
|
||||
operation inventories can evolve without changing domain ownership.
|
||||
@@ -1,79 +0,0 @@
|
||||
# ADR 0004: Define standard inspection operations by family and capability
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-06
|
||||
|
||||
## Context
|
||||
|
||||
CommandKit serves applications with shared ConfigKit and PromptKit inspection
|
||||
needs. A defined operator surface establishes the infrastructure CommandKit
|
||||
provides. Different integrations expose different resources and inspection
|
||||
capabilities, while shared verbs benefit from consistent meanings.
|
||||
|
||||
## Decision
|
||||
|
||||
CommandKit supplies help and version reporting and defines ConfigKit and
|
||||
PromptKit inspection operations. Each family defines its own supported set of
|
||||
operations. Registration installs handlers for the capabilities supplied by the
|
||||
integration and exposes their availability through help and discovery metadata.
|
||||
|
||||
| Standard operation | Responsibility |
|
||||
| --- | --- |
|
||||
| `help` | Describe registered standard and application commands. |
|
||||
| `version` | Report application version by default; report embedded CommandKit version when explicitly selected. |
|
||||
| `config scopes` | List registered configuration scopes and supported operations. |
|
||||
| `config validate` | Validate the selected configuration and its configured definitions. |
|
||||
| `config show` | Display final effective configuration. |
|
||||
| `config sources` | Describe the acquired and synthetic input source inventory. |
|
||||
| `config explain` | Explain effective or historical values and provenance at a selected path. |
|
||||
| `config diff` | Compare effective configuration selections semantically. |
|
||||
|
||||
The optional PromptKit suite supplies `promptkit list prompts`,
|
||||
`promptkit list profiles`, `promptkit show prompt`, and `promptkit show profile`.
|
||||
These operations expose captured definition catalogs, prompt metadata, and
|
||||
backend-completed named execution targets. PromptKit definition capabilities and
|
||||
its configuration scope are registered according to their available provider
|
||||
operations. Either can be integrated independently.
|
||||
|
||||
Adoption can use the supported subset under
|
||||
[ADR 0001](0001-command-dispatch-and-inputs.md). Missing comparison or catalog
|
||||
capabilities leave other inspection operations available.
|
||||
|
||||
Shared verbs keep consistent purposes: `list` enumerates resources, `show`
|
||||
displays a selected resource, and `diff` compares supported representations. Each
|
||||
family specializes those purposes for its own resources.
|
||||
|
||||
Version subjects are independent of configuration scopes and loading providers.
|
||||
|
||||
CommandKit owns vocabulary and observable contracts within its standard families.
|
||||
Custom execution, rendering, serving, sessions, and artifact workflows retain
|
||||
their application-owned meanings.
|
||||
|
||||
The [CLI reference](../cli.md) owns exact flags, operands, defaults, and report
|
||||
schemas for implemented operations.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| Initial operations limited to validation and display | Accelerates first integrations. Source explanation, comparison, and discovery remain repeated application infrastructure. |
|
||||
| Require every operation for every integration | Gives a uniform inventory. One unavailable capability blocks other useful operations and future resource families. |
|
||||
| Definition inspection through configuration operations alone | Source values and provenance share one path. Captured catalogs and completed execution targets require additional interpretation. |
|
||||
| Standardize execution and mutation alongside inspection | Expands shared vocabulary to more workflows. Additional domain and state-management contracts require their own evidence and design. |
|
||||
| Display dependency identities in ordinary application version output | Makes dependency information immediately visible. Application identity becomes coupled to dependency reporting. |
|
||||
|
||||
## Consequences
|
||||
|
||||
CommandKit supplies shared handlers with predictable meanings and discovers their
|
||||
availability from registration. Each enabled operation needs its own data
|
||||
contract: comparison needs supported native comparison results, catalogs need
|
||||
enumeration, and profile display needs safe execution-target inspection.
|
||||
|
||||
The [scope model](0009-configuration-scopes.md) and
|
||||
[comparison policy](0008-semantic-configuration-diff.md) describe related
|
||||
capability and behavioral decisions.
|
||||
65
docs/adr/0005-application-alias-routing.md
Normal file
65
docs/adr/0005-application-alias-routing.md
Normal file
@@ -0,0 +1,65 @@
|
||||
# ADR 0005: Separate application alias routing from canonical command ownership
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
## Date
|
||||
|
||||
2026-11-07; original decision made on 2026-10-19.
|
||||
|
||||
## Context
|
||||
|
||||
Applications need alternate command paths and flag spellings that suit their
|
||||
operator vocabulary. These conveniences should reuse the behavior supplied by
|
||||
application commands and optional integrations. Canonical command families
|
||||
already establish ownership of handlers, namespaces, inputs, and invocation
|
||||
behavior.
|
||||
|
||||
A routing layer allows applications to choose alternate spellings while
|
||||
preserving those ownership boundaries. Commands and routing rules have distinct
|
||||
roles, and their relationships require validation during application assembly.
|
||||
|
||||
## Decision
|
||||
|
||||
CommandKit core owns alias declaration, resolution, and coordination with parsing
|
||||
and help. Applications choose their alias mappings. Alias infrastructure is
|
||||
available independently of optional integrations under
|
||||
[ADR 0004](0004-optional-integration-modules.md).
|
||||
|
||||
Aliases belong to an application routing layer that directs invocations to
|
||||
canonical commands and flags. Canonical definitions retain ownership of their
|
||||
handlers, inputs, and namespaces. An alternate path within an integration's
|
||||
namespace remains an application routing rule; the integration continues to own
|
||||
the canonical command family and its operations.
|
||||
|
||||
Canonical commands and routing rules are distinct declaration kinds installed
|
||||
through the common assembly boundary in [ADR 0001](0001-command-dispatch-and-inputs.md).
|
||||
Installation validates their relationships together and preserves canonical
|
||||
ownership. Declaration capture, retained errors, and batch validation follow that
|
||||
shared model.
|
||||
|
||||
An invocation through an alias uses the canonical target's parsing, typed
|
||||
bindings, validation, and ordinary invocation lifecycle. Execution behavior
|
||||
remains with the canonical command and its owning application or integration.
|
||||
Core coordinates alternate routing and presentation through the same command
|
||||
infrastructure.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- Wrapper commands would introduce additional nodes and handler delegation into
|
||||
namespace ownership and invocation lifetimes.
|
||||
- Application argument rewriting would repeat routing infrastructure and separate
|
||||
alias handling from target validation, parsing, and help.
|
||||
- A separate alias assembly API would split validation of commands and their
|
||||
alternate routes across installation boundaries.
|
||||
|
||||
## Consequences
|
||||
|
||||
Applications can tailor vocabulary while reusing canonical behavior. Core must
|
||||
coordinate routing, parsing, and help across those layers, while optional
|
||||
integrations retain ownership of their command families.
|
||||
|
||||
GoDoc and the [CLI reference](../cli.md#application-owned-aliases) own exact API
|
||||
shapes, resolution rules, and presentation choices. Those details can evolve
|
||||
within this architectural separation.
|
||||
@@ -1,78 +0,0 @@
|
||||
# ADR 0005: Return explicit outcomes and deliver reports through defined channels
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-06
|
||||
|
||||
## Context
|
||||
|
||||
An invocation crosses routing, parsing, provider acquisition, a standard or
|
||||
application handler, report writing, and the application entry point. Operators
|
||||
and subprocess consumers need consistent classifications for those stages.
|
||||
Applications also have meaningful domain outcomes of their own.
|
||||
|
||||
## Decision
|
||||
|
||||
CommandKit returns an invocation outcome with an explicit classification and
|
||||
recommended process status. The public model distinguishes successful operation,
|
||||
usage error, operational failure, and application domain outcome. Failures retain
|
||||
their consumer-facing cause and supported `errors.Is`/`errors.As` identity.
|
||||
Exact Go declarations remain part of facade API design under
|
||||
[ADR 0003](0003-public-facade.md).
|
||||
|
||||
Use these mappings for CommandKit-owned commands:
|
||||
|
||||
| Status | Meaning |
|
||||
| --- | --- |
|
||||
| `0` | The requested operation completed successfully. |
|
||||
| `1` | A syntactically valid operation failed during loading, validation, lookup, inspection, cancellation, diagnostics delivery, or report writing. |
|
||||
| `2` | The invocation failed command, flag, scope, format, operand, or input-combination validation. |
|
||||
|
||||
CommandKit's handler result contract accepts domain classifications and suggested
|
||||
process statuses supplied by the caller. CommandKit preserves that classification
|
||||
when returning the handler's result. A custom domain status and a shared usage
|
||||
status may have the same numeric value; their explicit classifications retain
|
||||
their distinct meanings. The application entry point controls final process
|
||||
termination and status mapping.
|
||||
|
||||
CommandKit writes standard reports to the supplied report stream, conventionally
|
||||
stdout, and its warnings and errors to the supplied diagnostic stream,
|
||||
conventionally stderr. Callers choose the streams. CommandKit assigns responsibility
|
||||
for presenting its diagnostics, avoids duplicate presentation through its own
|
||||
paths, and reports write failures. Caller callbacks retain control of their own
|
||||
output. CommandKit adapts backend syntax failures into its public classification
|
||||
and diagnostic presentation. Usage guidance accompanies usage errors; operational
|
||||
failures receive diagnostics appropriate to the failed operation.
|
||||
|
||||
Warning severity alone permits a successful operation. A diagnostic writer
|
||||
failure is an operational failure.
|
||||
|
||||
A writer failure can leave a partial report and returns operational failure. The
|
||||
outcome identifies incomplete delivery. Custom handler output remains
|
||||
application-owned. [ADR 0007](0007-native-yaml-reports.md) covers `config show` report
|
||||
preparation; [ADR 0008](0008-semantic-configuration-diff.md) defines successful
|
||||
comparison outcomes.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| A single failure classification | Simplifies outcome handling. Callers derive syntax, operational, and domain distinctions through additional interpretation. |
|
||||
| Backend errors and output as the public outcome model | Reuses framework machinery directly. Backend conventions become dependencies for applications and subprocess consumers. |
|
||||
| One common mapping for application domain failures | Produces uniform numeric statuses. Applications adapt existing artifact and execution outcomes to shared categories. |
|
||||
| Handler-owned diagnostics for every failure | Gives each handler full presentation control. Shared diagnostic consistency requires repeated ownership and formatting coordination. |
|
||||
|
||||
## Consequences
|
||||
|
||||
The outcome model supports both Go callers and executable entry points. Explicit
|
||||
classification keeps domain identity intact through adapter and facade conversion.
|
||||
Single diagnostic ownership supports predictable presentation.
|
||||
|
||||
The public result/error design must preserve cause and delivery failures across
|
||||
handlers, writers, and the backend adapter. Diagnostic delivery bookkeeping
|
||||
remains API design work. Acceptance establishes the compatibility meaning of the
|
||||
status values and delivery rules across standard commands.
|
||||
@@ -1,77 +0,0 @@
|
||||
# ADR 0006: Apply common command grammar and recommend shared vocabulary
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-06
|
||||
|
||||
## Context
|
||||
|
||||
CommandKit owns routing, parsing, and help for standard and registered application
|
||||
commands. A concrete grammar makes option placement, operands, repetition, and
|
||||
help predictable across the application suite. Shared vocabulary also reduces
|
||||
the need to remember different verbs for equivalent operations.
|
||||
|
||||
## Decision
|
||||
|
||||
CommandKit's standard grammar and vocabulary are part of the contract for
|
||||
CommandKit-owned commands. Its shared dispatcher and binding APIs implement that
|
||||
grammar, so application-owned commands registered through those APIs receive the
|
||||
same parsing mechanics. Applications retain ownership of their command names,
|
||||
operand meanings, and domain behavior.
|
||||
|
||||
CommandKit's documentation recommends the same grammar and vocabulary for
|
||||
application-owned commands, including commands implemented outside its dispatcher.
|
||||
Applications are encouraged to use standard verbs such as `help`, `list`, and
|
||||
`show` where their operations have the corresponding purposes described in
|
||||
[ADR 0004](0004-standard-inspection-surface.md).
|
||||
|
||||
CommandKit parses options after the complete registered command path. Within the
|
||||
selected command, options and declared operands may be interspersed. Operand
|
||||
counts and types come from registration.
|
||||
|
||||
Standard options use lowercase names with hyphen-separated words and the `--`
|
||||
prefix. Value options accept `--name value` and `--name=value`. Boolean options
|
||||
accept their documented presence form and explicit values such as `--name=false`.
|
||||
The `--` token ends option parsing; subsequent tokens are operands.
|
||||
|
||||
Registered metadata identifies each flag as singleton or repeatable. For a
|
||||
singleton, the last occurrence supplies its value, including when the invocation
|
||||
mixes supported spellings. A repeatable flag accumulates values in invocation order.
|
||||
Presence follows the typed-input contract in
|
||||
[ADR 0001](0001-command-dispatch-and-inputs.md).
|
||||
|
||||
CommandKit validates paths, flag names, conversions, operand counts, and declared
|
||||
input combinations through the shared parser. Those failures use the usage
|
||||
classification in [ADR 0005](0005-invocation-outcomes.md).
|
||||
|
||||
Root help is available through `app`, `app help`, `app --help`, and `app -h`.
|
||||
Invoking a command group with no registered execution handler displays group help.
|
||||
A runnable command follows its registered handler and operand requirements,
|
||||
including when it also has subcommands. CommandKit-owned groups such as `config`
|
||||
display help on bare invocation. `app help COMMAND ...` and a resolved command's
|
||||
`--help` display the same registered help. Required execution operands are checked
|
||||
for execution requests; help uses registered metadata. Invalid paths and flag
|
||||
names receive usage diagnostics.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| Flags before all operands | Gives argument order a simple positional rule. Operators organize values around that rule when assembling commands. |
|
||||
| Common flags before or between command-path components | Supports familiar global-option styles. Routing and help need rules for options across several command levels. |
|
||||
| Reject repeated singleton flags | Detects repeated assignments, but prevents callers from assembling defaults followed by explicit overrides. |
|
||||
| Application-selected parser conventions | Supports existing CLI implementations. Operators and shared help need per-application syntax knowledge. |
|
||||
|
||||
## Consequences
|
||||
|
||||
Operators learn one option placement and repetition policy for adopting
|
||||
commands using CommandKit. Shared vocabulary guidance encourages consistent
|
||||
names for equivalent application-owned operations.
|
||||
|
||||
The internal adapter must preserve the selected grammar across backend changes.
|
||||
The [CLI reference](../cli.md) owns operation-specific command signatures and
|
||||
examples for implemented commands.
|
||||
78
docs/adr/0006-invocation-reporting.md
Normal file
78
docs/adr/0006-invocation-reporting.md
Normal file
@@ -0,0 +1,78 @@
|
||||
# ADR 0006: Share invocation reporting while preserving application outcomes
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
The structured-report formatting extension is accepted but not yet implemented;
|
||||
the [adoption roadmap](../roadmap/promptkit-v0.20.0.md#shared-core-report-output-prerequisite)
|
||||
tracks that work.
|
||||
|
||||
## Date
|
||||
|
||||
2026-11-07; consolidates decisions made on 2026-10-06 and 2026-10-25
|
||||
and the accepted shared-format ownership extension.
|
||||
|
||||
## Context
|
||||
|
||||
An invocation crosses routing, parsing, acquisition, command execution, and output
|
||||
delivery. Applications need consistent presentation and useful returned outcomes
|
||||
without giving a CLI library control of domain recovery or process termination.
|
||||
Separate reporting facilities would repeat visibility and failure-handling rules.
|
||||
|
||||
## Decision
|
||||
|
||||
Core provides one reporting facility per invocation for command results,
|
||||
immediate messages, deferred messages, and final presentation. Callers choose
|
||||
result and diagnostic destinations. Applications and integrations choose content,
|
||||
messages, and domain outcomes; core coordinates visibility, delivery, and its
|
||||
own parsing and presentation failures.
|
||||
|
||||
Applications decide whether a domain error warrants recovery, a warning, or a
|
||||
failed invocation. They supply explicit outcomes and explanations, optionally
|
||||
with an error cause. A cause alone does not select an outcome or create an
|
||||
operator-facing message. Preserve supplied causes and their supported public
|
||||
identity. Integrations adapt upstream evidence without taking ownership of its
|
||||
domain meaning or disclosure rules.
|
||||
|
||||
Return explicit outcome classifications that distinguish shared usage and
|
||||
operational failures from application-defined domain outcomes. Preserve domain
|
||||
classification and keep presentation failures separately observable from the
|
||||
operation's explanation and cause. Delivery failure must be visible without
|
||||
silently discarding the application's result. The application entry point owns
|
||||
final process status mapping and termination.
|
||||
|
||||
Present terminal failure explanations after ordinary reporting finishes. Core
|
||||
coordinates its own diagnostic paths to avoid duplicate presentation. Reporting
|
||||
state serves delivery and the returned outcome; logging and message history
|
||||
remain application responsibilities.
|
||||
|
||||
The accepted structured-report extension centralizes format selection,
|
||||
serialization, and rendering in core. Applications and integrations hand off
|
||||
selected content, including their chosen detail level and optional text template;
|
||||
core determines how to output it. New core formats should work through that
|
||||
shared handoff without each command maintaining encoders. This extends the same
|
||||
invocation lifecycle, with a writer API sharing rendering outside invocations.
|
||||
Implementation status and initial format choices remain in the roadmap above.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- Handler-owned presentation would maximize local control but repeat output,
|
||||
visibility, and delivery-error infrastructure.
|
||||
- Letting core interpret domain errors would give it recovery decisions that
|
||||
depend on application behavior.
|
||||
- One failure category or numeric status alone would lose meaningful distinctions
|
||||
between usage, operational, and domain results.
|
||||
- Separate facilities for results and messages, or encoders in each integration,
|
||||
would spread shared behavior across independent implementations.
|
||||
|
||||
## Consequences
|
||||
|
||||
Commands share presentation while retaining ownership of their content and
|
||||
outcomes. Core must keep operation and presentation evidence distinguishable,
|
||||
including when output is partial. Caller writers retain their own lifecycle.
|
||||
|
||||
GoDoc and the [CLI reference](../cli.md#reporting) own implemented APIs, numeric
|
||||
statuses, visibility controls, and exact delivery behavior. Report layouts,
|
||||
format defaults, YAML framing, and scope ordering are presentation contracts,
|
||||
not separate architectural decisions. The shared-format extension remains
|
||||
planned until its implementation and canonical contracts land.
|
||||
@@ -1,73 +0,0 @@
|
||||
# ADR 0007: Use native YAML and ordered documents for inspection reports
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-06
|
||||
|
||||
## Context
|
||||
|
||||
ConfigKit and PromptKit provide native YAML configuration inspection. Reusing
|
||||
their writers preserves captured value semantics, ordering, and redaction. YAML
|
||||
also supports automated consumption of structured reports.
|
||||
|
||||
## Decision
|
||||
|
||||
The initial standard uses text for concise operator reports and YAML for
|
||||
structured consumption.
|
||||
|
||||
A single-scope `config show` writes the owning library's complete native redacted
|
||||
YAML. Its output consists of the inspection document itself. The native writer
|
||||
preserves effective presence, null and container distinctions, stable mapping
|
||||
order, and sequence order according to its public contract.
|
||||
|
||||
`config show --scope all` emits one native document per registered scope in the
|
||||
order defined by [ADR 0009](0009-configuration-scopes.md). CommandKit supplies
|
||||
document separators and scope-label comments around native writer output. Each
|
||||
scope retains its own value namespace and native rendering; the documents can
|
||||
be decoded individually.
|
||||
|
||||
For `config show`, CommandKit checks operation availability for selected scopes
|
||||
before acquisition. It acquires all selected views and completes validation
|
||||
required by those provider contracts before report output begins. A failure
|
||||
returns its diagnostic outcome before report writing. Other inspection operations
|
||||
define their own output timing. After writing begins, a writer failure may leave
|
||||
partial bytes and returns operational failure under
|
||||
[ADR 0005](0005-invocation-outcomes.md).
|
||||
|
||||
Report confidentiality follows the owning libraries' sensitivity classifications.
|
||||
Their safe writers and records supply redacted content. CommandKit preserves
|
||||
those confidentiality semantics; arbitrary caller content retains the caller's
|
||||
disclosure policy.
|
||||
|
||||
Additional families select formats appropriate to their resources. Custom handler
|
||||
formats remain application-owned. The [CLI reference](../cli.md) owns exact
|
||||
per-operation formats, framing syntax, and report shapes for implemented commands.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| A scope-keyed YAML wrapper | Carries scope identity as parsed mapping keys. Rendering needs an additional wrapper representation and indentation of native documents. |
|
||||
| JSON alongside YAML initially | Serves JSON-specific tools. The library maintains another serializer and representation contract. |
|
||||
| YAML as every report's default | Provides uniform structured output. Interactive help, tables, and explanation workflows use structured documents for routine discovery. |
|
||||
| Write `config show` documents as each scope is acquired | Starts reporting earlier. A later acquisition failure can leave a successful prefix representing only part of the selection. |
|
||||
| Marshal application runtime structs | Reuses application data types. Presence, captured resolution, ordering, and safe historical inspection need a separate rendering lifecycle. |
|
||||
|
||||
## Consequences
|
||||
|
||||
Native display preserves owning-library behavior and keeps rendering focused.
|
||||
Combined inspection requires multi-document YAML consumption and an ordered scope
|
||||
contract.
|
||||
|
||||
Loading all selected scopes before `config show` output adds preparation time and
|
||||
allows a failure in one scope to prevent combined display. Explicit single-scope
|
||||
display remains available for a narrower view.
|
||||
|
||||
Additional structured schemas are compatibility contracts owned by CommandKit.
|
||||
Native concatenation can use existing writers; semantic comparison uses the owning
|
||||
library's supported comparison API under
|
||||
[ADR 0008](0008-semantic-configuration-diff.md).
|
||||
@@ -1,84 +0,0 @@
|
||||
# ADR 0008: Delegate effective configuration comparison to owning libraries
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-06; revised 2026-10-11.
|
||||
|
||||
## Context
|
||||
|
||||
ConfigKit provides a native configuration comparison capability. Exposing it
|
||||
through CommandKit gives applications a consistent operator interface and reduces
|
||||
repeated command, selection, and reporting infrastructure. ConfigKit remains the
|
||||
authority for the meaning and disclosure of its comparison results.
|
||||
|
||||
## Decision
|
||||
|
||||
### Comparison ownership
|
||||
|
||||
For ConfigKit-backed scopes declaring comparison support, `config diff` exposes
|
||||
ConfigKit's native comparison API. CommandKit checks capability availability before
|
||||
acquisition and coordinates selection, acquisition, adaptation, presentation,
|
||||
and invocation outcomes.
|
||||
|
||||
Integrations delegate comparison to their owning libraries' supported public
|
||||
APIs. ConfigKit owns its comparison semantics and disclosure rules. CommandKit
|
||||
follows the public contract of the ConfigKit version it adopts. When an adopted
|
||||
upstream revision changes those semantics, the changes flow through to
|
||||
CommandKit's integration. Upstream remains authoritative as the capability evolves.
|
||||
|
||||
Application-supplied providers retain ownership of their implementation and
|
||||
loading effects. [ADR 0012](0012-typed-configuration-comparison-pairs.md) governs
|
||||
paired selections, provider contracts, and typed input/shared-state lifetimes.
|
||||
|
||||
### Safe disclosure and presentation
|
||||
|
||||
Adapt and present native comparison results in accordance with the adopted
|
||||
upstream API's disclosure contract. The integration carries the upstream results
|
||||
and relevant metadata through its public provider boundary.
|
||||
|
||||
CommandKit owns report presentation and may summarize or transform the returned
|
||||
safe comparison data for different operator needs. Reports may vary in format,
|
||||
organization, and detail while respecting safe disclosure and the evidence
|
||||
provided by the comparison. Each report's documented meaning defines the
|
||||
conclusions an operator can draw from it.
|
||||
|
||||
Report formats, schemas, and rendering choices belong in the
|
||||
[CLI reference](../cli.md) when implemented. They can evolve independently of
|
||||
this ownership decision under the [release policy](../policy/release.md).
|
||||
|
||||
### Invocation outcomes
|
||||
|
||||
A completed comparison returns success regardless of whether differences are
|
||||
reported. Load, comparison, and writer
|
||||
failures use the operational failure classification in
|
||||
[ADR 0005](0005-invocation-outcomes.md). Applications may use comparison results
|
||||
to make their own domain decisions.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| Compare safe snapshots in CommandKit | Gives CommandKit direct control over comparison, but requires it to maintain equality and sensitivity logic and account for values already withheld from snapshots. Native comparison keeps those responsibilities with the owning library. |
|
||||
| Compare rendered configuration text | Reuses existing output, but formatting and masking affect the apparent differences. Native comparison supplies evidence grounded in the library's effective-value model. |
|
||||
| Leave comparison commands entirely to applications | Preserves application flexibility, but repeats selection, acquisition coordination, and presentation infrastructure across consumers. Integration providers retain application control within the common command system. |
|
||||
| Return a distinct status when differences are found | Supports assertion-oriented scripts, but couples successful inspection with a policy judgment about the result. The selected outcome model leaves that judgment to consumers. |
|
||||
|
||||
## Consequences
|
||||
|
||||
CommandKit supplies consistent comparison commands while relying on owning
|
||||
libraries for comparison semantics and safe disclosure. Dependency adoption
|
||||
includes adapting the integration and its documentation to upstream changes.
|
||||
New library integrations
|
||||
are assessed through their supported comparison contracts; each scope can expose
|
||||
its available capabilities independently under
|
||||
[ADR 0009](0009-configuration-scopes.md).
|
||||
|
||||
Reports can serve different operator needs using the same native comparison
|
||||
data. Their level of detail may differ, and sensitivity rules may limit what
|
||||
can be shown. Maintaining the boundary between comparison evidence and report
|
||||
presentation allows those reports to evolve while preserving library ownership
|
||||
and consumer control.
|
||||
@@ -1,80 +0,0 @@
|
||||
# ADR 0009: Select named configuration scopes with declared inspection capabilities
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-06
|
||||
|
||||
## Context
|
||||
|
||||
An application can expose its own configuration, PromptKit engine configuration,
|
||||
and other independently meaningful configurations through the `config` family.
|
||||
A scope identifies the configuration targeted by an operation. Different
|
||||
providers may support different inspection operations.
|
||||
|
||||
Configuration scopes and command families are distinct. A scope targets
|
||||
configuration; a family defines operations on its own resources. A library
|
||||
integration can expose either or both.
|
||||
|
||||
## Decision
|
||||
|
||||
Use stable semantic scope identifiers. The `app` scope describes application
|
||||
configuration; an optional `promptkit` scope describes captured engine
|
||||
configuration. Registration also accepts additional independently meaningful
|
||||
configuration scopes with unique identifiers.
|
||||
|
||||
Each scope declares its available inspection operations and their providers.
|
||||
Capabilities can include validation, native effective YAML, source inventory,
|
||||
path explanation, and safe semantic comparison data. CommandKit validates declared
|
||||
wiring and registers operations supplied by at least one scope under
|
||||
[ADR 0004](0004-standard-inspection-surface.md). Help and scope discovery report
|
||||
actual capabilities from metadata, independently of file loading.
|
||||
|
||||
Define narrow integration contracts, reusing upstream public types where useful
|
||||
and introducing CommandKit-owned abstractions where they simplify integration.
|
||||
Preserve supported upstream values, provenance, and confidentiality. Select
|
||||
provider representations against concrete integration needs; exact Go declarations
|
||||
remain API design work under
|
||||
[ADR 0003](0003-public-facade.md).
|
||||
|
||||
`--scope NAME` selects one configuration. `all` denotes all registered scopes for
|
||||
`config validate` and `config show`; `sources`, `explain`, and `diff` select one.
|
||||
An aggregate selection retains its all-scope meaning. CommandKit checks operation
|
||||
availability across the requested selection before acquiring views. An unavailable
|
||||
operation yields a usage diagnostic identifying the scope and available choices,
|
||||
so an aggregate result accurately describes the requested coverage.
|
||||
|
||||
`show`, `sources`, `explain`, `diff`, and `validate` default to `app`. Explicit
|
||||
`--scope all` requests aggregate validation or display.
|
||||
|
||||
Scope order is `app` first when registered, `promptkit` next when registered,
|
||||
then additional scopes sorted by identifier. `config scopes` and combined YAML
|
||||
show use that order. [ADR 0007](0007-native-yaml-reports.md) defines combined
|
||||
presentation. The [CLI reference](../cli.md) owns implemented selector syntax;
|
||||
the [consumer guide](../consumers/guide.md) explains acquisition integration.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| Require every configuration inspection operation per scope | Gives one capability set. Missing comparison or provenance blocks other useful inspection operations. |
|
||||
| A separate command tree for each configuration | Makes the target part of the path. Repeats common operations and help. |
|
||||
| One verb set for every library family | Gives a uniform inventory. Resource domains acquire operations with little useful meaning. |
|
||||
| Executable names as scope identifiers | Relates scopes to application branding. Shared scripts need application-specific identifiers. |
|
||||
| Validation defaults to `all` | Checks every scope implicitly, but adding a scope without validation support can make bare validation unavailable. |
|
||||
| Skip unsupported scopes during aggregate inspection | Produces available reports. The meaning and coverage of `all` become less apparent. |
|
||||
| Require CommandKit-owned provider types throughout | Gives a uniform abstraction boundary, but can duplicate upstream APIs and require unnecessary adapters. |
|
||||
|
||||
## Consequences
|
||||
|
||||
A shared configuration family serves multiple configurations while help and
|
||||
inventory make operation availability explicit. Individual capabilities can be
|
||||
integrated before other upstream inspection APIs exist. Default and ordering
|
||||
rules remain observable CommandKit behavior.
|
||||
|
||||
An `all` request can report unsupported coverage; default application inspection
|
||||
remains independent of other scopes' capabilities. Provider design must balance
|
||||
simple wiring against dependency coupling as concrete integrations are developed.
|
||||
@@ -1,100 +0,0 @@
|
||||
# ADR 0010: Separate the core facade from optional integration modules
|
||||
|
||||
## Status
|
||||
|
||||
Accepted. Partially supersedes
|
||||
[ADR 0003](0003-public-facade.md) as described below.
|
||||
Partially superseded by [ADR 0011](0011-captured-declarations-and-installation.md)
|
||||
for the consumer-migration consequence during the unreleased prototype
|
||||
transition. It also supplies the registration and invocation-lifetime
|
||||
decisions left open here. The module
|
||||
boundary and remaining principles continue to apply; this record's decision
|
||||
text is retained.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-09
|
||||
|
||||
## Context
|
||||
|
||||
CommandKit serves consumers that need its command infrastructure with different
|
||||
combinations of library integrations, including none. A consumer using only the
|
||||
core should not acquire dependencies belonging to optional integrations.
|
||||
|
||||
ADR 0003 establishes deliberate public contracts and an internal CLI backend
|
||||
boundary. Those principles remain appropriate. Its initial single root facade,
|
||||
however, combines core and integration responsibilities. Separate packages within
|
||||
one module would separate imports while retaining shared module requirements.
|
||||
|
||||
## Decision
|
||||
|
||||
Retain the root `commandkit` package as the core module's public facade. It owns
|
||||
core command declarations, registration, typed inputs, dispatch, help/version,
|
||||
shared syntax, diagnostics, and invocation outcomes.
|
||||
|
||||
Provide optional library integrations as separate Go modules with their own
|
||||
public package contracts. Each integration owns the standard command handlers,
|
||||
provider contracts, reports, and adapters appropriate to its responsibility.
|
||||
Applications select integrations and explicitly register their commands; importing
|
||||
an integration does not install a command family.
|
||||
|
||||
Integrations provide convenient registration of their standard command families,
|
||||
with standard declarations and handlers supplied by the integration. Applications
|
||||
provide acquisition and domain-specific context without assembling individual
|
||||
standard commands or repeating adapter plumbing. More specialized composition
|
||||
remains available where concrete consumer needs justify it.
|
||||
|
||||
Dependencies point from integrations toward the core. The core's public API,
|
||||
implementation, and module requirements remain independent of optional
|
||||
integration libraries. An integration may depend on another integration when
|
||||
its responsibility requires that relationship. Document such dependencies so
|
||||
consumers can understand the modules they select.
|
||||
|
||||
Integrations compose through supported public core contracts and preserve
|
||||
CommandKit's standard grammar, command ownership, help, and outcome conventions.
|
||||
They do not access private core state or backend structures. Add public contracts
|
||||
where concrete integration needs justify them, without requiring a general plugin
|
||||
or backend-selection framework.
|
||||
|
||||
### Relationship to ADR 0003
|
||||
|
||||
The root-facade and public-type ownership provisions of ADR 0003 now apply to
|
||||
the core module. Integration-owned public types and operations belong in their
|
||||
respective public packages. The permission to expose deliberately selected
|
||||
upstream library types applies within the integrations that depend on them;
|
||||
it does not justify optional integration dependencies in the core.
|
||||
|
||||
ADR 0003's remaining principles continue to apply across the core and
|
||||
integrations: deliberate exports, private implementation state, proportionate
|
||||
internal layering, no exposure of internal or backend types, and preservation of
|
||||
documented ownership, presence, callback lifetime, and error semantics. Application
|
||||
input types and caller-supplied values and errors retain their existing handling.
|
||||
Cobra/pflag remain behind the core's internal adapter.
|
||||
|
||||
This decision changes the scope of the single-facade decision rather than
|
||||
replacing its contract discipline. ADR 0003 is partially superseded and its
|
||||
original decision text remains intact.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| Keep integrations in the root package | Preserves existing imports and simplifies releases, but core consumers acquire optional library dependencies. |
|
||||
| Use separate packages within one module | Separates compiled imports and retains one release unit, but keeps integration requirements in the shared module graph. |
|
||||
| Have applications implement integration handlers | Keeps the core independent, but recreates duplicated inspection commands and weakens consistent operator behavior. |
|
||||
| Introduce universal provider contracts in the core | Could support several libraries through a common model, but adds abstractions and conversion obligations before concrete needs justify them. |
|
||||
|
||||
## Consequences
|
||||
|
||||
Consumers can adopt the core independently and add supported integrations as
|
||||
needed. Integrations remain maintained parts of CommandKit, with shared CLI
|
||||
conventions and owning-library semantics. Dependency independence does not mean
|
||||
the core has no external implementation dependencies.
|
||||
|
||||
Moving existing integration APIs requires a documented consumer migration.
|
||||
Integration modules add module-specific dependency, validation, and release work.
|
||||
Core tests, examples, and tools must not reintroduce the optional dependencies
|
||||
that this boundary removes.
|
||||
|
||||
Exact registration mechanics and release cadence are not selected here.
|
||||
Current GoDoc and CLI contracts continue to own implemented behavior.
|
||||
@@ -1,172 +0,0 @@
|
||||
# ADR 0011: Capture command declarations and install optional families explicitly
|
||||
|
||||
## Status
|
||||
|
||||
Accepted. Refines [ADR 0001](0001-command-dispatch-and-inputs.md) for declaration
|
||||
construction, installation, optional-family namespace reservation, and integration
|
||||
input/state lifetimes. Partially supersedes
|
||||
[ADR 0010](0010-optional-integration-modules.md) only for its consumer-migration
|
||||
consequence during the unreleased prototype transition, and refines its
|
||||
convenient composition principle.
|
||||
|
||||
Refined by [ADR 0012](0012-typed-configuration-comparison-pairs.md) for
|
||||
two-selection configuration comparison and its input/state lifetime. The
|
||||
single-selection lifecycle and other decisions remain in force.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-10
|
||||
|
||||
## Context
|
||||
|
||||
Applications declare domain commands, while optional integrations assemble
|
||||
standard command families. A common construction and installation model reduces
|
||||
repeated error checks and registration plumbing. Integrations need public typed
|
||||
composition contracts to assemble those families while preserving core and
|
||||
backend boundaries.
|
||||
|
||||
Declaration and installation have different responsibilities. An optional family
|
||||
claims a namespace when installed; selecting a dependency alone should leave the
|
||||
application's command surface unchanged. During execution, scope-specific CLI
|
||||
inputs and application-owned shared state also have distinct lifetimes. Making
|
||||
those lifetimes explicit avoids accidental aliasing between selected scopes.
|
||||
|
||||
At the time of this decision, the implementation was an unreleased prototype
|
||||
with no downstream consumers. Its API shapes carried no compatibility obligations
|
||||
that would constrain the selected design.
|
||||
|
||||
## Decision
|
||||
|
||||
### Declaration capture and reuse
|
||||
|
||||
Applications and integrations construct the same opaque core command declarations
|
||||
and install them through core application construction or registration. Initial
|
||||
integrations provide complete-family factories and focused conveniences through
|
||||
that common installation API. Suite and provider types remain integration-owned.
|
||||
|
||||
Factories eagerly capture metadata, bindings, capability selections, selector
|
||||
applicability, and callback references. They copy the declaration collections
|
||||
needed to isolate returned commands from later edits to source metadata.
|
||||
Construction errors remain attached for installation to report. This model uses
|
||||
eager declarations with public typed composition; a deferred preparation lifecycle
|
||||
and untyped integration payload are outside the selected API.
|
||||
|
||||
Declarations may be reused across applications with independent registry and
|
||||
invocation state. Callback references and captured application objects retain
|
||||
caller ownership. Reuse provides no deep-copy or concurrent-dispatch guarantee.
|
||||
Application helpers performing other fallible work may still return errors.
|
||||
|
||||
### Installation and retained errors
|
||||
|
||||
Core validates each installation batch before registry mutation, checking
|
||||
retained errors, bindings, placement, and collisions. Failed application
|
||||
construction returns no usable application; failed later registration preserves
|
||||
the existing registry. Atomicity covers one installation call. Separate calls
|
||||
and arbitrary callback effects retain their own lifetimes.
|
||||
|
||||
Report retained errors with useful command context and preserve supported wrapped
|
||||
error identity. The aggregate-error representation remains an implementation
|
||||
choice.
|
||||
|
||||
An explicit absence declaration contributes no command, help entry, or namespace.
|
||||
Installation checks attached errors before skipping it. A zero command declaration
|
||||
remains invalid. Integrations define their own empty-suite semantics: the initial
|
||||
configuration suite needs at least one named scope, and metadata-only scopes
|
||||
remain discoverable. A definition suite with no capabilities contributes nothing.
|
||||
|
||||
Binding validation applies to generated command declarations. Unused selector
|
||||
bindings in an absent family are ignored; explicitly retained adapter-construction
|
||||
errors still reach installation. A nil loader supplied to an adapter remains
|
||||
invalid wiring even if its capabilities are subsequently cleared.
|
||||
|
||||
### Namespace ownership and placement
|
||||
|
||||
Core construction reserves help and version. An optional standard family owns
|
||||
its complete root namespace upon installation. Imports and absent declarations
|
||||
claim nothing. An application may occupy an uninstalled family name; installing
|
||||
a conflicting declaration then fails in either registration order. Installation
|
||||
preserves existing handlers and group ownership. Private application operations
|
||||
remain outside installed standard families.
|
||||
|
||||
Standard families carry root-only placement metadata, which core enforces when
|
||||
they are nested beneath another group. Placement is a public declaration property;
|
||||
its enforcement is independent of package identity or a list of integration names.
|
||||
A real empty root-only group claims its namespace and obeys placement checks.
|
||||
Explicit absence contributes no node to place.
|
||||
|
||||
### Input and shared-state lifetimes
|
||||
|
||||
Integration suites distinguish typed CLI input from typed shared acquisition
|
||||
state. Ordinary configuration inspection initializes one input per selected scope,
|
||||
applies its applicable selector bindings, and initializes shared state once for
|
||||
the inspection invocation. Input validation receives the scope identity and its
|
||||
typed input. Named definition inspection uses one input and one shared state.
|
||||
Providers receive both explicitly. ADR 0012 refines this lifecycle for comparison
|
||||
pairs with two selections of one scope.
|
||||
|
||||
Availability preflight and applicable input checks precede shared-state
|
||||
initialization and acquisition. Failures may stop later input factories.
|
||||
Construction, installation, help, version, and scope discovery leave suite
|
||||
input/state factories and acquisition providers uninvoked.
|
||||
|
||||
An omitted factory supplies its type's zero value, including nil pointers.
|
||||
Applications provide initialization needed by their accessors and providers;
|
||||
providers may intentionally accept nil. Allocation of application objects,
|
||||
cloning, and aliases returned by factories remain caller responsibilities.
|
||||
Core-owned parsed collections stay independent when applied to separate inputs.
|
||||
Caller-owned objects and callback effects retain their own lifetimes.
|
||||
|
||||
### Typed binding composition
|
||||
|
||||
Core provides a narrow typed contract to capture converted values and apply a
|
||||
selected binding subset to initialized input. It preserves binding identity,
|
||||
defaults, and presence while keeping private setters, parser state, and backend
|
||||
objects behind their existing boundaries. A copied binding retains its identity;
|
||||
a newly constructed lookalike has its own identity.
|
||||
|
||||
Execution-required checks apply to the selected subset. Missing required input
|
||||
is a usage failure; invalid binding selection or destination is a wiring failure
|
||||
with operational classification at invocation. These categories remain identifiable
|
||||
through supported wrapping and stop execution before shared-state initialization
|
||||
and acquisition. Metadata defects detectable during assembly of generated
|
||||
commands remain installation errors under the validation boundary above.
|
||||
|
||||
### Relationship to earlier decisions
|
||||
|
||||
For the unreleased prototype transition covered by this decision, compatibility
|
||||
wrappers and a downstream migration guide were unnecessary. This exception to
|
||||
ADR 0010's migration consequence is limited to that transition. Changes to
|
||||
published contracts follow the [release policy](../policy/release.md).
|
||||
|
||||
ADR 0001 retains dispatcher, registry, typed-input, and application-ownership
|
||||
principles. ADR 0010 governs module boundaries and dependency direction, with
|
||||
[ADR 0003](0003-public-facade.md) governing deliberate exports and backend isolation
|
||||
within that scope. ADRs 0004 through 0009 retain their operation, grammar, report,
|
||||
and outcome decisions. Go declarations and GoDoc own exact implemented signatures.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| Fallible constructors plus integration-specific registration helpers | Makes each construction failure immediate, but creates several assembly conventions and repeated consumer checks. Captured errors keep one installation boundary. |
|
||||
| Deferred preparation callbacks | Allows installation to construct a family, but adds lifecycle and error timing beyond eager capture. No demonstrated assembly need requires it. |
|
||||
| Reserve all known optional family names at core construction | Prevents later name conflicts, but consumes namespaces for integrations the application has not selected. Installed-family ownership keeps conflicts explicit without that restriction. |
|
||||
| Separate family/plugin registration framework | Could encode ownership and composition, but a captured command with root-only placement and batch validation expresses the required behavior without another installation model. |
|
||||
| One shared input/state object | Uses fewer type parameters and can share a cache through references in separate input values, but leaves the distinct lifetimes implicit and scope-input isolation to application conventions. Explicit input and state types make those lifetimes visible. |
|
||||
| Clone hooks or automatic pointer allocation | Can hide input construction, but adds object-graph and initialization responsibilities that belong to the application. Explicit factories keep those choices visible. |
|
||||
| Public binding getters/setters or an untyped value bag | Enables integration assembly, but exposes private mechanics or returns typed-input assembly to string lookup. Narrow typed composition addresses the actual need. |
|
||||
|
||||
## Consequences
|
||||
|
||||
Consumers assemble domain commands and optional families through one installation
|
||||
boundary. Eager assembly errors reach that boundary before provider acquisition.
|
||||
Namespace collisions remain explicit choices for the application to resolve.
|
||||
|
||||
Separate input and state types make initialization and sharing visible. Focused
|
||||
conveniences support simple applications, while typed composition gives
|
||||
integrations the public contracts needed to assemble their families.
|
||||
|
||||
The [architecture policy](../policy/architecture.md) owns normative boundaries;
|
||||
roadmaps own implementation status and sequencing. Application loading, cache
|
||||
design, startup, domain validation, callback effects, and process exit remain
|
||||
consumer responsibilities.
|
||||
@@ -1,108 +0,0 @@
|
||||
# ADR 0012: Prepare typed selection pairs for configuration comparison
|
||||
|
||||
## Status
|
||||
|
||||
Accepted. Refines [ADR 0011](0011-captured-declarations-and-installation.md) for
|
||||
two-selection configuration comparison; its other decisions remain in force.
|
||||
[ADR 0008](0008-semantic-configuration-diff.md) governs native comparison and
|
||||
report presentation.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-11
|
||||
|
||||
## Context
|
||||
|
||||
Native effective-configuration comparison needs two completed loads. ConfigKit
|
||||
requires results of the same configuration type, which an ordinary inspection
|
||||
view does not expose for pairwise comparison. A generic adapter can retain that
|
||||
type without introducing result assertions or a universal core provider model.
|
||||
|
||||
ADR 0011 separates a selected scope's typed input from shared acquisition state.
|
||||
A comparison selects the same scope twice, potentially with different roots or
|
||||
overlays. Reusing one input obscures which selection a provider receives; creating
|
||||
separate shared state loses the invocation-wide lifetime chosen for inspection.
|
||||
|
||||
## Decision
|
||||
|
||||
### Selections and provider ownership
|
||||
|
||||
Comparison selects one scope and prepares an earlier/left selection and a
|
||||
later/right selection. Omitted right selection fields inherit the corresponding
|
||||
left field and supplied state. An explicit right override, including an empty
|
||||
value, replaces that field. Providers retain interpretation of omitted defaults
|
||||
and explicit empty values. Applicable domain selector values are shared between
|
||||
the two sides initially; independent per-side domain selectors may be considered
|
||||
for a concrete consumer need.
|
||||
|
||||
Equal selections are allowed. CommandKit does not skip acquisition merely because
|
||||
their selection values are equal: caller-owned loading may produce different
|
||||
effective results. Exact flag spellings belong in the CLI reference when
|
||||
implemented.
|
||||
|
||||
Use a narrow optional comparison provider owned by the integration. Its request
|
||||
groups each side's selection with its typed input and supplies one shared state
|
||||
value separately. The provider returns acquired native comparison results
|
||||
with diagnostics and an error through the existing acquisition convention.
|
||||
Reuse useful upstream public record types rather than duplicating them solely
|
||||
to rename fields. Exact exported signatures belong in Go declarations and GoDoc.
|
||||
|
||||
The typed ConfigKit adapter invokes the supplied loader for each reached side
|
||||
and passes the successful typed results to `configkit.Diff`. It retains the
|
||||
configuration type inside that adapter, without reflection, result type
|
||||
assertions, private core access, or a comparison-facet framework. Applications
|
||||
may supply their own pair provider through the same integration contract.
|
||||
|
||||
Declared capabilities determine required wiring. A comparison-only scope needs
|
||||
its comparison provider, without an unrelated ordinary acquisition callback.
|
||||
Ordinary operations continue to use their ordinary acquisition provider.
|
||||
Retained adapter construction errors still apply when capabilities are narrowed.
|
||||
Other scopes and families need not support comparison under
|
||||
[ADR 0009](0009-configuration-scopes.md).
|
||||
|
||||
### Typed input and shared state lifetime
|
||||
|
||||
Capture comparison declarations and applicable selector bindings under ADR 0011.
|
||||
Convert supplied flag values through core once, including on help paths; applying
|
||||
the values to both inputs does not parse them again.
|
||||
|
||||
After availability preflight, initialize each reached side's typed input
|
||||
separately, apply the same applicable captured selector values, and check that
|
||||
input with the selected scope identity and that side's selection. Finish both
|
||||
input checks before initializing shared state once and invoking the pair
|
||||
provider. Failures may stop later factories or loads. Construction, installation,
|
||||
help, version, and scope discovery invoke neither input/state factories nor
|
||||
acquisition/comparison providers.
|
||||
|
||||
Existing factory ownership rules remain unchanged: an omitted factory supplies
|
||||
its type's zero value, including nil pointers. Separate factory calls do not
|
||||
guarantee distinct caller-owned objects. CommandKit does not allocate arbitrary
|
||||
pointer types, clone application graphs, repair caller aliases, or supply or
|
||||
repair application caches. Core-owned parsed collections remain independent
|
||||
when applied to the two inputs; callback effects remain caller-owned.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| Symmetric independently resolved left/right selectors | Makes each side explicit and avoids inheritance. It adds vocabulary and repetition for common base-versus-overlay comparisons. |
|
||||
| One typed input for both sides | Requires fewer factory calls, but obscures side-specific selection checks and leaves mutation isolation implicit. |
|
||||
| Acquire a comparison facet with each ordinary view | Shares single-side acquisition across operations, but requires a public compatibility contract between heterogeneous facets and additional handle or assertion machinery. |
|
||||
| Separate shared state for each side | Isolates acquisition state, but loses the invocation-wide sharing already selected for inspection. Applications can choose isolation within their own pair provider if needed. |
|
||||
|
||||
## Consequences
|
||||
|
||||
Pair preparation has explicit input and state lifetimes while ordinary inspection
|
||||
keeps its existing lifecycle. Generic result handling stays inside the integration
|
||||
adapter; core gains no owning-library dependency or universal comparison model.
|
||||
|
||||
Shared state permits application-owned caches. A cache used by a pair provider
|
||||
should distinguish selections and any input values affecting loading to avoid
|
||||
reusing the left result for a different right selection. This is integration
|
||||
guidance, not a CommandKit cache policy or guarantee about caller callbacks.
|
||||
|
||||
The [architecture policy](../policy/architecture.md) owns normative boundaries.
|
||||
ADR 0008 governs delegation to upstream comparison semantics, safe disclosure,
|
||||
and CommandKit's presentation responsibility. This decision does not add a new
|
||||
equality engine or strengthen application
|
||||
loading, object ownership, or concurrency contracts.
|
||||
@@ -1,68 +0,0 @@
|
||||
# ADR 0013: Separate application alias routing from canonical command ownership
|
||||
|
||||
## Status
|
||||
|
||||
Accepted. Refines [ADR 0011](0011-captured-declarations-and-installation.md)
|
||||
by extending its shared installation boundary to application routing rules.
|
||||
Its canonical command ownership and declaration principles remain in force.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-19
|
||||
|
||||
## Context
|
||||
|
||||
Applications need alternate command paths and flag spellings that suit their
|
||||
operator vocabulary. These conveniences should reuse the behavior supplied by
|
||||
application commands and optional integrations. Canonical command families
|
||||
already establish ownership of handlers, namespaces, inputs, and invocation
|
||||
behavior.
|
||||
|
||||
A routing layer allows applications to choose alternate spellings while
|
||||
preserving those ownership boundaries. Commands and routing rules have distinct
|
||||
roles, and their relationships require validation during application assembly.
|
||||
|
||||
## Decision
|
||||
|
||||
CommandKit core owns alias declaration, resolution, and coordination with parsing
|
||||
and help. Applications choose their alias mappings. Alias infrastructure is
|
||||
available independently of optional integrations under the module boundaries
|
||||
established by [ADR 0010](0010-optional-integration-modules.md).
|
||||
|
||||
Aliases belong to an application routing layer that directs invocations to
|
||||
canonical commands and flags. Canonical definitions retain ownership of their
|
||||
handlers, inputs, and namespaces. An alternate path within an integration's
|
||||
namespace remains an application routing rule; the integration continues to own
|
||||
the canonical command family and its operations.
|
||||
|
||||
Canonical commands and routing rules are distinct declaration kinds installed
|
||||
through a common core assembly boundary. Installation validates their
|
||||
relationships together, preserves canonical definitions and namespace ownership,
|
||||
and applies the batch-atomicity and retained-error model of ADR 0011 to both
|
||||
layers. Declaration capture and reuse follow that existing model.
|
||||
|
||||
An invocation through an alias uses the canonical target's parsing, typed
|
||||
bindings, validation, and ordinary invocation lifecycle. Execution behavior
|
||||
remains with the canonical command and its owning application or integration.
|
||||
Core coordinates alternate routing and presentation through the same command
|
||||
infrastructure.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| Install aliases as wrapper commands | Reuses the command tree for discovery, but introduces additional command nodes and handler delegation into namespace ownership and invocation lifetimes. |
|
||||
| Have applications rewrite arguments before dispatch | Gives applications direct control over shortcuts, but repeats routing infrastructure and separates alias handling from target validation, parsing, and help. |
|
||||
| Register aliases through a separate assembly API | Makes routing declarations explicit, but splits validation of commands and their alternate routes across installation boundaries. Distinct declaration kinds express the separation within one atomic batch. |
|
||||
|
||||
## Consequences
|
||||
|
||||
Applications can tailor operator vocabulary while reusing canonical behavior.
|
||||
Core maintains the relationship between routing rules and canonical definitions
|
||||
as declarations are installed. Optional integrations continue to supply their
|
||||
command families through the existing ownership model.
|
||||
|
||||
Routing, parsing, and help must coordinate across the two layers. Exact API
|
||||
shapes, resolution rules, and presentation choices belong in GoDoc and the
|
||||
[CLI reference](../cli.md) when implemented. Those details can evolve within
|
||||
this architectural separation.
|
||||
@@ -1,79 +0,0 @@
|
||||
# ADR 0014: Share command-line presentation within each invocation
|
||||
|
||||
## Status
|
||||
|
||||
Accepted. Extends [ADR 0005](0005-invocation-outcomes.md) with shared reporting
|
||||
for each invocation. Its outcome classifications, standard status meanings,
|
||||
output channels, error-cause preservation, and application ownership of process
|
||||
exit remain in force.
|
||||
|
||||
## Date
|
||||
|
||||
2026-10-25
|
||||
|
||||
## Context
|
||||
|
||||
Applications need consistent control over command results, messages shown during
|
||||
a run, and messages shown at its end. Sharing that control reduces repeated
|
||||
output code across applications and integrations.
|
||||
|
||||
An application decides what an error means for its work. It may recover silently,
|
||||
show a warning, or end the invocation. CommandKit needs the chosen outcome and
|
||||
messages to present that decision to the operator.
|
||||
|
||||
## Decision
|
||||
|
||||
CommandKit core provides one reporting facility for each invocation. Application
|
||||
commands, integration commands, and core commands use it for results, immediate
|
||||
messages, and deferred messages. Core applies shared rules for visibility,
|
||||
formatting, and delivery, and completes reporting when the invocation ends.
|
||||
Callers choose the output destinations.
|
||||
|
||||
Applications decide how to respond to domain-specific errors and choose their
|
||||
outcomes and messages. CommandKit may provide shared helpers for carrying,
|
||||
inspecting, and presenting errors while leaving those decisions with the
|
||||
application.
|
||||
|
||||
Applications supply explicit outcomes and explanations for failures. They may
|
||||
also supply a Go error cause. CommandKit keeps that error unchanged for the caller
|
||||
to inspect. Supplying a cause alone does not select an outcome or generate an
|
||||
operator-facing message. CommandKit remains responsible for handling its own
|
||||
errors, including routing, parsing, and presentation failures.
|
||||
|
||||
Integrations adapt upstream results and diagnostics into command outcomes and
|
||||
messages. The upstream libraries retain ownership of their meanings and rules
|
||||
for safe disclosure.
|
||||
|
||||
An Error message explains a failed invocation with a non-zero status. Its
|
||||
explanation is presented at the end of the invocation, after normal reporting
|
||||
finishes. The returned outcome carries that explanation. The application entry
|
||||
point decides how to exit the process.
|
||||
|
||||
CommandKit reports rendering and delivery failures separately from the command's
|
||||
explanation. A presentation failure produces an operational failure for standard
|
||||
outcomes under ADR 0005. Application-defined domain classifications are preserved,
|
||||
along with an already non-zero domain status. A successful domain outcome receives
|
||||
a non-zero status if presentation fails. The original explanation and any supplied
|
||||
cause remain available to the caller. Intentionally suppressed output is not a
|
||||
delivery failure.
|
||||
|
||||
Reporting keeps the state needed to deliver messages and return the invocation
|
||||
outcome. Logging and message history remain application concerns.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Alternative | Analysis |
|
||||
| --- | --- |
|
||||
| Let each application manage all presentation | Gives applications full control, but repeats visibility and delivery code across commands and integrations. |
|
||||
| Have core decide whether domain-specific errors require recovery, a warning, or failure | Reduces some caller code, but gives core decisions that depend on application behavior. |
|
||||
| Use separate facilities for results, immediate messages, and deferred messages | Lets each facility serve one purpose, but spreads visibility and final delivery across several paths. |
|
||||
|
||||
## Consequences
|
||||
|
||||
Applications and integrations share presentation behavior while choosing their
|
||||
own results and messages. Core handles reporting failures consistently and keeps
|
||||
them visible in the returned outcome.
|
||||
|
||||
GoDoc and the [CLI reference](../cli.md) define the implemented API, flags,
|
||||
message formats, and delivery details. Those details can evolve within this
|
||||
ownership model.
|
||||
14
docs/adr/README.md
Normal file
14
docs/adr/README.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# Architectural decision records
|
||||
|
||||
These records explain major structural and ownership decisions. The
|
||||
[architecture policy](../policy/architecture.md) owns normative boundaries;
|
||||
GoDoc and the [CLI reference](../cli.md) own implemented contracts.
|
||||
|
||||
| ADR | Decision |
|
||||
| --- | --- |
|
||||
| [0001](0001-command-dispatch-and-inputs.md) | Dispatch, captured declarations, and typed inputs |
|
||||
| [0002](0002-public-facade-and-cli-backend.md) | Public facade and internal CLI backend |
|
||||
| [0003](0003-configuration-scopes.md) | Configuration scopes and declared capabilities |
|
||||
| [0004](0004-optional-integration-modules.md) | Optional integration modules and upstream ownership |
|
||||
| [0005](0005-application-alias-routing.md) | Alias routing and canonical command ownership |
|
||||
| [0006](0006-invocation-reporting.md) | Invocation reporting, outcomes, and presentation ownership |
|
||||
429
docs/cli.md
429
docs/cli.md
@@ -46,7 +46,7 @@ The supported flags are:
|
||||
| Flag | Values | Default | Meaning |
|
||||
| --- | --- | --- | --- |
|
||||
| `--scope` | `app`, `commandkit` | `app` | Select the caller's application identity or the embedded CommandKit module identity. |
|
||||
| `--format` | `text`, `yaml` | `text` | Select the output format. |
|
||||
| `--format` | `text`, `yaml`, `json` | automatic | Select the output format; automatic uses text for version. |
|
||||
|
||||
Text output is `NAME VERSION`, followed by ` (REVISION)` when the selected
|
||||
identity has a revision. An empty application version is displayed as `dev`;
|
||||
@@ -58,7 +58,7 @@ versionless replacement, an untagged module, or missing build information
|
||||
displays `dev`. The CommandKit identity name is `CommandKit`; dependency build
|
||||
metadata does not supply a revision.
|
||||
|
||||
YAML output uses these explicit fields, including an empty revision:
|
||||
YAML and JSON output use these fields, including an empty revision:
|
||||
|
||||
```yaml
|
||||
name: ExampleApp
|
||||
@@ -111,6 +111,14 @@ caller passes result and diagnostic writers to `App.Execute`; substantive
|
||||
results go to `Streams.Out`, and categorized messages, terminal explanations,
|
||||
and usage guidance go to `Streams.Err`.
|
||||
|
||||
The shared `--format` flag selects `text`, `yaml`, or `json` for reports
|
||||
submitted through the core reporter. When omitted, a report's text template
|
||||
selects text; otherwise scalar values and nonempty string lists use text, while
|
||||
structured values, empty collections, and null use YAML. Explicit text without a
|
||||
template uses YAML for structured values. Invalid or empty format values are
|
||||
usage errors. Raw output, help, completion, and diagnostics are not encoded as
|
||||
reports.
|
||||
|
||||
### Modes and visibility
|
||||
|
||||
Each invocation starts in ordinary mode. `--quiet`, `--verbose`, and `--debug`
|
||||
@@ -154,9 +162,9 @@ example version --quiet
|
||||
Reporting flags do not go before or between command-path components. Tokens
|
||||
consumed as values and tokens after `--` retain their normal meaning.
|
||||
|
||||
The reserved long spellings are `--quiet`, `--verbose`, `--debug`, and
|
||||
`--progress`; application declarations cannot reuse them. There are no built-in
|
||||
short spellings. Applications may define aliases such as `-q → --quiet`,
|
||||
The reserved long spellings are `--quiet`, `--verbose`, `--debug`,
|
||||
`--progress`, and `--format`; application declarations cannot reuse them. There
|
||||
are no built-in short spellings. Applications may define aliases such as `-q → --quiet`,
|
||||
`-v → --verbose`, and `-d → --debug`; canonical and aliased occurrences share
|
||||
the same ordering. Thus `example export --verbose -q` selects quiet mode.
|
||||
|
||||
@@ -289,14 +297,26 @@ example config scopes
|
||||
example config scopes --format yaml
|
||||
```
|
||||
|
||||
Text output uses one `scope: operation, operation` line per scope. YAML uses a
|
||||
`scopes` sequence with explicit `name` and `operations` fields. Scope order is
|
||||
Text output uses one `scope: operation, operation` line per scope and lists any
|
||||
declared optional features. Structured output uses a `scopes` sequence with
|
||||
`name`, `operations`, and any supported `features`. Scope order is
|
||||
`app`, then `promptkit`, then other names alphabetically. A metadata-only scope
|
||||
can be listed without an acquisition callback. Discovery does not construct a
|
||||
runtime context or acquire configuration. It reports the intersection between
|
||||
declared scope capabilities and installed handlers, so an operation is listed
|
||||
only when the corresponding command is available.
|
||||
|
||||
Scopes can opt in to transient overrides. For an opted-in scope, acquisition
|
||||
commands accept repeatable `--set POINTER=JSON`; comparison also accepts
|
||||
`--against-set POINTER=JSON` for the right side. Each assignment is passed to
|
||||
the loader in order, with `--set` or `--against-set` as its source label.
|
||||
The pointer and value are split at the first `=`, so pointer keys containing
|
||||
`=` cannot be addressed by these flags; JSON strings can contain `=`. Values
|
||||
use JSON types, including null, false, zero, and empty containers. ConfigKit
|
||||
owns override path validation and conflict handling. A selected scope must opt
|
||||
in before receiving overrides; for `--scope all`, every selected scope must
|
||||
support them.
|
||||
|
||||
Applications can add `ckprompt.ConfigScope(loadEngine)` to the ConfigKit suite
|
||||
to expose PromptKit engine configuration through these handlers. The scope
|
||||
declares validate, show, sources, explain, and native diff. It does not install
|
||||
@@ -308,54 +328,67 @@ PromptKit prompt or profile definition commands.
|
||||
`app`; `--scope all` validates every registered scope and is available when each
|
||||
scope declares validation. The command checks all selected capabilities before
|
||||
calling scope providers.
|
||||
Its default format is text; `--format yaml` emits a `scopes` sequence with
|
||||
`name` and `valid: true` for each scope that completed successfully.
|
||||
Automatic output is concise text; structured formats emit a `scopes` sequence
|
||||
with each reached scope and its outcome (`valid`, `failed`, or `canceled`).
|
||||
|
||||
```text
|
||||
example config validate
|
||||
example config validate --scope promptkit --format yaml
|
||||
example config validate --scope all
|
||||
example config validate --scope all --details --severity warning --code schema.version
|
||||
```
|
||||
|
||||
Each successful scope is reported as `SCOPE: valid`. Aggregate validation stops
|
||||
at the first load or output failure; records from earlier successful scopes may
|
||||
already have been written. Provider warnings go to the diagnostic stream and do
|
||||
not alone make validation fail. `--config` and `--overlay` preserve whether an
|
||||
at the first load failure or cancellation, then submits one report containing
|
||||
the reached scopes. Output errors occur after acquisition has stopped. Provider
|
||||
warnings go to the diagnostic stream and do not alone make validation fail.
|
||||
`--details` includes native findings and the source references needed to
|
||||
interpret them. Each scope's detail state is `unavailable`, `empty`, `filtered`,
|
||||
or `present`. Repeat `--severity error|warning` or `--code CODE` to filter
|
||||
findings: values within a filter match any, and the two filters narrow together.
|
||||
Filters require `--details` and never change the validation outcome. Detailed
|
||||
output suppresses ordinary warnings associated with its native findings; other
|
||||
messages and terminal failure explanations remain visible.
|
||||
`--config` and `--overlay` preserve whether an
|
||||
empty value was explicitly supplied, so a scope callback can map those inputs to
|
||||
its own ConfigKit load policy. Help and invalid syntax do not call scope
|
||||
providers.
|
||||
|
||||
### Show effective configuration
|
||||
|
||||
`config show` writes the provider's native effective YAML for one scope. Its
|
||||
default scope is `app`; `--format yaml` is accepted and YAML is the only initial
|
||||
format. Single-scope output is passed through unchanged, without a CommandKit
|
||||
header or document marker.
|
||||
`config show` displays the provider's safe effective configuration. The default
|
||||
scope is `app`. The native inspection YAML is converted to a logical report
|
||||
value, preserving meaningful scalar types, empty collections, and redaction.
|
||||
Automatic formatting uses text for a single scalar or nonempty string list and
|
||||
YAML for structured values; `--format` selects text, YAML, or JSON.
|
||||
|
||||
```text
|
||||
example config show
|
||||
example config show --scope promptkit
|
||||
example config show --scope all
|
||||
example config show --path /server/addr --format json
|
||||
```
|
||||
|
||||
`--scope all` acquires every selected scope and checks each effective writer
|
||||
before writing output. It then emits one YAML document per scope in discovery
|
||||
order, with a `# scope: NAME` comment at each document boundary. For ordinary
|
||||
block documents the comment follows the marker. When a native opening marker
|
||||
contains inline content, the comment precedes that marker so it does not
|
||||
interrupt the native value. Existing native markers and leading comments are
|
||||
retained; documents without a marker receive one. Scope labels containing line
|
||||
control characters are quoted to keep them on one comment line. A provider
|
||||
failure leaves the output stream empty. A rendering or output failure may leave
|
||||
an aggregate prefix; `Outcome.Presentation.Output` records incomplete delivery
|
||||
and the destination or rendering error.
|
||||
`--scope all` acquires every selected scope before producing one mapping keyed
|
||||
by scope name, including when only one scope is registered. A single selected
|
||||
scope is unwrapped. A provider failure prevents report output. Conversion or
|
||||
output failures are recorded in `Outcome.Presentation.Output`.
|
||||
|
||||
For a scope that supports path-selected show, `--path POINTER` displays only
|
||||
that safe effective value. An explicitly empty pointer selects the root, and a
|
||||
present null remains a value. Missing and historical-only paths fail; path
|
||||
selection cannot be combined with `--scope all`.
|
||||
|
||||
### List configuration sources
|
||||
|
||||
`config sources` reports the source inventory captured during the selected
|
||||
scope's acquisition. It reads the source facet once and does not reload
|
||||
configuration. The default scope is `app`; `--scope all` is unsupported. Text is
|
||||
the default format, and `--format yaml` returns a structured report:
|
||||
the automatic format, and `--format yaml` or `--format json` returns a structured report.
|
||||
`--source-id ID` selects one entry by the ID from that acquisition; an unknown
|
||||
ID fails. If acquisition fails but returns a captured source inventory, the
|
||||
command reports that evidence and preserves the acquisition error. Unavailable
|
||||
inventory is reported as such.
|
||||
|
||||
```yaml
|
||||
scope: app
|
||||
@@ -401,29 +434,39 @@ Text output begins with the scope heading and prints the same source fields,
|
||||
quoting labels and paths. These fields project the selected ConfigKit source
|
||||
records; CommandKit does not reload files or rerun version checks. See the
|
||||
[ConfigKit v1.1.0 source records](https://forge.maximumdirect.net/base-layer/configkit/src/commit/191015e289d7f2b91abb9fdd9c4f2f5cf75b4de9/records.go)
|
||||
for native evidence definitions. Ckprompt v0.2.0 uses
|
||||
[ConfigKit v0.8.0](https://gitea.maximumdirect.net/eric/ConfigKit/src/commit/137769f3f18a370c68444242fb5d88e620e307e5/inspection.go).
|
||||
for native evidence definitions.
|
||||
|
||||
### Explain a configuration path
|
||||
|
||||
`config explain --path POINTER` explains the effective and historical value at a
|
||||
JSON Pointer path. `--path` is required; an explicitly empty value selects the
|
||||
root. The default scope is `app`; `--format yaml` selects structured output, and
|
||||
text is the default. `--scope all` is unsupported.
|
||||
JSON Pointer path. An explicitly empty path selects the root. `config explain
|
||||
--list` discovers paths when the selected scope supports path discovery. An
|
||||
invocation with neither mode displays help; the two modes cannot be combined.
|
||||
The default scope is `app`; `--format yaml` or `--format json` selects
|
||||
structured output, and automatic output uses text. `--scope all` is unsupported.
|
||||
|
||||
```text
|
||||
example config explain --path /server/addr
|
||||
example config explain --path /profiles/team~1summary --format yaml
|
||||
example config explain --path= --format yaml
|
||||
example config explain --list --under /profiles --historical
|
||||
```
|
||||
|
||||
Listing normally includes current paths. `--historical` adds paths that only
|
||||
occurred in history; `--under POINTER` selects a subtree, and `--explicit=true`
|
||||
or `--explicit=false` filters current paths by native explicitness. Historical-only
|
||||
paths do not match an explicitness filter. These options require `--list`.
|
||||
The report contains the scope and each selected path's current presence and,
|
||||
when present, its explicitness. Path discovery does not include values or history.
|
||||
|
||||
Pointer tokens use JSON Pointer escaping: `~1` represents `/` and `~0`
|
||||
represents `~`. A malformed pointer is a usage error with status `2` and is
|
||||
rejected before acquisition. A well-formed path that is unknown in the selected
|
||||
configuration is an operational error with status `1`. Text output comes from
|
||||
the scope's native explanation writer.
|
||||
configuration is an operational error with status `1`. Text output includes
|
||||
the scope's native explanation and available field metadata. Structured output
|
||||
includes metadata when supplied by the scope.
|
||||
|
||||
YAML output uses these root fields:
|
||||
Structured output uses these root fields:
|
||||
|
||||
```yaml
|
||||
scope: app
|
||||
@@ -462,35 +505,49 @@ configuration inspection API. PromptKit owns the meaning of that native
|
||||
comparison; CommandKit uses the existing `config diff` preparation and report
|
||||
path.
|
||||
`--config` and `--overlay` select the left side. `--against-config` and
|
||||
`--against-overlay` independently override the right side. When a right-side
|
||||
field is omitted, it inherits the corresponding left value and supplied state;
|
||||
an explicit empty string overrides it and remains supplied. Equal selections are
|
||||
allowed; their equality alone does not cause CommandKit to skip the provider.
|
||||
`--against-overlay` select the right side. An omitted field keeps that side's
|
||||
ordinary application loading behavior and unsupplied state; an explicit empty
|
||||
string remains supplied. Application selectors affect the left side, while
|
||||
declared `--against-*` counterparts affect the right. Equal selections are
|
||||
allowed and do not cause CommandKit to skip the provider.
|
||||
|
||||
YAML is the only format and the default. Explicit `--format yaml` is accepted;
|
||||
`text` and other formats are usage errors. For example:
|
||||
Automatic output is YAML. The shared `--format` also accepts YAML, JSON, and
|
||||
text; text uses the same structured representation. For example:
|
||||
|
||||
```text
|
||||
example config diff --config before.yml --against-config after.yml
|
||||
example config diff --config base.yml --against-overlay candidate
|
||||
example config diff --config base.yml --overlay current --against-overlay ""
|
||||
example config diff --scope promptkit --config before.yml --against-config after.yml
|
||||
example config diff --config before.yml --against-config after.yml --details --check
|
||||
```
|
||||
|
||||
`--details` replaces the concise report with `{scope, differences}`, containing
|
||||
one entry per native difference. Each entry has `path`, `before`, `after`, and
|
||||
`hidden_changed`; each snapshot has `present`, `redacted`, and `value`. An
|
||||
absent snapshot has `present: false` and a null value, distinct from a present
|
||||
null. Empty comparisons contain `differences: []`.
|
||||
|
||||
`--check` returns status `3` when native differences exist and `0` when they do
|
||||
not. Without it, a completed comparison succeeds even when differences exist.
|
||||
Usage errors retain status `2`, and operational failures retain status `1`.
|
||||
The report is still delivered in check mode; a presentation failure remains
|
||||
separate evidence and does not replace a nonzero difference outcome.
|
||||
|
||||
For ConfigKit-backed scopes, ConfigKit compares frozen effective typed values
|
||||
after defaults and resolution; source or provenance differences alone do not
|
||||
create a change. PromptKit delegates its native comparison to ConfigKit. The
|
||||
report is one YAML document with `additions`, `changes`, and `deletions` in that
|
||||
order. Additions and changes preserve semantic paths and contain right-side
|
||||
values provided by the native comparison. Deletions contain canonical JSON
|
||||
concise report contains `additions`, `changes`, and `deletions`. Additions and changes
|
||||
preserve semantic paths and contain right-side values provided by the native
|
||||
comparison. Deletions contain canonical JSON
|
||||
Pointer paths. Explicit null is a value; it is not a deletion. Changed sequences
|
||||
and native structural replacement regions stay atomic.
|
||||
|
||||
ConfigKit pairs sensitivity across both loads. A concealed change can therefore
|
||||
appear even when its two safe snapshots are equal. For those ConfigKit-backed
|
||||
comparisons, the report omits separate redaction and hidden-change metadata: a
|
||||
comparisons, the concise report omits separate redaction and hidden-change metadata: a
|
||||
reported masked region changed, but that does not mean every member inside it
|
||||
changed. Marker-looking public strings stay ordinary YAML values. An empty
|
||||
changed. Marker-looking public strings stay ordinary strings. An empty
|
||||
comparison succeeds with this shape:
|
||||
|
||||
```yaml
|
||||
@@ -504,7 +561,7 @@ automatically applicable patch. Exceptional whole-root empty/null transitions
|
||||
can be ambiguous because the report has no root envelope; ordinary field-level
|
||||
null values and deletions retain their distinction.
|
||||
|
||||
Successful comparisons return status `0`, including empty results.
|
||||
Without `--check`, successful comparisons return status `0`, including empty results.
|
||||
Unsupported scopes and format errors are usage errors; input checks retain the
|
||||
existing usage/operational classification. Load and native comparison failures
|
||||
are operational and preserve supported error identity.
|
||||
@@ -526,76 +583,84 @@ output.
|
||||
|
||||
## PromptKit definition inspection
|
||||
|
||||
Applications can install prompt and profile inspection independently with
|
||||
`ckprompt.Command(suite)`. The `ckprompt.FromEngine(loadEngine)` adapter
|
||||
supplies these callbacks alongside native requirements discovery and the five
|
||||
catalogs. Its loader receives invocation context, configuration selection,
|
||||
typed input, and shared state. Direct suite callbacks retain their own
|
||||
implementation and lifecycle.
|
||||
|
||||
Prompt inspection uses an ID only. PromptKit returns any descriptive version
|
||||
metadata as an optional report field; there is no `--version` flag for selecting
|
||||
a prompt version. The prompt format and native selection behavior remain owned by
|
||||
[PromptKit v0.16.0](https://gitea.maximumdirect.net/eric/promptkit/src/commit/9178f3eb91c2b2138caa78e22be93c048b4bc992/docs/consumers/pkg-promptkit.md).
|
||||
Applications can install prompt, profile, and backend inspection independently
|
||||
with `ckprompt.Command(suite)`. `ckprompt.FromEngine(loadEngine)` supplies these
|
||||
callbacks alongside requirements discovery and the five catalogs. Its loader
|
||||
receives invocation context, configuration selection, typed input, and shared
|
||||
state. Direct callbacks retain their own lifecycle.
|
||||
|
||||
```text
|
||||
example promptkit show prompt customer/summary --format yaml
|
||||
example promptkit show prompt customer/summary
|
||||
example promptkit show profile customer-support --format yaml
|
||||
example promptkit show profile customer-support --format json
|
||||
example promptkit show backend local --format yaml
|
||||
```
|
||||
|
||||
Both commands require one ID operand and accept `--config`, `--overlay`, and
|
||||
`--format text|yaml` (default `text`). These commands have no built-in
|
||||
`--scope` selection; their namespace is `promptkit`.
|
||||
Each command takes one resource ID and accepts `--config` and `--overlay`.
|
||||
Reports use the native PromptKit inspection value through the shared reporting
|
||||
formats; automatic and explicit text use YAML for these structured values. Native
|
||||
JSON field names and omission rules apply. Absent optional fields are omitted;
|
||||
explicit zero values and empty collections remain present. Prompt messages are
|
||||
captured content, not rendered requests, and the prompt hash is opaque.
|
||||
|
||||
Prompt YAML preserves native input order and uses an optional `version` field.
|
||||
The key is omitted when PromptKit returns no version and is retained when the
|
||||
version is present, including an empty string. The prompt hash is an opaque
|
||||
owning-library equality value.
|
||||
Profile reports describe the selected profile before backend completion or
|
||||
request overrides. Backend reports describe configured backend fields. An
|
||||
`api_key_env` value names an environment variable; it is not a credential
|
||||
value or a claim that one is available. Neither report resolves references or
|
||||
performs a network probe. See the [PromptKit resource inspection contracts](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/resource_inspection.go).
|
||||
A missing ID is a usage error; native lookup errors and cancellation retain
|
||||
supported cause identity.
|
||||
|
||||
```yaml
|
||||
prompt_id: customer/summary
|
||||
version: "2"
|
||||
prompt_hash: opaque-value
|
||||
default_profile_id: customer-support
|
||||
inputs:
|
||||
- name: topic
|
||||
required: true
|
||||
content_type: text/plain
|
||||
description: Topic to summarize
|
||||
output_contract:
|
||||
format: json
|
||||
validation_mode: basic
|
||||
schema_path: ""
|
||||
repair_attempts: 2
|
||||
### Resource namespace selection
|
||||
|
||||
An application can enable resource namespace flags with `ckprompt.WithNamespaces`
|
||||
and provide prompt, profile, and backend defaults. Omitted flags retain those
|
||||
defaults; an explicitly empty value clears the corresponding default. Qualified
|
||||
resource IDs pass through unchanged. Without the option, the application loader
|
||||
controls the engine view and these flags are unavailable.
|
||||
|
||||
| Operation | Available namespace flags |
|
||||
| --- | --- |
|
||||
| `show prompt` | `--llm-prompt-namespace` |
|
||||
| `show profile` | `--llm-profile-namespace` |
|
||||
| `show backend` | `--llm-backend-namespace` |
|
||||
| `requirements show` | `--llm-prompt-namespace`, `--llm-profile-namespace` |
|
||||
| `requirements validate`, `show prepared`, `test` | All three, including `--llm-backend-namespace` |
|
||||
|
||||
Catalog namespace filters remain separate; configuration inspection has no
|
||||
resource namespace selectors.
|
||||
|
||||
### PromptKit convenience aliases
|
||||
|
||||
Applications that install `ckprompt.Declarations(suite)` provide scoped
|
||||
convenience spellings for the enabled PromptKit commands. Each applicable
|
||||
`--llm-NAME` flag also accepts `--NAME`; `--llm-input-text` additionally accepts
|
||||
`--llm-input` and `--input` for literal text. Use `--llm-input-file` or
|
||||
`--input-file` for a file reference. Canonical and alias spellings share the
|
||||
same binding, including their occurrence order and explicit-value semantics.
|
||||
|
||||
Applications that install `ckprompt.Command(suite)` receive the canonical
|
||||
spellings only. The aliases do not apply to application-owned commands unless
|
||||
the application installs them separately.
|
||||
|
||||
## PromptKit prepared-request preview
|
||||
|
||||
When `Suite.PrepareRequest` is present, `ckprompt.Command(suite)` installs
|
||||
`promptkit show prepared PROMPT_ID` independently of validation and other
|
||||
inspection commands. It accepts the same configuration, selector, profile,
|
||||
session, variable, input, and execution flags as
|
||||
[request validation](#concrete-request-validation):
|
||||
|
||||
```text
|
||||
example promptkit show prepared briefing --llm-input-text topic=roadmap --format json
|
||||
```
|
||||
|
||||
Profile YAML preserves the effective values reported by PromptKit, including
|
||||
zero values and nested provider parameters. `api_key_env` is only an
|
||||
environment-variable name. `api_key_required` reports a direct credential
|
||||
requirement; neither field reports credential availability. A nil provider
|
||||
parameter map is displayed as `{}`.
|
||||
|
||||
```yaml
|
||||
profile_id: customer-support
|
||||
effective_model_params:
|
||||
backend_id: local
|
||||
endpoint: https://example.invalid/v1
|
||||
model: support-model
|
||||
temperature: 0
|
||||
max_tokens: 0
|
||||
top_p: 0
|
||||
timeout_seconds: 600
|
||||
service_tier: ""
|
||||
reasoning_effort: ""
|
||||
api_key_env: ""
|
||||
extra_params: {}
|
||||
api_key_required: true
|
||||
```
|
||||
|
||||
Text uses labeled fields and includes nested `extra_params` values. A missing ID
|
||||
is a usage error. Definition selection reaches the owning inspection API and
|
||||
preserves supported error identity and cancellation.
|
||||
The command returns PromptKit's native prepared-run report using the shared
|
||||
formats; automatic and explicit text use YAML. Preparation can read resources
|
||||
and report rendered application content. It makes no model call and does not
|
||||
guarantee a subsequent execution will succeed. Application callbacks and
|
||||
loaders retain their own effects. Native preparation errors retain supported
|
||||
cause identity. The [PromptKit Prepare API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/engine.go)
|
||||
owns the prepared value and upstream preparation behavior.
|
||||
|
||||
## PromptKit requirements
|
||||
|
||||
@@ -605,8 +670,8 @@ native selection and discovery rules:
|
||||
|
||||
```text
|
||||
example promptkit requirements show briefing --campaign spring
|
||||
example promptkit requirements show briefing --profile editorial --var mode=full
|
||||
example promptkit requirements show briefing --session-id session-42 --var note= --format yaml
|
||||
example promptkit requirements show briefing --llm-profile editorial --llm-var mode=full
|
||||
example promptkit requirements show briefing --llm-session-id session-42 --llm-var note= --format yaml
|
||||
```
|
||||
|
||||
The command accepts:
|
||||
@@ -616,41 +681,42 @@ The command accepts:
|
||||
| `--config` | path string | omitted | Select the configuration input; explicit presence is retained. |
|
||||
| `--overlay` | path string | omitted | Select one overlay; explicit presence is retained. Repeated occurrences use the last value. |
|
||||
| Suite selectors | application-defined | per selector | The flags captured from `Suite.Selectors`. |
|
||||
| `--profile` | string | empty | Pass the profile ID to PromptKit; empty uses its native selection rule. |
|
||||
| `--session-id` | string | empty | Pass session context to PromptKit. |
|
||||
| `--var` | repeatable `KEY=VALUE` | none | Supply caller-variable context for native discovery. |
|
||||
| `--format` | `yaml` | `yaml` | Select the requirements report format. Other formats are usage errors for this operation. |
|
||||
| `--llm-profile` | string | empty | Pass the profile ID to PromptKit; empty uses its native selection rule. |
|
||||
| `--llm-session-id` | string | empty | Pass session context to PromptKit. |
|
||||
| `--llm-var` | repeatable `KEY=VALUE` | none | Supply caller-variable context for native discovery. |
|
||||
| `--format` | `text`, `yaml`, `json` | automatic | Select the requirements report format; automatic and text use YAML for this structured report. |
|
||||
|
||||
The `promptkit` namespace identifies the operation, so there is no built-in
|
||||
`--scope` flag. An explicitly empty profile or session value retains PromptKit's
|
||||
native empty-string meaning. Requirements inspection does not require a profile
|
||||
to be execution-ready. See the
|
||||
[PromptKit v0.16.0 consumer guide](https://gitea.maximumdirect.net/eric/promptkit/src/commit/9178f3eb91c2b2138caa78e22be93c048b4bc992/docs/consumers/pkg-promptkit.md)
|
||||
native empty-string meaning. Profile selection establishes the reported profile
|
||||
identity rather than changing the discovered requirements. An enabled profile
|
||||
namespace qualifies an explicitly supplied short profile ID; it does not rewrite
|
||||
the prompt's stored default reference. Requirements inspection does not require
|
||||
the selected profile to be execution-ready. See the
|
||||
[PromptKit v0.20.0 consumer guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/docs/consumers/pkg-promptkit.md)
|
||||
for native configuration, selection, and requirements behavior. The built-in
|
||||
flags other than `--var` are singleton bindings; when repeated, the last value
|
||||
flags other than `--llm-var` are singleton bindings; when repeated, the last value
|
||||
is used. Suite selectors retain their declared binding behavior.
|
||||
|
||||
Each `--var` occurrence must contain `=`. CommandKit splits at the first
|
||||
Each `--llm-var` occurrence must contain `=`. CommandKit splits at the first
|
||||
separator and preserves the exact key and remaining value. Empty keys and
|
||||
values, whitespace, commas, and additional `=` characters are retained. All
|
||||
occurrences are parsed; duplicate keys use the last value, while any malformed
|
||||
occurrence is a usage error even if a later assignment is valid.
|
||||
|
||||
The YAML report contains selected identities, native completeness, and input,
|
||||
The report contains selected identities, native completeness, and input,
|
||||
variable, and issue inventories. False values and empty inventories are
|
||||
retained. Input metadata preserves null versus an empty string. Variable entries
|
||||
contain `name`, `kind`, `supplied`, and `explanation`. `supplied` reports native
|
||||
exact-key presence, including an explicitly empty value, independently of
|
||||
`kind` and `complete`. Explanations and issue descriptions are upstream-owned
|
||||
human-readable summaries, not machine-readable details. The optional `version`
|
||||
key is omitted when absent and retained when supplied by PromptKit.
|
||||
human-readable summaries, not machine-readable details.
|
||||
|
||||
For a prompt with the template `{{if .mode}}{{input "notes"}}{{end}}` and no
|
||||
input declarations, omitting `mode` can produce a partial report:
|
||||
|
||||
```yaml
|
||||
prompt_id: briefing
|
||||
version: "2"
|
||||
profile_id: editorial
|
||||
complete: false
|
||||
inputs:
|
||||
@@ -688,8 +754,8 @@ prompt ID and passes a concrete request to PromptKit's native
|
||||
`Engine.ValidateRequest` preparation path:
|
||||
|
||||
```text
|
||||
example promptkit requirements validate briefing --campaign spring --input topic=topic.txt
|
||||
example promptkit requirements validate briefing --profile editorial --session-id session-42 --var mode=full --input notes=notes.txt
|
||||
example promptkit requirements validate briefing --campaign spring --llm-input-file topic=topic.txt
|
||||
example promptkit requirements validate briefing --llm-profile editorial --llm-session-id session-42 --llm-var mode=full --llm-input-file notes=notes.txt
|
||||
```
|
||||
|
||||
The command accepts:
|
||||
@@ -699,26 +765,31 @@ The command accepts:
|
||||
| `--config` | path string | omitted | Select the configuration input; explicit presence is retained. |
|
||||
| `--overlay` | path string | omitted | Select one overlay; explicit presence is retained. Repeated occurrences use the last value. |
|
||||
| Suite selectors | application-defined | per selector | The flags captured from `Suite.Selectors`. |
|
||||
| `--profile` | string | empty | Pass the profile ID to PromptKit. |
|
||||
| `--session-id` | string | empty | Pass session context to PromptKit. |
|
||||
| `--var` | repeatable `KEY=VALUE` | none | Supply caller variables for the concrete request. |
|
||||
| `--input` | repeatable `NAME=PATH` | none | Bind a file-backed PromptKit artifact. |
|
||||
| `--format` | `yaml` | `yaml` | Select the success confirmation format. Other formats are usage errors. |
|
||||
| `--llm-profile` | string | empty | Pass the profile ID to PromptKit. |
|
||||
| `--llm-session-id` | string | empty | Pass session context to PromptKit. |
|
||||
| `--llm-var` | repeatable `KEY=VALUE` | none | Supply caller variables for the concrete request. |
|
||||
| `--llm-input-text` | repeatable `NAME=TEXT` | none | Bind a literal PromptKit artifact. |
|
||||
| `--llm-input-file` | repeatable `NAME=PATH` | none | Bind a file-backed PromptKit artifact. |
|
||||
| `--format` | `text`, `yaml`, `json` | automatic | Select the success confirmation format; automatic and text use YAML for this structured report. |
|
||||
|
||||
The built-in flags other than repeatable `--var` and `--input` are singleton
|
||||
bindings; when repeated, the last value is used. Explicit empty `--config` or
|
||||
Validation also accepts the execution controls from `--llm-endpoint` through
|
||||
`--llm-extra-params` listed under [smoke testing](#promptkit-smoke-testing).
|
||||
The built-in flags other than
|
||||
`--llm-var`, `--llm-input-text`, and `--llm-input-file` are singleton bindings;
|
||||
when repeated, the last value is used. Explicit empty `--config` or
|
||||
`--overlay` values keep their supplied-presence information. The profile and
|
||||
session fields use native empty-string semantics. PromptKit owns their
|
||||
interpretation and selection errors.
|
||||
|
||||
Each `--var` and `--input` occurrence must contain `=`. CommandKit splits at the
|
||||
first separator and preserves the exact key/name and remaining value/path.
|
||||
Empty variable keys and values and empty input names and paths are passed to
|
||||
native validation. File paths become `promptkit.File(PATH)` references without
|
||||
being read, normalized, expanded, or rebased during argument binding. Duplicate
|
||||
keys or names use the last value, but every occurrence is parsed.
|
||||
Each `--llm-var`, `--llm-input-text`, and `--llm-input-file` occurrence must
|
||||
contain `=`. CommandKit splits at the first separator and preserves the exact
|
||||
key/name and remaining value. Empty names and values are passed to native
|
||||
validation. Text becomes a `promptkit.Inline` reference; file paths become
|
||||
`promptkit.File` references without being read, normalized, expanded, or
|
||||
rebased during argument binding. Every occurrence is parsed; for each input
|
||||
name the last text or file occurrence wins, regardless of form.
|
||||
|
||||
On success, the YAML confirmation contains only the requested prompt ID and
|
||||
On success, the confirmation contains only the requested prompt ID and
|
||||
`valid: true`:
|
||||
|
||||
```yaml
|
||||
@@ -733,7 +804,7 @@ configuration and credential checks. It does not make a model call or retain a
|
||||
prepared execution snapshot. A successful report describes this preparation
|
||||
invocation; it does not certify provider acceptance or guarantee later
|
||||
execution. See PromptKit's
|
||||
[`Engine.ValidateRequest` API](https://gitea.maximumdirect.net/eric/promptkit/src/commit/9178f3eb91c2b2138caa78e22be93c048b4bc992/engine.go).
|
||||
[`Engine.ValidateRequest` API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/engine.go).
|
||||
|
||||
Builder, engine-loading, and native validation errors use the operational path
|
||||
(status `1`) with supported error identity and acquired diagnostics retained.
|
||||
@@ -756,8 +827,10 @@ example promptkit list collections
|
||||
```
|
||||
|
||||
All catalogs accept `--config`, `--overlay`, applicable flags from
|
||||
`Suite.Selectors`, and `--format yaml` (the default). Other formats are usage
|
||||
errors. Prompt, profile, and backend listings accept namespace selection:
|
||||
`Suite.Selectors`, and the shared `--format` flag. Automatic output uses text
|
||||
for nonempty string lists and YAML for other inventories; explicit `text` uses
|
||||
the same rendering for structured inventories. Prompt, profile, and backend
|
||||
listings accept namespace selection:
|
||||
|
||||
| Binding | Effect |
|
||||
| --- | --- |
|
||||
@@ -773,11 +846,10 @@ before provider work. Namespace inventory accepts repeatable `--kind KIND`;
|
||||
omitting `--kind` forwards PromptKit's native default kind selection. Repeated
|
||||
values are forwarded in order. Collections have no namespace or kind filter.
|
||||
|
||||
Each operation writes one bare YAML sequence, retaining provider order and
|
||||
native identities:
|
||||
Each operation reports one bare sequence, retaining provider order and native
|
||||
identities. YAML examples follow:
|
||||
|
||||
- Prompt entries are `{id, version?}`. The optional `version` key is omitted
|
||||
when absent and retained for a present empty or nonempty value.
|
||||
- Prompt entries are `{id}`.
|
||||
- Profiles, backends, and namespaces are strings.
|
||||
- Collection entries are `{namespace, version?}`, where `version` projects
|
||||
PromptKit's optional release version.
|
||||
@@ -785,7 +857,6 @@ native identities:
|
||||
|
||||
```yaml
|
||||
- id: team/briefing
|
||||
version: "2"
|
||||
```
|
||||
|
||||
```yaml
|
||||
@@ -796,7 +867,7 @@ native identities:
|
||||
A catalog result is an inventory, not a readiness check or execution result.
|
||||
The owning provider controls membership and order. Namespace filters are passed
|
||||
to PromptKit without local membership interpretation. See the
|
||||
[PromptKit v0.16.0 consumer guide](https://gitea.maximumdirect.net/eric/promptkit/src/commit/9178f3eb91c2b2138caa78e22be93c048b4bc992/docs/consumers/pkg-promptkit.md)
|
||||
[PromptKit v0.20.0 consumer guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/docs/consumers/pkg-promptkit.md)
|
||||
for native resource and selection definitions.
|
||||
|
||||
### PromptKit smoke testing
|
||||
@@ -809,43 +880,49 @@ each aggregate call changes the seed kind before invoking it. The command
|
||||
accepts:
|
||||
|
||||
```text
|
||||
example promptkit test text_inference --campaign spring --prompt briefing --profile spring
|
||||
example promptkit test all --campaign spring --prompt briefing --profile spring
|
||||
example promptkit test authentication --backend local
|
||||
example promptkit test text_inference --campaign spring --llm-prompt briefing --llm-profile spring
|
||||
example promptkit test all --campaign spring --llm-prompt briefing --llm-profile spring
|
||||
example promptkit test authentication --llm-backend local
|
||||
```
|
||||
|
||||
| Flag | Values | Default | Meaning |
|
||||
| --- | --- | --- | --- |
|
||||
| `--config`, `--overlay` | path strings | omitted | Select PromptKit configuration; supplied presence is retained. |
|
||||
| Suite selectors | application-defined | per selector | Captured flags from `Suite.Selectors`. |
|
||||
| `--backend` | string | empty | Native backend ID. |
|
||||
| `--prompt` | string | empty | Native prompt ID. |
|
||||
| `--profile` | string | empty | Native profile ID. |
|
||||
| `--endpoint` | string | omitted | Override the execution endpoint. |
|
||||
| `--model` | string | omitted | Override the execution model. |
|
||||
| `--temperature` | float | omitted | Override execution temperature. |
|
||||
| `--max-tokens` | integer | omitted | Override execution maximum tokens. |
|
||||
| `--top-p` | float | omitted | Override execution top-p. |
|
||||
| `--timeout-seconds` | integer | omitted | Override the execution timeout. |
|
||||
| `--service-tier` | string | omitted | Override the execution service tier. |
|
||||
| `--reasoning-effort` | string | omitted | Override execution reasoning effort. |
|
||||
| `--api-key-env` | string | omitted | Supply an API-key environment-variable name to native configuration. |
|
||||
| `--transient-retries` | integer | omitted | Set the native inference transient retry count. |
|
||||
| `--format` | `yaml` | `yaml` | Select the report format. Other formats are usage errors. |
|
||||
| `--llm-backend` | string | empty | Native backend ID. |
|
||||
| `--llm-prompt` | string | empty | Native prompt ID. |
|
||||
| `--llm-profile` | string | empty | Native profile ID. |
|
||||
| `--llm-endpoint` | string | omitted | Override the execution endpoint. |
|
||||
| `--llm-model` | string | omitted | Override the execution model. |
|
||||
| `--llm-temperature` | float | omitted | Override execution temperature. |
|
||||
| `--llm-max-tokens` | integer | omitted | Override execution maximum tokens. |
|
||||
| `--llm-top-p` | float | omitted | Override execution top-p. |
|
||||
| `--llm-timeout-seconds` | integer | omitted | Override the execution timeout. |
|
||||
| `--llm-service-tier` | string | omitted | Override the execution service tier. |
|
||||
| `--llm-reasoning-effort` | string | omitted | Override execution reasoning effort. |
|
||||
| `--llm-api-key-env` | string | omitted | Supply an API-key environment-variable name to native configuration. |
|
||||
| `--llm-transient-retries` | integer | omitted | Set the native inference transient retry count. |
|
||||
| `--llm-extra-params` | JSON object | omitted | Supply provider parameters as a whole map. |
|
||||
| `--format` | `text`, `yaml`, `json` | automatic | Select the report format; automatic and text use YAML for these structured reports. |
|
||||
|
||||
The execution flags populate PromptKit's native execution override. The
|
||||
`--api-key-env` value is a variable name, not a credential value. Application
|
||||
selectors, loader policy, credentials, and client wiring remain application
|
||||
`--llm-api-key-env` value is a variable name, not a credential value. The
|
||||
extra-parameters flag accepts one JSON object, including an empty object;
|
||||
PromptKit owns its native replacement semantics and validation. Integer JSON
|
||||
numbers use signed or unsigned 64-bit integers where representable; decimal
|
||||
and exponent numbers use floating point.
|
||||
|
||||
Application selectors, loader policy, credentials, and client wiring remain application
|
||||
owned. The `WithSmokeTesting` helper accepts an optional typed builder. A nil
|
||||
builder forwards the seed; a supplied builder's complete native request is
|
||||
authoritative. The helper retains a native report when PromptKit returns both a
|
||||
report and an error.
|
||||
|
||||
A single report projects the native smoke report into YAML. It preserves native
|
||||
A single report projects the native smoke report. It preserves native
|
||||
false, unknown/null, and incomplete values and does not add a readiness score.
|
||||
The report includes `kind`, `supported`, `applicable`, `completed`, `reason`,
|
||||
`target`, `facts`, `timing`, `attempts`, `usage`, and `failure`. Its target
|
||||
contains selected IDs, optional `version`, selection source, endpoint, effective
|
||||
contains selected IDs, selection source, endpoint, effective
|
||||
settings, and settings-presence flags. Attempt entries retain their own facts,
|
||||
timing, failure, and token-usage evidence. Durations use Go duration strings;
|
||||
token counts preserve `value`, `known`, and `complete`.
|
||||
@@ -859,14 +936,14 @@ applicable: null
|
||||
completed: true
|
||||
reason: http_diagnostics_unavailable
|
||||
target:
|
||||
backend_id: ""
|
||||
backend_id: local
|
||||
profile_id: spring
|
||||
prompt_id: briefing
|
||||
version: "1"
|
||||
default_source_backend_id: ""
|
||||
selection_source: profile
|
||||
endpoint: https://example.invalid/v1
|
||||
effective_settings:
|
||||
backend_id: local
|
||||
endpoint: https://example.invalid/v1
|
||||
model: spring-model
|
||||
temperature: 0
|
||||
@@ -911,7 +988,7 @@ usage:
|
||||
failure: ""
|
||||
```
|
||||
|
||||
Aggregate output is one YAML mapping with ordered `tests` entries. Each entry
|
||||
Aggregate output is one mapping with ordered `tests` entries. Each entry
|
||||
has selected `kind`, nullable `report`, and optional `error` text. The inner
|
||||
report keeps its native `kind`. This cancellation example shows two attempted
|
||||
operations with no reports; later kinds are absent because cancellation stops
|
||||
@@ -939,9 +1016,9 @@ operation causes. Syntax, operand, unsupported format, and conflicting
|
||||
namespace selection are usage status `2`.
|
||||
|
||||
Native configuration, selection, and diagnostic meanings remain owned by
|
||||
PromptKit. See the [v0.16.0 consumer guide](https://gitea.maximumdirect.net/eric/promptkit/src/commit/9178f3eb91c2b2138caa78e22be93c048b4bc992/docs/consumers/pkg-promptkit.md),
|
||||
[smoke API](https://gitea.maximumdirect.net/eric/promptkit/src/commit/9178f3eb91c2b2138caa78e22be93c048b4bc992/smoke_diagnostics.go),
|
||||
and [engine API](https://gitea.maximumdirect.net/eric/promptkit/src/commit/9178f3eb91c2b2138caa78e22be93c048b4bc992/engine.go).
|
||||
PromptKit. See the [v0.20.0 consumer guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/docs/consumers/pkg-promptkit.md),
|
||||
[smoke API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/smoke_diagnostics.go),
|
||||
and [engine API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/engine.go).
|
||||
|
||||
## Outcome status
|
||||
|
||||
|
||||
@@ -16,14 +16,20 @@ installed at the application root, not as group children.
|
||||
| `go.maximumdirect.net/ckprompt` | The application wants PromptKit engine configuration/comparison, five catalogs, named inspection, requirements discovery, request validation, or native smoke testing. |
|
||||
|
||||
The published matched releases are core v0.3.0, ckconfig v0.2.0, and ckprompt v0.2.0.
|
||||
The local ckconfig v0.3.0 candidate uses ConfigKit v1.1.0 and does not compose
|
||||
The published ckconfig v0.3.0 uses ConfigKit v1.1.0 and does not compose
|
||||
with ckprompt v0.2.0, which retains ckconfig v0.2.0 and ConfigKit v0.8.0.
|
||||
Update application imports and dependency versions together; old and new core
|
||||
paths have distinct Go type identities. Install core with
|
||||
Install core with
|
||||
`go get go.maximumdirect.net/commandkit@v0.3.0` and either integration with
|
||||
`go get go.maximumdirect.net/ckconfig@v0.2.0` or
|
||||
`go get go.maximumdirect.net/ckprompt@v0.2.0`.
|
||||
|
||||
The current ckprompt source targets ckconfig v0.3.0, ConfigKit v1.1.0, and
|
||||
PromptKit v0.20.0 using their `go.maximumdirect.net` identities. Its v0.3.0
|
||||
release is a candidate, not a published release. A Go 1.27.0 workspace may
|
||||
compose all three local modules. The current integration source uses APIs that
|
||||
require the upcoming core and ckconfig releases; independent validation follows
|
||||
their publication and dependency alignment.
|
||||
|
||||
The two integrations are independent optional imports. `ckprompt` uses the
|
||||
public scope and error contracts from `ckconfig`; importing it does not add the
|
||||
`config` family. An application that wants both families passes both returned
|
||||
@@ -32,8 +38,8 @@ core-only, ConfigKit-only, and composed applications.
|
||||
|
||||
## Go compatibility
|
||||
|
||||
Core and ckprompt declare a consumer minimum of Go 1.26.0; the ckconfig
|
||||
v0.3.0 candidate requires Go 1.27.0. The root module also
|
||||
Core declares a consumer minimum of Go 1.26.0; both current integration
|
||||
modules require Go 1.27.0. The root module also
|
||||
selects ReleaseKit v0.9.0 (`go.maximumdirect.net/releasekit`) as a Go tool, which
|
||||
makes that tool's module graph part of the root consumer module requirements
|
||||
even though production packages do not import ReleaseKit. The
|
||||
@@ -108,7 +114,7 @@ static choices or is a filesystem path:
|
||||
|
||||
```go
|
||||
commandkit.FlagMeta{
|
||||
Name: "format",
|
||||
Name: "view",
|
||||
Completion: commandkit.CompleteChoices(
|
||||
commandkit.CompletionChoice{Value: "text", Description: "Readable text"},
|
||||
commandkit.CompletionChoice{Value: "yaml", Description: "YAML output"},
|
||||
@@ -129,12 +135,20 @@ installation alongside aliases and integration commands.
|
||||
## Invocation reporting
|
||||
|
||||
`Invocation.Reporter()` supplies the reporter for the current handler. Use
|
||||
`Output()` or `RenderOutput()` for substantive results; use `Warn`, `Info`,
|
||||
`Report()` for formatted substantive values and optional text templates;
|
||||
use `Output()` or `RenderOutput()` for deliberate raw output. Use `Warn`, `Info`,
|
||||
`Progress`, and `Debug` for categorized messages. Queue a summary with
|
||||
`AtEnd().Info` when it belongs after the handler returns. The
|
||||
[CLI reference](../cli.md#reporting) owns flag grammar, visibility, prefixes,
|
||||
and status behavior.
|
||||
|
||||
Reports use JSON serialization to establish the common value representation
|
||||
for YAML and JSON. A text template receives the original value; without one,
|
||||
text uses readable scalar or string-list output and YAML for structured values.
|
||||
The CLI's shared format selection and the writer-level `RenderReport` use the
|
||||
same rules. Use `DecodeYAMLReport` only for safe upstream inspection YAML that
|
||||
must become a report value; ordinary strings are not parsed as YAML.
|
||||
|
||||
Return terminal text with `Failure(message, details...)`, `Usage(message,
|
||||
details...)`, or `WithExplanation` on a domain outcome. Attach an optional Go
|
||||
error separately with `WithCause`. A cause is preserved for inspection, but it
|
||||
@@ -160,15 +174,6 @@ invocation are safe concurrently, but concurrent submission order is not
|
||||
specified. The caller owns the writers passed to `Execute`; CommandKit does not
|
||||
close them.
|
||||
|
||||
### Migrating from the previous reporting API
|
||||
|
||||
| Previous API | Current API |
|
||||
| --- | --- |
|
||||
| `invocation.Streams.Out` / `.Err` | `invocation.Reporter().Output()` and categorized reporter methods. `Streams` remains the argument to `App.Execute`. |
|
||||
| `Failure(err)` / `Usage(err)` | `Failure("operator-facing explanation").WithCause(err)` / `Usage("usage explanation").WithCause(err)`. Choose the explanation deliberately; the cause alone is not printed. |
|
||||
| `Outcome.Diagnostics` or terminal `SeverityError` | Submit independent messages through reporter methods. Put failure context in `Explanation`; provider `Acquired.Diagnostics` remains passive data for the owning integration to submit. |
|
||||
| `ReportIncomplete`, `DiagnosticDelivery`, or `DeliveryError` | Inspect `Outcome.Presentation.Output` and `.Diagnostics`, including each `DeliveryResult.State`, `RenderError`, and `WriteError`. |
|
||||
|
||||
## Application-owned aliases
|
||||
|
||||
Pass commands and aliases together as declarations. Integration factories can
|
||||
@@ -230,8 +235,10 @@ Use `ckconfig.Command(ckconfig.Suite[I, S]{...})` when the application needs
|
||||
multiple named scopes, selector flags, scope-aware input checks, or shared
|
||||
acquisition state or a custom comparison provider. A declared `Diff` capability
|
||||
uses `Scope.Compare`; `ckconfig.FromConfigKit` and `AppCommand` provide the
|
||||
ConfigKit-backed implementation. Each comparison side gets its own initialized
|
||||
and checked input, while state is shared by the invocation. Factory results
|
||||
ConfigKit-backed implementation. `Selector.AgainstName` opts a selector into an
|
||||
independent right-side flag. Each comparison side gets its own initialized and
|
||||
checked input, with only its supplied selectors applied; state is shared by the
|
||||
invocation. Factory results
|
||||
remain caller-owned, so separate initialization calls do not guarantee distinct
|
||||
objects. See
|
||||
[ckconfig.Suite's GoDoc](../../integrations/ckconfig/contracts.go) for factory
|
||||
@@ -239,10 +246,17 @@ timing, omitted-factory zero values (including nil pointers), and ownership.
|
||||
The application owns the state type and what it caches. `ckconfig.FromConfigKit`
|
||||
adapts a typed ConfigKit loader without calling it during construction.
|
||||
|
||||
The `config` family provides scope discovery, validation, native effective YAML,
|
||||
The `config` family provides scope discovery, validation, safe effective configuration display,
|
||||
source inventory, path explanation, and ConfigKit-backed comparison for the
|
||||
capabilities declared by its scopes. The [CLI reference](../cli.md#configuration-scopes)
|
||||
owns operator syntax and report details.
|
||||
owns operator syntax and report details. `Scope.Features` declares optional modes; acquired
|
||||
`View.Metadata` and `View.Findings` carry native path metadata and diagnostic
|
||||
records when available. `Findings.Messages` contains presentations associated
|
||||
with those records, while `Acquired.Diagnostics` carries independent messages.
|
||||
Set `Scope.Features.Overrides` only when the loader passes
|
||||
`Selection.Overrides` to ConfigKit as part of its normal load. The integration
|
||||
parses CLI records but cannot add them to an already-loaded result. The
|
||||
[CLI reference](../cli.md#configuration-scopes) describes the operator syntax.
|
||||
|
||||
## PromptKit configuration, definitions, and requirements
|
||||
|
||||
@@ -250,20 +264,25 @@ owns operator syntax and report details.
|
||||
engine's captured configuration. Add that scope to a `ckconfig.Suite` to expose
|
||||
it under `config` with validate/show/sources/explain and native diff operations;
|
||||
it does not install PromptKit catalog, definition, or requirements commands.
|
||||
Its override feature is disabled because the released PromptKit configuration
|
||||
loader does not accept ConfigKit override records.
|
||||
|
||||
`ckprompt.FromEngine(loadEngine)` supplies eight callbacks: prompt, profile,
|
||||
backend, namespace, and collection catalogs; named prompt and profile
|
||||
inspection; and native requirements discovery. Concrete request validation and
|
||||
smoke testing are separate capabilities, added explicitly with
|
||||
`ckprompt.WithRequestValidation` and `ckprompt.WithSmokeTesting`. The suite has
|
||||
ten independently optional callbacks in total. `ckprompt.Command(suite)` creates
|
||||
only operations whose callbacks are present; discovery, validation, and smoke
|
||||
testing can be installed independently. A composed suite can enable both
|
||||
additional operations:
|
||||
`ckprompt.FromEngine(loadEngine)` supplies nine callbacks: prompt, profile,
|
||||
backend, namespace, and collection catalogs; named prompt, profile, and backend
|
||||
inspection; and native requirements discovery. Concrete request validation,
|
||||
prepared-request preview, and smoke testing are separate capabilities, added
|
||||
with `ckprompt.WithRequestValidation`, `ckprompt.WithRequestPreparation`, and
|
||||
`ckprompt.WithSmokeTesting`. The suite has twelve independently optional
|
||||
callbacks in total. `ckprompt.Command(suite)` creates only operations whose
|
||||
callbacks are present, with canonical flags. `ckprompt.Declarations(suite)`
|
||||
returns the command and its scoped convenience aliases for installation with
|
||||
other declarations. These capabilities can be installed independently. A
|
||||
composed suite can enable the additional operations:
|
||||
|
||||
```go
|
||||
suite := ckprompt.FromEngine(loadEngine)
|
||||
suite = ckprompt.WithRequestValidation(suite, loadEngine, buildRequest)
|
||||
suite = ckprompt.WithRequestPreparation(suite, loadEngine, nil)
|
||||
suite = ckprompt.WithSmokeTesting(suite, loadEngine, nil)
|
||||
suite.NewInput = newInput
|
||||
suite.NewState = newState
|
||||
@@ -293,7 +312,7 @@ absent, so explicitly supplied empty values stay meaningful. Applications that
|
||||
validate and then execute a request are encouraged to share their request
|
||||
construction logic between those paths.
|
||||
|
||||
The eight catalog and inspection callbacks and the two explicit additions are
|
||||
The catalog and inspection callbacks and the explicit additions are
|
||||
independently optional. For catalogs without named or requirements inspection,
|
||||
narrow the suite before command capture:
|
||||
|
||||
@@ -301,11 +320,12 @@ narrow the suite before command capture:
|
||||
definitions := ckprompt.FromEngine(loadEngine)
|
||||
definitions.InspectPrompt = nil
|
||||
definitions.InspectProfile = nil
|
||||
definitions.InspectBackend = nil
|
||||
definitions.InspectRequirements = nil
|
||||
definitionCommand := ckprompt.Command(definitions)
|
||||
```
|
||||
|
||||
Each selected inspection, requirements, validation, smoke, or catalog operation
|
||||
Each selected inspection, requirements, validation, preparation, smoke, or catalog operation
|
||||
prepares one input, applies its captured selectors, checks that input, and
|
||||
initializes one state value when those steps are reached. The bundled validation
|
||||
adapter delegates concrete request preparation to PromptKit and carries its
|
||||
@@ -318,6 +338,24 @@ and state. `FromEngine` uses PromptKit's public listing and inspection methods,
|
||||
including `Engine.InspectRequirements`; validation must be opted into separately
|
||||
and uses `Engine.ValidateRequest`.
|
||||
|
||||
`ckprompt.WithRequestPreparation` adds a separate callback backed by
|
||||
`Engine.Prepare`. Its optional builder receives the seeded request and returns
|
||||
the complete request to prepare. The resulting native report can contain
|
||||
rendered application content. See the [CLI reference](../cli.md#promptkit-prepared-request-preview)
|
||||
for operator behavior.
|
||||
|
||||
Application-owned commands can use `ckprompt.NewExecutionFlags`,
|
||||
`ckprompt.NewResourceFlags`, and `ckprompt.NewPromptInputFlags` to bind the
|
||||
same canonical request flags into their own input types. Each collection exposes
|
||||
individual handles and an `All` method, so a command can choose its applicable
|
||||
subset. The application decides how to apply the resulting values to its request.
|
||||
|
||||
`ckprompt.WithNamespaces` enables standard resource namespace selection from
|
||||
application-supplied defaults. Loaders used with this option should leave view
|
||||
selection to the adapter. Without it, a loader can supply its own engine view.
|
||||
Direct callbacks receive the composed selection in their request. The
|
||||
[CLI reference](../cli.md#resource-namespace-selection) lists applicable flags.
|
||||
|
||||
Catalog, named definition inspection, and requirements discovery do not render
|
||||
messages or load request artifacts. Concrete request validation follows native
|
||||
PromptKit preparation, which can resolve prompt/profile resources, load
|
||||
@@ -338,6 +376,28 @@ combines app and PromptKit config scopes, comparison and catalogs, named and
|
||||
requirements inspection, request validation, smoke testing, and an
|
||||
application-owned `session restore` command.
|
||||
|
||||
### Namespace views
|
||||
|
||||
An application can return a scoped PromptKit view from its own engine loader:
|
||||
|
||||
```go
|
||||
func loadScopedEngine(ctx context.Context, selection ckconfig.Selection, input Input, state State) (*promptkit.Engine, error) {
|
||||
engine, err := loadEngine(ctx, selection, input, state)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return engine.WithNamespaces(promptkit.Namespaces{
|
||||
Prompt: "editorial", Profile: "team", Backend: "providers",
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
These are independent defaults for unqualified caller-supplied prompt, profile,
|
||||
and backend names; qualified IDs pass through. Stored references and configuration
|
||||
inspection are unchanged, while namespace and collection inventories remain global.
|
||||
Catalog `--namespace` filters are separate from these defaults. See the released
|
||||
[namespace API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/namespaces.go).
|
||||
|
||||
## Outcomes and ownership
|
||||
|
||||
Core classifies usage and operational failures while preserving application
|
||||
@@ -350,24 +410,8 @@ signal handling, and exit mapping; `Execute` never exits the process.
|
||||
Go declarations and GoDoc own exact exported contracts. ConfigKit owns
|
||||
configuration decoding, validation, and provenance. PromptKit owns prompt
|
||||
formats, profile resolution, and inspection details. See the
|
||||
[ConfigKit v0.8.0 inspection API for ckprompt v0.2.0](https://gitea.maximumdirect.net/eric/ConfigKit/src/commit/137769f3f18a370c68444242fb5d88e620e307e5/inspection.go),
|
||||
[PromptKit engine methods](https://gitea.maximumdirect.net/eric/promptkit/src/commit/9178f3eb91c2b2138caa78e22be93c048b4bc992/engine.go),
|
||||
[configuration inspection](https://gitea.maximumdirect.net/eric/promptkit/src/commit/9178f3eb91c2b2138caa78e22be93c048b4bc992/configuration_inspection.go),
|
||||
[smoke diagnostics](https://gitea.maximumdirect.net/eric/promptkit/src/commit/9178f3eb91c2b2138caa78e22be93c048b4bc992/smoke_diagnostics.go),
|
||||
and [PromptKit v0.16.0 consumer guidance](https://gitea.maximumdirect.net/eric/promptkit/src/commit/9178f3eb91c2b2138caa78e22be93c048b4bc992/docs/consumers/pkg-promptkit.md).
|
||||
|
||||
## ConfigKit v1.1 migration
|
||||
|
||||
The ckconfig v0.3.0 candidate uses `go.maximumdirect.net/configkit v1.1.0`
|
||||
and Go 1.27.0. Consumers must migrate ConfigKit imports and values passed to
|
||||
ckconfig: the old and new package paths have distinct type identities. Source
|
||||
reports rename `destination_unresolved` to `destination_is_fallback` and
|
||||
`version_check` to `version_evidence`, and add `empty_import_selections`.
|
||||
|
||||
The upstream [v0.9 migration notes](https://forge.maximumdirect.net/base-layer/configkit/src/commit/191015e289d7f2b91abb9fdd9c4f2f5cf75b4de9/docs/releases/v0.9.0.md),
|
||||
[v0.10 notes](https://forge.maximumdirect.net/base-layer/configkit/src/commit/191015e289d7f2b91abb9fdd9c4f2f5cf75b4de9/docs/releases/v0.10.0.md),
|
||||
[v1.0 migration notes](https://forge.maximumdirect.net/base-layer/configkit/src/commit/191015e289d7f2b91abb9fdd9c4f2f5cf75b4de9/docs/releases/v1.0.0.md),
|
||||
and [v1.1 notes](https://forge.maximumdirect.net/base-layer/configkit/src/commit/191015e289d7f2b91abb9fdd9c4f2f5cf75b4de9/docs/releases/v1.1.0.md)
|
||||
cover source-root `configkit` controls becoming `config`, import requiredness
|
||||
and defaults, collection registration and operations, removed APIs, and CLI
|
||||
assignment order.
|
||||
[ConfigKit v1.1.0 source records](https://forge.maximumdirect.net/base-layer/configkit/src/commit/191015e289d7f2b91abb9fdd9c4f2f5cf75b4de9/records.go),
|
||||
[PromptKit engine methods](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/engine.go),
|
||||
[configuration inspection](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/configuration_inspection.go),
|
||||
[smoke diagnostics](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/smoke_diagnostics.go),
|
||||
and [PromptKit v0.20.0 consumer guidance](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/docs/consumers/pkg-promptkit.md).
|
||||
|
||||
@@ -15,7 +15,7 @@ canonical documentation owners.
|
||||
For application-owned aliases, use the
|
||||
[CLI reference](cli.md#application-owned-aliases),
|
||||
[Go declarations and GoDoc](../command.go), and
|
||||
[ADR 0013](adr/0013-application-alias-routing.md). Keep unfinished work and
|
||||
[ADR 0005](adr/0005-application-alias-routing.md). Keep unfinished work and
|
||||
capability proposals in [future work](roadmap/future.md).
|
||||
|
||||
## Initial orientation
|
||||
@@ -24,7 +24,7 @@ capability proposals in [future work](roadmap/future.md).
|
||||
2. Read the [agent policy](policy/agents.md) and select other applicable policies
|
||||
using the guide below.
|
||||
3. Read the owning roadmap for proposals and implementation status, and the
|
||||
applicable ADR for accepted decisions and rationale.
|
||||
applicable [ADR](adr/README.md) for accepted decisions and rationale.
|
||||
4. Inspect implementation and relevant consumer contracts when they exist.
|
||||
|
||||
## Policy Reading Guide
|
||||
@@ -54,12 +54,12 @@ capability proposals in [future work](roadmap/future.md).
|
||||
| Task | Read |
|
||||
| --- | --- |
|
||||
| Implemented CLI behavior | [CLI reference](cli.md) |
|
||||
| Invocation reporting | [CLI reporting contract](cli.md#reporting), [consumer guide](consumers/guide.md#invocation-reporting), core GoDoc, and [ADR 0014](adr/0014-invocation-reporting.md) |
|
||||
| Application-owned aliases | [CLI reference](cli.md#application-owned-aliases), [Go declarations and GoDoc](../command.go), [consumer guide](consumers/guide.md#application-owned-aliases), and [ADR 0013](adr/0013-application-alias-routing.md) |
|
||||
| Invocation reporting | [CLI reporting contract](cli.md#reporting), [consumer guide](consumers/guide.md#invocation-reporting), core GoDoc, and [ADR 0006](adr/0006-invocation-reporting.md) |
|
||||
| Application-owned aliases | [CLI reference](cli.md#application-owned-aliases), [Go declarations and GoDoc](../command.go), [consumer guide](consumers/guide.md#application-owned-aliases), and [ADR 0005](adr/0005-application-alias-routing.md) |
|
||||
| Public API usage and standard-suite wiring | [Consumer guide](consumers/guide.md), [ckconfig package](../integrations/ckconfig/doc.go), [ckprompt package](../integrations/ckprompt/doc.go), and applicable ADRs |
|
||||
| Dispatcher, registration, or typed inputs | [Command declarations](../command.go), [bindings](../binding.go), [invocation](../execute.go), and [ADR 0001](adr/0001-command-dispatch-and-inputs.md), refined by [ADR 0011](adr/0011-captured-declarations-and-installation.md) |
|
||||
| Backend integration | [Internal overview](internal/overview.md), [adapter implementation](../internal/cobra/parse.go), and [ADR 0002](adr/0002-cobra-backend.md) |
|
||||
| Public facade or adapter boundaries | [Internal overview](internal/overview.md), [ADR 0003](adr/0003-public-facade.md) as scoped by [ADR 0010](adr/0010-optional-integration-modules.md), and the architecture policy |
|
||||
| Dispatcher, registration, or typed inputs | [Command declarations](../command.go), [bindings](../binding.go), [invocation](../execute.go), and [ADR 0001](adr/0001-command-dispatch-and-inputs.md) |
|
||||
| Backend integration | [Internal overview](internal/overview.md), [adapter implementation](../internal/cobra/parse.go), and [ADR 0002](adr/0002-public-facade-and-cli-backend.md) |
|
||||
| Public facade or adapter boundaries | [Internal overview](internal/overview.md), [ADR 0002](adr/0002-public-facade-and-cli-backend.md), [ADR 0004](adr/0004-optional-integration-modules.md), and the architecture policy |
|
||||
| Module ownership and public contracts | [Consumer guide](consumers/guide.md), [internal overview](internal/overview.md), [core GoDoc](../doc.go), [ckconfig GoDoc](../integrations/ckconfig/doc.go), [ckprompt GoDoc](../integrations/ckprompt/doc.go), and applicable ADRs |
|
||||
| Unfinished work and capability proposals | [Future work](roadmap/future.md) |
|
||||
| Completed planning and implementation history | [Completed dependency upgrades, PromptKit validation, discovery, smoke testing, and remediation](https://gitea.maximumdirect.net/eric/CommandKit/src/commit/a6278a6d9f940948ec7745955d745523aaff0734/docs/roadmap), [earlier ConfigKit and PromptKit adoption and remediation](https://gitea.maximumdirect.net/eric/CommandKit/src/commit/8a82620dfcd34c0ae56bbecb0d014eb49786bc92/docs/roadmap), [earlier retired records](https://gitea.maximumdirect.net/eric/CommandKit/src/commit/6bc37e7ba64ca0920b4d0cc77039a18d4006b24e/docs/roadmap), and [completed module implementation and remediation](https://gitea.maximumdirect.net/eric/CommandKit/src/commit/bb2528532b78d30e52f5082e491a5e1fd9b0fb99/docs/roadmap) in Git history |
|
||||
@@ -72,7 +72,8 @@ Read all applicable rows for cross-cutting work. Go declarations and GoDoc own
|
||||
current exported contracts; the CLI reference owns operator behavior. The
|
||||
[maintainer release procedure](release.md) owns current release operations.
|
||||
Completed roadmaps and implementation evidence remain available in Git history,
|
||||
including [ConfigKit adoption, reporting, release-tooling, and remediation records](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/260256d722f52bc947103d078cb67a129f4cc9f1/docs/roadmap),
|
||||
including [PromptKit v0.18.0 adoption and implementation](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/540e2359d66d604a563df0be1c9fc961588f5b9c/docs/roadmap),
|
||||
[ConfigKit adoption, reporting, release-tooling, and remediation records](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/260256d722f52bc947103d078cb67a129f4cc9f1/docs/roadmap),
|
||||
[application-owned alias planning, implementation, and remediation](https://gitea.maximumdirect.net/eric/CommandKit/src/commit/f42aefe02d84e154855ac922173e6f367180929f/docs/roadmap)
|
||||
and [PromptKit requirements implementation and remediation](https://gitea.maximumdirect.net/eric/CommandKit/src/commit/40499a43608bf60d1104cd8ee24caf18ac0e9e66/docs/roadmap).
|
||||
These records are not assignments to restart completed work. The
|
||||
@@ -101,12 +102,18 @@ evidence, not build dependencies. Implemented contracts belong in CommandKit
|
||||
under their canonical owners.
|
||||
|
||||
The root module does not traverse nested modules. Preserve the ignored `go.work`
|
||||
and `go.work.sum`; use `GOWORK=off GOTOOLCHAIN=local` for dependency preparation,
|
||||
module suites, and examples during the ckconfig migration. Local ckprompt uses
|
||||
the old ConfigKit identity and cannot compose with migrated local ckconfig. Its
|
||||
independent suite and composed example use published ckconfig v0.2.0; restore
|
||||
full local workspace guidance after the coordinated ckprompt migration.
|
||||
Run `go test ./...` separately from each module directory.
|
||||
and `go.work.sum`; use `GOWORK=off GOTOOLCHAIN=local` for dependency preparation
|
||||
and independent module suites once released requirements are aligned. Until then,
|
||||
the integrations require a Go 1.27.0 workspace containing all three modules.
|
||||
Run `GOWORK=off GOTOOLCHAIN=local go test ./...` separately from each module
|
||||
directory. From the repository root, a workspace containing all three modules can
|
||||
also run:
|
||||
|
||||
```sh
|
||||
GOTOOLCHAIN=local go test ./...
|
||||
GOTOOLCHAIN=local go test ./integrations/ckconfig/...
|
||||
GOTOOLCHAIN=local go test ./integrations/ckprompt/...
|
||||
```
|
||||
|
||||
Format changed Go files with `gofmt`. The
|
||||
[maintainer release procedure](release.md) owns candidate preparation and
|
||||
@@ -126,30 +133,31 @@ or publishing.
|
||||
|
||||
## Current public examples
|
||||
|
||||
The maintained consumers compile with their owning module suites and run without
|
||||
external services. The PromptKit smoke examples use local fixtures and the
|
||||
example's configured client:
|
||||
The maintained consumers run without external services using the aligned local
|
||||
workspace. The PromptKit smoke examples use local fixtures and the example's
|
||||
configured client:
|
||||
|
||||
```sh
|
||||
GOWORK=off GOTOOLCHAIN=local go run ./examples/core workspace greet --count=0 --tag=first --tag second
|
||||
(cd integrations/ckconfig/examples/simple && GOWORK=off GOTOOLCHAIN=local go run . config show)
|
||||
(cd integrations/ckconfig/examples/simple && GOWORK=off GOTOOLCHAIN=local go run . config diff --config fixtures/before.yml --against-config fixtures/after.yml)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . config validate --scope all --campaign spring --limit=0)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . config diff --scope app --config fixtures/before.yml --against-config fixtures/after.yml)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . config diff --scope promptkit --config fixtures/before.yml --against-config fixtures/after.yml --campaign spring)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . promptkit list prompts --config fixtures/before.yml --campaign spring)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . promptkit list profiles --config fixtures/after.yml --campaign autumn --format yaml)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . promptkit list backends --namespace team)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . promptkit list namespaces --kind prompt --kind profile)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . promptkit list collections)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . promptkit show prompt briefing --campaign spring --format yaml)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . promptkit requirements show briefing --campaign spring)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . promptkit requirements show briefing --campaign spring --var mode=full --format yaml)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . promptkit requirements validate briefing --campaign spring --input topic=fixtures/topic.txt)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . promptkit requirements validate briefing --campaign spring --input topic=fixtures/topic.txt --var mode=full --input notes=fixtures/notes.txt --format yaml)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . promptkit test reachability --campaign spring --prompt briefing --profile spring)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . promptkit test all --campaign spring --prompt briefing --profile spring)
|
||||
(cd integrations/ckprompt/examples/composed && GOWORK=off GOTOOLCHAIN=local go run . session restore session-42 --campaign spring)
|
||||
GOTOOLCHAIN=local go run ./examples/core workspace greet --count=0 --tag=first --tag second
|
||||
(cd integrations/ckconfig/examples/simple && GOTOOLCHAIN=local go run . config show)
|
||||
(cd integrations/ckconfig/examples/simple && GOTOOLCHAIN=local go run . config diff --config fixtures/before.yml --against-config fixtures/after.yml)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . config validate --scope all --campaign spring --limit=0)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . config diff --scope app --config fixtures/before.yml --against-config fixtures/after.yml)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . config diff --scope promptkit --config fixtures/before.yml --against-config fixtures/after.yml --campaign spring)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . promptkit list prompts --config fixtures/before.yml --campaign spring)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . promptkit list profiles --config fixtures/after.yml --campaign autumn --format yaml)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . promptkit list backends --namespace team)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . promptkit list namespaces --kind prompt --kind profile)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . promptkit list collections)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . promptkit show prompt briefing --campaign spring --format yaml)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . promptkit show prepared briefing --campaign spring --input topic=sprint --profile spring --extra-params '{"campaign":"preview"}')
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . promptkit requirements show briefing --campaign spring)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . promptkit requirements show briefing --campaign spring --var mode=full --format yaml)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . promptkit requirements validate briefing --campaign spring --input-file topic=fixtures/topic.txt)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . promptkit requirements validate briefing --campaign spring --input-file topic=fixtures/topic.txt --var mode=full --input-file notes=fixtures/notes.txt --format yaml)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . promptkit test reachability --campaign spring --prompt briefing --profile spring)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . promptkit test all --campaign spring --prompt briefing --profile spring)
|
||||
(cd integrations/ckprompt/examples/composed && GOTOOLCHAIN=local go run . session restore session-42 --campaign spring)
|
||||
```
|
||||
|
||||
The [consumer guide](consumers/guide.md) explains how their public API usage
|
||||
|
||||
@@ -14,7 +14,7 @@ The core, ckconfig, and ckprompt modules declare
|
||||
|
||||
The root facade owns captured canonical command declarations, application-owned
|
||||
routing rules, binding conversion, invocation coordination, the per-App
|
||||
registries, standard help/version commands, invocation reporting, and outcome
|
||||
registries, standard help/version commands, shared report rendering, invocation reporting, and outcome
|
||||
finalization.
|
||||
Its dependency graph has no ConfigKit or PromptKit integration dependency.
|
||||
Applications provide typed callbacks and install routing rules alongside the
|
||||
@@ -90,8 +90,9 @@ acquisitions or comparison callback.
|
||||
`integrations/ckprompt` owns PromptKit engine loading, configuration-scope
|
||||
adaptation and native comparison, plus optional prompt/profile/backend/namespace/
|
||||
collection catalogs, named inspection, native requirements discovery,
|
||||
concrete request validation, and native smoke testing. Validation and smoke
|
||||
testing delegate to PromptKit and are independently opted into a suite. Smoke
|
||||
concrete request validation, prepared-request preview, and native smoke testing.
|
||||
Validation, preview, and smoke testing delegate to PromptKit and are independently
|
||||
opted into a suite. Smoke
|
||||
operations use the application's native engine and its configured client or
|
||||
probes. The integration uses public core and ckconfig contracts plus PromptKit's
|
||||
public APIs. It does not add a configuration family when its declaration is
|
||||
|
||||
@@ -119,8 +119,9 @@ Material: `docs/policy/meta.md`, `docs/policy/agents.md`,
|
||||
`docs/policy/documentation.md`, `docs/policy/release.md`, and
|
||||
`docs/policy/oss.md`; the root `AGENTS.md` orientation after the knowledge-graph
|
||||
instructions; and the Policy Reading Guide in `docs/development.md`, adapted for
|
||||
this repository. The release policy uses baseline
|
||||
`e833faddf120c789a9b45348edaf75720de16348`; the remaining material uses baseline
|
||||
this repository. The documentation policy uses baseline
|
||||
`beb5f191470a9daef2383981a6bfd02232490ab4`; the release policy uses
|
||||
`e833faddf120c789a9b45348edaf75720de16348`; the remaining material uses
|
||||
`d84a38ebab26f048cafbe59a2246700c35d29843`.
|
||||
|
||||
Copyright (C) 2026 Eric Rakestraw
|
||||
@@ -131,12 +132,16 @@ License and notices: [CC BY-SA 4.0](licenses/CC-BY-SA-4.0.txt) |
|
||||
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/COPYRIGHT) |
|
||||
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/LICENSE) |
|
||||
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/COPYRIGHT) |
|
||||
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/LICENSE).
|
||||
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/LICENSE) |
|
||||
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/beb5f191470a9daef2383981a6bfd02232490ab4/COPYRIGHT) |
|
||||
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/beb5f191470a9daef2383981a6bfd02232490ab4/LICENSE).
|
||||
|
||||
[Source](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843).
|
||||
|
||||
[Source](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348).
|
||||
|
||||
[Source](https://gitea.maximumdirect.net/eric/policy/src/commit/beb5f191470a9daef2383981a6bfd02232490ab4).
|
||||
|
||||
## ReleaseKit
|
||||
|
||||
Selected module: `go.maximumdirect.net/releasekit` at `v0.9.0` (selected Go tool; not a runtime import).
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Base Policy Version:** 1.3
|
||||
|
||||
**Last Updated**: 2026-10-26
|
||||
**Last Updated**: 2026-11-06
|
||||
|
||||
**Upstream Source:** [architecture.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/architecture.md)
|
||||
|
||||
@@ -23,6 +23,22 @@ Exact exported contracts belong in Go declarations and GoDoc; implemented
|
||||
operator behavior belongs in the CLI reference. Do not describe planned packages
|
||||
or APIs as existing implementation.
|
||||
|
||||
## Ownership Boundaries
|
||||
|
||||
Applications and integration handlers choose the operation and report content;
|
||||
CommandKit core supplies the shared CLI mechanics. Integrated libraries retain
|
||||
ownership of their domain behavior. These boundaries govern current and planned
|
||||
capabilities; they do not imply that a planned API is implemented.
|
||||
|
||||
| Area | CommandKit Owns | CommandKit Does Not Own |
|
||||
| --- | --- | --- |
|
||||
| **CLI output — core** | Format selection, serialization, template execution, and output delivery | Choosing report content or detail level; authoring application-specific text templates |
|
||||
| **PromptKit/ConfigKit integrations** | Standard commands, flags, and report content that expose useful operator tasks through upstream public APIs | Helpers or convenience interfaces for application-internal use of upstream APIs |
|
||||
| **CLI inputs** | CLI syntax, parsing, typed bindings, presence tracking, and usage diagnostics | Application business rules or upstream domain-validation semantics |
|
||||
| **Upstream behavior** | Selecting and invoking supported capabilities, adapting their results, and preserving their meaning | Reimplementing upstream configuration resolution, prompt preparation, validation, or other domain algorithms |
|
||||
| **Outcomes and errors — core** | Carrying and presenting selected outcomes; handling CommandKit's own parsing, rendering, and delivery failures | Deciding application recovery policy or terminating the process |
|
||||
| **Application lifecycle** | Command dispatch and invocation reporting lifecycle | Application startup, engine construction, credential provisioning, signal handling, or long-lived application state |
|
||||
|
||||
## Success Criteria
|
||||
|
||||
Evaluate designs and adoption against both criteria:
|
||||
@@ -42,12 +58,29 @@ Replacing parsing and dispatch plumbing with equally repetitive registration or
|
||||
callback bookkeeping does not satisfy infrastructure reduction. Keep enough
|
||||
flexibility to express genuine application requirements within one command model.
|
||||
|
||||
## Go Types And Facilities
|
||||
|
||||
CommandKit is a Go library for Go applications. Its APIs and implementation use
|
||||
ordinary Go types, language features, and standard-library facilities. Their
|
||||
documented semantics and representational limits are accepted design constraints.
|
||||
CommandKit does not introduce substitute type systems or compatibility machinery
|
||||
merely to circumvent those limits.
|
||||
|
||||
Ordinary parsing, application-defined domain types, and necessary serialization
|
||||
adapters remain appropriate. Preserve values that the selected Go types can
|
||||
represent; accepting their limits does not justify accidental rounding or
|
||||
truncation during conversion. Keep CLI boundary conversions small and focused,
|
||||
without turning them into general-purpose type-conversion frameworks.
|
||||
|
||||
Specific numeric parsing and report serialization contracts remain separate.
|
||||
A CLI parser's selected numeric types do not establish a blanket restriction on
|
||||
application-supplied values or silently redefine their serialization contracts.
|
||||
GoDoc and CLI documentation own implemented behavior; roadmaps own pending work.
|
||||
|
||||
## Command And Application Ownership
|
||||
|
||||
[ADR 0001](../adr/0001-command-dispatch-and-inputs.md) records the selected
|
||||
CommandKit-owned dispatcher, per-instance registry, and typed-input model.
|
||||
[ADR 0011](../adr/0011-captured-declarations-and-installation.md) refines declaration
|
||||
capture, installation, optional-family ownership, and invocation input lifetimes.
|
||||
dispatcher, captured declarations, installation boundary, and typed-input model.
|
||||
|
||||
CommandKit owns dispatch, common parsing, presence tracking, help, shared syntax
|
||||
diagnostics, and the handlers and CLI contracts of its standard families.
|
||||
@@ -68,12 +101,12 @@ Applications own their executable entry points, context creation, signals,
|
||||
stream selection, runtime construction, and final process exit. CommandKit
|
||||
returns invocation outcomes and must not terminate the process. Its common
|
||||
mechanics apply to custom commands without taking ownership of their domain
|
||||
semantics or success-report formats.
|
||||
semantics or report content.
|
||||
|
||||
CommandKit's grammar applies to commands using its dispatcher and binding APIs.
|
||||
Its documentation recommends the same grammar and vocabulary for application-owned
|
||||
commands, including those outside its dispatcher, under
|
||||
[ADR 0006](../adr/0006-command-grammar.md).
|
||||
commands, including those outside its dispatcher. The
|
||||
[CLI reference](../cli.md#registered-command-syntax) owns implemented grammar.
|
||||
|
||||
Use explicit instance construction and composable command registration, not
|
||||
package-global or import-time registries. Applications and integrations supply
|
||||
@@ -126,8 +159,25 @@ application-owned.
|
||||
Use one reporting facility per invocation for command results, immediate messages,
|
||||
and deferred messages. Core owns shared visibility, formatting, delivery, and
|
||||
finalization. Applications and integrations choose their report content and
|
||||
messages; callers choose the destinations. [ADR 0014](../adr/0014-invocation-reporting.md)
|
||||
extends the outcome and delivery model in [ADR 0005](../adr/0005-invocation-outcomes.md).
|
||||
messages; callers choose the destinations.
|
||||
[ADR 0006](../adr/0006-invocation-reporting.md) records this reporting and outcome
|
||||
ownership model. Its accepted structured-report extension remains planned in the
|
||||
[adoption roadmap](../roadmap/promptkit-v0.20.0.md#shared-core-report-output-prerequisite).
|
||||
|
||||
For that shared report handoff, core owns format selection, serialization,
|
||||
template execution, and delivery. Applications and integrations select logical
|
||||
report content and detail level, and author any report-specific text templates.
|
||||
Changing format must not implicitly change that content or detail level.
|
||||
Representations and encoders are core implementation choices; commands should
|
||||
not maintain parallel rendering pipelines or a separate report tree per format.
|
||||
|
||||
Use ordinary Go report values and thin projections where upstream data needs
|
||||
adaptation. Prefer standard serialization and template facilities to a new public
|
||||
document model, tag convention, or template language. Shared rendering serves
|
||||
both invocation reporting and direct writer use, while invocation delivery keeps
|
||||
the existing visibility, outcome, and presentation-failure lifecycle. Exact
|
||||
serialization conventions, format options, and API signatures belong in the
|
||||
roadmap until implemented, then in their API and CLI contracts.
|
||||
|
||||
Applications decide how to respond to domain-specific errors. CommandKit may
|
||||
provide shared helpers for carrying, inspecting, and presenting errors while
|
||||
@@ -137,10 +187,11 @@ handles its own errors, including routing, parsing, and presentation failures.
|
||||
|
||||
Preserve application-defined domain classifications and supplied error identity.
|
||||
Report rendering and delivery failures separately from the command's explanation
|
||||
and cause, applying the outcome rules in ADR 0005 and ADR 0014. Intentionally
|
||||
suppressed output is not a delivery failure. Present terminal failure explanations
|
||||
after normal reporting finishes, avoid duplicate presentation through core's own
|
||||
paths, and retain the explanation and any supplied cause in the returned outcome.
|
||||
and cause, applying the [CLI reporting contract](../cli.md#presentation-failures).
|
||||
Intentionally suppressed output is not a delivery failure. Present terminal
|
||||
failure explanations after normal reporting finishes, avoid duplicate presentation
|
||||
through core's own paths, and retain the explanation and any supplied cause in
|
||||
the returned outcome.
|
||||
|
||||
Keep reporting state scoped to the invocation's presentation and returned outcome.
|
||||
Logging and message history remain application concerns.
|
||||
@@ -162,12 +213,14 @@ Factories need not run after a failure and remain uninvoked during construction,
|
||||
installation, help, version, and scope discovery.
|
||||
|
||||
For two-selection configuration comparison, prepare and check each side's input
|
||||
separately with its scope identity and selection, applying the same applicable
|
||||
converted selector values to both. Finish both checks before initializing shared
|
||||
state once and invoking the integration-owned pair provider under
|
||||
[ADR 0012](../adr/0012-typed-configuration-comparison-pairs.md). Required provider
|
||||
wiring follows declared capabilities; a comparison-only scope does not require
|
||||
an unrelated ordinary acquisition callback.
|
||||
separately with its scope identity and selection, applying only the selectors
|
||||
supplied for that side. Finish both checks before initializing shared
|
||||
state once and invoking the integration-owned pair provider. The
|
||||
[consumer guide](../consumers/guide.md#configkit-scopes) and linked GoDoc own the
|
||||
provider lifecycle; the [CLI reference](../cli.md#compare-configuration-selections)
|
||||
owns current selector behavior. Required provider wiring follows declared
|
||||
capabilities; a comparison-only scope does not require an unrelated ordinary
|
||||
acquisition callback.
|
||||
|
||||
Omitted input and state factories supply the respective type's zero value,
|
||||
including nil for pointers. Caller factories and callbacks retain responsibility
|
||||
@@ -187,8 +240,8 @@ composition does not create a second parser or a raw-argument handler model.
|
||||
|
||||
CommandKit keeps parsed values, collections, and presence from one invocation out
|
||||
of subsequent runs. Storage allocation and safe reuse are implementation choices;
|
||||
rebuilding backend state is the initial strategy under
|
||||
[ADR 0002](../adr/0002-cobra-backend.md). Caller-owned closures and runtime state
|
||||
the [internal overview](../internal/overview.md#internalcobra) describes the
|
||||
current backend lifecycle. Caller-owned closures and runtime state
|
||||
retain their own lifecycle. Concurrent dispatch is a separate contract.
|
||||
|
||||
Applications may interpret parsed domain values and provide domain value parsers
|
||||
@@ -197,16 +250,18 @@ Keep input declarations available without application initialization.
|
||||
|
||||
## Public Facade And Dependency Direction
|
||||
|
||||
[ADR 0010](../adr/0010-optional-integration-modules.md) scopes the root
|
||||
`commandkit` facade to the core module and selects separate optional integration
|
||||
modules with their own public package contracts. It partially supersedes
|
||||
[ADR 0003](../adr/0003-public-facade.md), whose remaining facade and internal
|
||||
adapter principles apply to the core and integrations alike.
|
||||
[ADR 0004](../adr/0004-optional-integration-modules.md) selects separate optional
|
||||
integration modules with their own public package contracts. The facade and
|
||||
backend isolation principles in
|
||||
[ADR 0002](../adr/0002-public-facade-and-cli-backend.md) apply within those module
|
||||
boundaries.
|
||||
|
||||
The core owns command declarations, registration, bindings, dispatch, help/version,
|
||||
shared syntax, diagnostics, and outcomes. Each integration owns its standard
|
||||
handlers, provider contracts, reports, adapters, and integration-specific public
|
||||
types. Dependencies point from integrations toward the core; an integration may
|
||||
shared syntax, reporting mechanics, diagnostics, and outcomes. Each integration
|
||||
owns its standard handlers, provider contracts, report content, adapters, and
|
||||
integration-specific public types. Integrations expose operator-facing CLI tasks;
|
||||
they do not provide convenience interfaces for application-internal upstream APIs.
|
||||
Dependencies point from integrations toward the core; an integration may
|
||||
depend on another integration when its responsibility requires that relationship.
|
||||
Document those dependencies. Core public signatures, implementation imports, and
|
||||
module requirements remain independent of optional integration libraries,
|
||||
@@ -241,11 +296,11 @@ without exporting private assembly or backend structures.
|
||||
|
||||
## Backend And Library Integration
|
||||
|
||||
[ADR 0002](../adr/0002-cobra-backend.md) selects Cobra with pflag as the sole
|
||||
initial backend. Their types and operations stay inside an internal adapter that
|
||||
translates CommandKit-owned definitions into backend machinery. Registry logic,
|
||||
standard handlers, and shared internal representations remain independent of
|
||||
backend-specific structures.
|
||||
[ADR 0002](../adr/0002-public-facade-and-cli-backend.md) selects Cobra with pflag
|
||||
as the sole initial backend. Their types and operations stay inside an internal
|
||||
adapter that translates CommandKit-owned definitions into backend machinery.
|
||||
Registry logic, standard handlers, and shared internal representations remain
|
||||
independent of backend-specific structures.
|
||||
|
||||
Reuse backend routing and parsing mechanisms, adapting them to selected
|
||||
CommandKit semantics. Do not replicate Cobra's entire API through renamed
|
||||
@@ -253,9 +308,9 @@ wrappers. Introduce narrow internal interfaces where actual interactions justify
|
||||
them; a public backend selection or plugin framework is not part of the design.
|
||||
|
||||
ConfigKit and PromptKit own configuration composition, provenance, inspection
|
||||
semantics, secret classification, and native rendering. Applications provide
|
||||
schemas, acquisition, domain resolution and validation, and construction of
|
||||
inspection providers. CommandKit exposes those capabilities through supported
|
||||
semantics, secret classification, and their native inspection representations.
|
||||
Applications provide schemas, acquisition, domain resolution and validation,
|
||||
and construction of inspection providers. CommandKit exposes those capabilities through supported
|
||||
upstream APIs. The public contract of the adopted library version governs their
|
||||
meaning and disclosure rules. When CommandKit adopts an upstream revision,
|
||||
changes to those semantics flow through its integration. Adaptation and
|
||||
@@ -275,15 +330,26 @@ packages or depend on adjacent checkouts.
|
||||
Use narrow integration contracts, reusing upstream public types where useful and
|
||||
introducing CommandKit-owned abstractions where they simplify integration.
|
||||
Concrete integration needs guide provider representations under
|
||||
[ADR 0009](../adr/0009-configuration-scopes.md).
|
||||
[ADR 0003](../adr/0003-configuration-scopes.md).
|
||||
|
||||
Native report writers and safe inspection data preserve owning-library semantics.
|
||||
Loading all selected views before report output is a `config show` decision under
|
||||
[ADR 0007](../adr/0007-native-yaml-reports.md); other inspection operations define
|
||||
their own output timing. Semantic comparison exposes the adopted upstream
|
||||
comparison API, carrying its results and relevant metadata through the provider
|
||||
boundary. CommandKit owns report presentation under
|
||||
[ADR 0008](../adr/0008-semantic-configuration-diff.md).
|
||||
Use upstream safe inspection data to preserve owning-library meaning and
|
||||
disclosure rules under [ADR 0004](../adr/0004-optional-integration-modules.md).
|
||||
Do not reconstruct inspection reports from mutable runtime configuration or source
|
||||
files when the upstream inspection API supplies captured, safe evidence. Explicit
|
||||
adaptation into ordinary report values must preserve the selected evidence and
|
||||
report conversion failures rather than silently changing its meaning.
|
||||
|
||||
CommandKit parses and forwards supplied CLI selections and overrides through the
|
||||
declared acquisition boundary. Upstream libraries retain path validity,
|
||||
resolution, precedence, conflict handling, and domain validation. Preserve their
|
||||
errors instead of inventing a parallel override policy or retrying with altered
|
||||
values. Application loading and application-owned overrides retain their own
|
||||
responsibilities.
|
||||
|
||||
The [CLI reference](../cli.md#show-effective-configuration) owns current report
|
||||
formats and operation-specific preparation and delivery timing. Semantic
|
||||
comparison exposes the adopted upstream comparison API and carries its evidence
|
||||
through the provider boundary; it does not introduce a CommandKit equality engine.
|
||||
|
||||
## Scope And Non-goals
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
**Base Policy Version:** 1.11
|
||||
|
||||
**Last Updated**: 2026-10-10
|
||||
**Last Updated**: 2026-11-07
|
||||
|
||||
**Upstream Source:** [documentation.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/documentation.md)
|
||||
**Upstream Source:** [documentation.md](https://gitea.maximumdirect.net/eric/policy/src/commit/beb5f191470a9daef2383981a6bfd02232490ab4/docs/policy/documentation.md)
|
||||
|
||||
## Purpose
|
||||
|
||||
@@ -86,7 +86,7 @@ secret values.
|
||||
| Inventory of implemented internal packages | `docs/internal/overview.md` | Implemented packages and components, responsibilities, and links to focused internal docs. | Normative architecture, contributor reading policy, external contracts. |
|
||||
| Behavior and architecture of internal packages | Other files under `docs/internal/` | Implementation flow, collaborators, state transitions, package-local guarantees and failures, and relevant tests. | Global architecture invariants, configuration definitions and defaults, external schemas, operator procedures. |
|
||||
| Architectural decision records | `docs/adr/` | Significant decisions, context, alternatives, rationale, consequences, and supersession history. | Current behavior reference, implementation status, task sequencing. |
|
||||
| Future work and implementation status | `docs/roadmap/` | Proposed, accepted, deferred, or rejected work; implementation status, sequencing, and task breakdowns. | Implemented behavior reference and architectural decision rationale. |
|
||||
| Future work and implementation status | `docs/roadmap/` | Proposed, accepted, or deferred work; implementation status, sequencing, and task breakdowns. | Implemented behavior reference and architectural decision rationale. |
|
||||
| Release-note history | `docs/releases/` | One checked-in summary per source release under the procedure; the note at its immutable tag is the release record. | Current commands, behavior, contracts, and compatibility definitions. |
|
||||
| Complete copyable artifacts | `examples/` | Maintained configuration, inputs, and other copyable or runnable files. | Field-by-field reference, command reference, prose explanation. |
|
||||
|
||||
@@ -147,14 +147,16 @@ mechanisms only.
|
||||
|
||||
## Architecture Decision Records
|
||||
|
||||
ADRs record durable architectural decisions: responsibility boundaries,
|
||||
ownership, significant constraints, and the reasons for choosing them. A settled
|
||||
implementation or presentation choice does not automatically belong in an ADR.
|
||||
Ask whether changing the detail would alter the architecture or represent
|
||||
reasonable evolution within it. Details that can evolve within the chosen
|
||||
architecture belong in API or CLI contracts, implementation documentation, or
|
||||
roadmaps. Describe upstream behavior as context without turning it into an
|
||||
independent project guarantee.
|
||||
ADRs record major architectural decisions, such as responsibility and ownership
|
||||
boundaries, large-scale architectural features, or significant architectural
|
||||
invariants, and the reasons for choosing them. Routine choices, implementation
|
||||
or presentation decisions, and rejected suggestions do not warrant an ADR
|
||||
unless they otherwise represent a significant architectural decision. Ask
|
||||
whether changing the detail would alter the architecture or represent reasonable
|
||||
evolution within it. Details that can evolve within the chosen architecture
|
||||
belong in API or CLI contracts, implementation documentation, or roadmaps.
|
||||
Describe upstream behavior as context without turning it into an independent
|
||||
project guarantee.
|
||||
|
||||
Use sequentially numbered ADR filenames such as
|
||||
`0001-record-architecture-decisions.md`. Follow the lightweight Nygard format:
|
||||
@@ -169,8 +171,8 @@ Use sequentially numbered ADR filenames such as
|
||||
|
||||
Treat the decision content of an accepted ADR as immutable. When a decision
|
||||
changes, create a new ADR and update the earlier ADR's status to superseded.
|
||||
Rejected architectural alternatives belong in the ADR; rejected product ideas
|
||||
belong in the roadmap.
|
||||
|
||||
Roadmaps should preserve plausible future work, not rejected product ideas.
|
||||
|
||||
## Maintenance
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Base Policy Version:** 1.3
|
||||
|
||||
**Last Updated**: 2026-10-17
|
||||
**Last Updated**: 2026-11-07
|
||||
|
||||
**Upstream Source:** [testing.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/testing.md)
|
||||
|
||||
@@ -63,16 +63,19 @@ implemented:
|
||||
- Help and command discovery without provider loading or runtime construction.
|
||||
- Provider failures, cancellation, output errors, and preservation of application
|
||||
outcomes and public error identity.
|
||||
- Selected inspection/report contracts, including native YAML and document order
|
||||
for `config show --scope all`.
|
||||
- Selected inspection/report contracts, including safe scalar preservation and
|
||||
scope-keyed aggregation for `config show --scope all`.
|
||||
- Public type ownership and the internal Cobra/pflag import boundary selected by
|
||||
[ADR 0003](../adr/0003-public-facade.md).
|
||||
[ADR 0002](../adr/0002-public-facade-and-cli-backend.md).
|
||||
|
||||
Use external-package consumer tests for facade semantics and real backend
|
||||
integration where correctness depends on that interaction. Internal package
|
||||
tests own focused mechanisms.
|
||||
Boundary checks protect selected architectural constraints; behavioral evidence
|
||||
protects invocation semantics and ownership through conversions.
|
||||
For shared reports, compare logical values and selected evidence rather than
|
||||
YAML formatting or mapping order. Preserve sequence ordering only where the
|
||||
relevant contract gives it meaning.
|
||||
|
||||
Do not infer concurrent-dispatch support from fresh invocation state. Test
|
||||
concurrency guarantees only if deliberately selected. Coverage targets, race
|
||||
|
||||
@@ -35,8 +35,8 @@ module metadata.
|
||||
|
||||
## Release toolchain
|
||||
|
||||
The selected release toolchain is **Go 1.27.0**. Core and ckprompt declare a
|
||||
consumer minimum of **Go 1.26.0**; ckconfig requires **Go 1.27.0**. Maintainers
|
||||
The selected release toolchain is **Go 1.27.0**. Core declares a
|
||||
consumer minimum of **Go 1.26.0**; both integrations require **Go 1.27.0**. Maintainers
|
||||
use Go 1.27.0 for dependency preparation, candidate validation, and ReleaseKit
|
||||
execution. The
|
||||
[consumer guide](consumers/guide.md#go-compatibility) and
|
||||
|
||||
32
docs/releases/v0.4.0.md
Normal file
32
docs/releases/v0.4.0.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# CommandKit v0.4.0
|
||||
|
||||
CommandKit v0.4.0 adds shared structured reporting and reusable CLI input
|
||||
facilities. Applications and integrations can submit one report value for
|
||||
automatic or explicit text, YAML, and JSON output. Core selects the format,
|
||||
renders optional standard text templates, and records presentation failures
|
||||
through the existing invocation lifecycle. The writer API exposes the same
|
||||
rendering behavior outside an invocation.
|
||||
|
||||
Report values use JSON serialization conventions for structured output. The
|
||||
safe YAML conversion helper accepts upstream inspection documents without
|
||||
reconstructing configuration or treating ordinary strings as YAML. Public CLI
|
||||
JSON parsing and ordered flag occurrences support structured inputs and
|
||||
interleaved bindings. Applications can reuse and rename flag bindings while
|
||||
preserving their typed parsing and presence behavior.
|
||||
|
||||
This pre-1.0 minor release reserves the long flag `--format` for core and
|
||||
changes standard version output to use shared reporting. Applications that
|
||||
declare a local `--format` must remove or rename it; an application alias may
|
||||
target the core flag. Integration report framing and format availability have
|
||||
changed with the shared API; select compatible integration releases as they
|
||||
become available. See the [CLI reference](../cli.md#reporting) and
|
||||
[consumer guide](../consumers/guide.md#invocation-reporting) for current
|
||||
contracts and examples.
|
||||
|
||||
Core continues to declare a Go 1.26.0 consumer minimum. The maintainer release
|
||||
toolchain is Go 1.27.0, and core has no ConfigKit or PromptKit integration
|
||||
dependency.
|
||||
|
||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.4.0/COPYRIGHT) |
|
||||
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.4.0/LICENSE) |
|
||||
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.4.0/docs/oss/attribution.md)
|
||||
@@ -8,6 +8,9 @@ No delivery dates are selected here.
|
||||
Completed roadmaps, implementation plans, and review findings have been retired.
|
||||
This document preserves unfinished work and unselected ideas under the
|
||||
[release policy](../policy/release.md#release-documentation-and-preparation).
|
||||
The completed PromptKit v0.18.0 adoption roadmap and implementation plan remain
|
||||
available in the
|
||||
[PromptKit retirement snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/540e2359d66d604a563df0be1c9fc961588f5b9c/docs/roadmap).
|
||||
The completed ConfigKit adoption, reporting, dependency alignment, release-tooling,
|
||||
and remediation records remain available at the
|
||||
[retirement snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/260256d722f52bc947103d078cb67a129f4cc9f1/docs/roadmap).
|
||||
@@ -21,88 +24,110 @@ an idea here does not select its syntax, API, priority, or delivery date.
|
||||
|
||||
## Pending release and integration work
|
||||
|
||||
### ckconfig release and hosted delivery
|
||||
### ckprompt release
|
||||
|
||||
The ckconfig v0.3.0 candidate adopts ConfigKit v1.1.0 and Go 1.27.0; its
|
||||
implementation and audits are complete. Its
|
||||
[candidate release note](../../integrations/ckconfig/docs/releases/v0.3.0.md)
|
||||
is prepared, but source publication and hosted delivery remain pending. Complete
|
||||
those operations when requested through the [release procedure](../release.md),
|
||||
using the existing fresh-version guards and reporting source publication and
|
||||
hosted Gitea delivery separately. Publishing this roadmap cleanup does not
|
||||
publish a module version tag or deliver a release page.
|
||||
The PromptKit v0.18.0 adoption is complete. The
|
||||
[ckprompt v0.3.0 candidate](../../integrations/ckprompt/docs/releases/v0.3.0.md)
|
||||
remains unpublished. Publication and hosted delivery remain separate operations
|
||||
under the [release procedure](../release.md).
|
||||
The published ckprompt v0.2.0 retains its earlier dependencies; see the
|
||||
[consumer guide](../consumers/guide.md#module-selection) for module selection.
|
||||
|
||||
### ckprompt dependency migration and workspace alignment
|
||||
### PromptKit v0.20.0 adoption
|
||||
|
||||
Review the upstream PromptKit vanity release and select compatible ConfigKit
|
||||
and PromptKit dependencies before migrating ckprompt's adapters and maintained
|
||||
composed consumer. The new ckconfig uses vanity ConfigKit types; ckprompt v0.2.0
|
||||
still uses published ckconfig v0.2.0 and old-path ConfigKit v0.8.0. Their local
|
||||
sources do not currently compose in the three-module workspace. See the
|
||||
[consumer guide](../consumers/guide.md#module-selection) for the current module
|
||||
relationship.
|
||||
|
||||
The follow-up includes migrating affected imports and public type boundaries,
|
||||
selecting real released dependency versions and the required Go minimum,
|
||||
updating notices and migration guidance, and validating both ckprompt's
|
||||
independent graph and the aligned composed consumer. Restore three-module
|
||||
workspace guidance when those dependencies align, updating the ignored workspace
|
||||
Go version as needed. Until then, preserve local workspace files and validate
|
||||
with workspace discovery off as described in the [development guide](../development.md).
|
||||
No unreviewed PromptKit version or new compatibility bridge is selected here.
|
||||
The [PromptKit v0.20.0 roadmap](promptkit-v0.20.0.md) owns the agreed adoption,
|
||||
the shared core reporting/input prerequisites, operator CLI additions for
|
||||
PromptKit and ConfigKit, recorded decisions, and completion checklist. It targets
|
||||
a clean alpha adoption without backward-compatibility provisions or consumer
|
||||
migration guidance. Implementation has not started. Use released upstream
|
||||
contracts only; do not inspect or monitor unreleased work in anticipation of
|
||||
adoption.
|
||||
|
||||
## Future capability targets
|
||||
|
||||
### Comparison extensions
|
||||
|
||||
Independent per-side domain selectors and an optional assertion mode remain
|
||||
unselected extensions to the delivered ConfigKit comparison. Consider them only
|
||||
for a concrete consumer need and a deliberate API/behavior decision under the
|
||||
relevant ADRs.
|
||||
The [working roadmap](promptkit-v0.20.0.md#additional-configkit-operator-workflows)
|
||||
owns independent comparison selections (OD-9), assertion outcomes (OD-10), and
|
||||
optional detailed reports (OD-5). These accepted plans do not change currently
|
||||
implemented behavior.
|
||||
|
||||
General collection-clearing support is deferred pending a concrete consumer need.
|
||||
Revisit standardized syntax and binding support for explicitly replacing a
|
||||
nonempty application-default selector collection with an empty collection.
|
||||
This is separate from clearing configuration lists through OD-11's transient
|
||||
overrides and does not reinstate comparison inheritance. No clearing grammar
|
||||
or public helper API is selected.
|
||||
|
||||
### Configuration inspection extensions
|
||||
|
||||
The [completed ConfigKit v1.1.0 adoption review](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/260256d722f52bc947103d078cb67a129f4cc9f1/docs/roadmap/configkit-v1.1.0.md#selected-scope-decisions)
|
||||
retained the following work after dependency and source-report adoption.
|
||||
Metadata inspection is the recommended next functional sprint; the other
|
||||
features have no selected sequence or delivery date. These proposals do not
|
||||
establish command grammar, report schemas, or new provider requirements.
|
||||
ConfigKit's public APIs own the evidence and its semantics.
|
||||
|
||||
- **Optional field metadata, path discovery, and history (OD-3).** Expose native
|
||||
`Metadata.Lookup`, `IsExplicit`, `HistoricalPaths`, and `History` through an
|
||||
optional provider capability. Design field and history reports together,
|
||||
keeping existing providers usable. Distinguish effective paths from removed
|
||||
historical paths: a failed `Lookup` must not suppress available `History`.
|
||||
Validate that distinction and faithful projection of returned field/change
|
||||
records without recreating upstream provenance logic. Historical enumeration
|
||||
is not an exhaustive inventory of possible schema fields. This gives the
|
||||
earlier field-origin inventory proposal a concrete, upstream-backed scope;
|
||||
command names, selectors, and report shapes remain to be designed.
|
||||
- **Failed-load source inventory (OD-4).** Present acquired source evidence from
|
||||
`LoadError.Sources()` while retaining the failed outcome and diagnostics.
|
||||
Design how an adapter returns its source facet on error and how result output
|
||||
precedes terminal failure presentation. Cover acquisition and report-delivery
|
||||
failures together; current diagnostic context remains available meanwhile.
|
||||
- **Detailed comparison (OD-5).** Consider an additional form projecting native
|
||||
`Difference` paths, both snapshots, presence/redaction fields, and
|
||||
`HiddenChanged`. The current comparison retains the reduced
|
||||
additions/changes/deletions report. Decide later whether a detailed form
|
||||
complements it or replaces it through a deliberate compatibility change.
|
||||
- **Structured diagnostics (OD-6).** Consider machine-readable native codes,
|
||||
paths, severities, and locations alongside CommandKit's shared reporting
|
||||
design. Define result/diagnostic channels, warning and terminal-failure
|
||||
interaction, and delivery outcomes. A ckconfig-specific report remains an
|
||||
alternative, with its cross-family alignment considered explicitly.
|
||||
- **Source-ID filtering.** Consider selecting a record already available in the
|
||||
source inventory. Native `Source(id)` lookup is a convenience; this proposal
|
||||
need not introduce another command or require a lookup method from every
|
||||
custom source provider.
|
||||
The [working roadmap](promptkit-v0.20.0.md#shared-configuration-capabilities)
|
||||
owns metadata/path discovery (OD-4), detailed comparison (OD-5), failed-load
|
||||
evidence and aggregate validation (OD-6), focused inspection/filters (OD-8), and
|
||||
transient overrides (OD-11). The six-command suite, selected output behavior,
|
||||
and pass-through override policy are defined there. Implementation belongs in
|
||||
`ckconfig`, with PromptKit exposing native evidence through its configuration
|
||||
scope. Use the shared core reporting prerequisite and thin projections;
|
||||
presentation refinements should follow implementation and beta feedback.
|
||||
All numbered decisions are settled; exact APIs and wiring remain implementation
|
||||
work. Persistent configuration editing remains deferred.
|
||||
|
||||
Discovery, import defaults, collection identities, and field-level resolution
|
||||
recording remain available through application loaders. Standard inspection of
|
||||
resource contexts or secrets-directory bootstrap has no immediate proposal;
|
||||
those capabilities primarily serve application loading and startup.
|
||||
recording remain available through application loaders. Discovery tracing,
|
||||
resource-context inspection, and secrets-directory bootstrap commands remain
|
||||
deferred. Acquired source records do not provide a complete trace of rejected
|
||||
discovery candidates; bootstrap and resource contexts primarily serve
|
||||
application loading and startup.
|
||||
|
||||
### PromptKit inspection and selection extensions
|
||||
|
||||
The [PromptKit v0.20.0 roadmap](promptkit-v0.20.0.md#targeted-end-state)
|
||||
owns native prompt/profile/backend resource inspection, concrete request preview,
|
||||
applicable request flags, namespace selection, and the shared configuration
|
||||
inspection extensions. The [resource inspection plan](promptkit-v0.20.0.md#resource-inspection)
|
||||
includes backend inspection through the released upstream API. Execution flags
|
||||
will be public reusable `ckprompt` collections for standard and application-owned
|
||||
CLI commands, composed through existing core bindings.
|
||||
[Roadmap OD-2](promptkit-v0.20.0.md#od-2-request-controls-and-provider-parameter-grammar)
|
||||
records the agreed canonical naming, scoped convenience aliases, integration
|
||||
installation collection, selected text/file input forms, and CLI JSON number
|
||||
policy. Numeric conversion uses ordinary Go types and a small internal helper
|
||||
with policy comments, behind a narrow public core CLI JSON parser. Collections
|
||||
and aliases use existing declarations; cross-flag text/file precedence uses the
|
||||
roadmap's ordered typed input prerequisite.
|
||||
Output-contract overrides and appended-message flags are deferred below.
|
||||
These are CLI features; general-purpose helpers for
|
||||
application-internal PromptKit use are outside CommandKit's ownership boundary.
|
||||
|
||||
[Roadmap OD-3](promptkit-v0.20.0.md#od-3-namespace-flags-and-loader-defaults)
|
||||
records the agreed namespace-selector applicability, including the limited role
|
||||
of profile selection in requirements inspection. That selection follows the
|
||||
released upstream identity requirement; it does not change prompt dependencies.
|
||||
|
||||
- **Output-contract override flags.** Deferred from the current adoption. A
|
||||
possible future operator task is validating or previewing one prompt with a
|
||||
replacement output contract without editing its definition. PromptKit uses
|
||||
whole-contract replacement; a complete-contract file option was discussed,
|
||||
but no flag spelling or file format is selected. Existing configuration and
|
||||
application builders remain available. Revisit when the standard `promptkit`
|
||||
commands have a demonstrated need for this workflow.
|
||||
|
||||
- **Appended-message flags.** Deferred from the current adoption. The potential
|
||||
operator task is reproducing a single request with application-added messages
|
||||
through `promptkit show prepared` or `promptkit requirements validate`, to
|
||||
inspect roles, ordering, and content or check preparation. These commands do
|
||||
not test model responses or application workflows. Appended messages follow
|
||||
definition messages in supplied order; they are already rendered and do not
|
||||
satisfy missing named prompt inputs. Revisit when request reproduction is a
|
||||
demonstrated operator requirement. An ordered message-list file is a candidate,
|
||||
but no flag syntax, file format, or supported-role selection is decided.
|
||||
Deferring flags does not remove native appended messages from preview reports
|
||||
when an application builder supplies them.
|
||||
|
||||
[Roadmap OD-2](promptkit-v0.20.0.md#od-2-request-controls-and-provider-parameter-grammar)
|
||||
selects inline text and explicit file input for single-prompt validation and
|
||||
preview. Native API availability alone does not select further CLI syntax or
|
||||
require a convenience API for application execution.
|
||||
|
||||
### Alias completion and discovery
|
||||
|
||||
@@ -120,6 +145,16 @@ steps. No delivery date or final API is selected here.
|
||||
|
||||
### Reporting extensions
|
||||
|
||||
The [shared core report output prerequisite](promptkit-v0.20.0.md#shared-core-report-output-prerequisite)
|
||||
owns application-selected content, core rendering, universal/automatic format
|
||||
selection, JSON representation conventions, text templates, and safe YAML input
|
||||
conversion. Text, YAML, and JSON land together; new core formats work through the
|
||||
same report API. The [output inventory](promptkit-v0.20.0.md#output-implementation-inventory)
|
||||
identifies report paths and preserves explicit raw/help/diagnostic boundaries.
|
||||
OD-6 defines one aggregate validation report and its changed delivery timing.
|
||||
XML is outside current consideration; Markdown and other renderers are not
|
||||
selected for this adoption.
|
||||
|
||||
Error-conversion helpers such as `WarnError` remain deferred pending demonstrated
|
||||
value; applications can already use `report.Warn(err.Error())`. Terminal redraw
|
||||
and progress-bar presentation were outside the completed reporting scope and
|
||||
@@ -144,11 +179,12 @@ candidate checks do not become general prohibitions on development workspaces.
|
||||
These capabilities remain outside the delivered scope and require a concrete
|
||||
operator or consumer need and an appropriate ownership/behavior decision:
|
||||
|
||||
- JSON reports and output-file management or reloadable export.
|
||||
- Additional report renderers as described under [reporting extensions](#reporting-extensions),
|
||||
and output-file management or reloadable export.
|
||||
- Shell completion extensions, including alias discovery described above and
|
||||
dynamic discovery of configured or remote values.
|
||||
- Configuration mutation and generic value assignment. Field metadata and
|
||||
provenance inspection are scoped under
|
||||
- Persistent configuration mutation. Transient CLI overrides are selected under
|
||||
roadmap OD-11; field metadata and provenance inspection are scoped under
|
||||
[configuration inspection extensions](#configuration-inspection-extensions).
|
||||
- Credential diagnostics beyond PromptKit's native smoke checks and additional
|
||||
live provider probes.
|
||||
@@ -158,8 +194,13 @@ operator or consumer need and an appropriate ownership/behavior decision:
|
||||
- Backend selection or replacement, a plugin framework, general dependency
|
||||
injection, and concurrent-dispatch guarantees.
|
||||
|
||||
Execution, rendering, serving, and session operations remain application-owned.
|
||||
Shared vocabulary is guidance under [ADR 0006](../adr/0006-command-grammar.md).
|
||||
Execution, serving, and session operations remain application-owned. The
|
||||
[request preview proposal](promptkit-v0.20.0.md#preview-and-request-flags)
|
||||
exposes native preparation and rendering as an agreed operator inspection target;
|
||||
implementation has not started.
|
||||
The [architecture policy](../policy/architecture.md#command-and-application-ownership)
|
||||
recommends shared vocabulary; the [CLI reference](../cli.md#registered-command-syntax)
|
||||
owns implemented grammar.
|
||||
Backend replacement remains possible behind the accepted facade, subject to the
|
||||
published API/CLI contracts and deliberate compatibility decisions.
|
||||
|
||||
@@ -175,9 +216,6 @@ records are historical evidence, not performance guarantees or release gates.
|
||||
|
||||
## Consumer adoption
|
||||
|
||||
Consumer migrations remain separate from library delivery. Applications can
|
||||
replace duplicated standard handlers and routing, then update their CLI docs
|
||||
and subprocess consumers for intentional changes while retaining domain commands.
|
||||
No migration order or claim about individual applications' adoption is recorded
|
||||
here; the [consumer guide](../consumers/guide.md) and maintained examples provide
|
||||
integration guidance.
|
||||
CommandKit is in alpha with no consumers. No application adoption work or rollout
|
||||
order is selected. The [consumer guide](../consumers/guide.md) and maintained
|
||||
examples provide integration guidance for future applications.
|
||||
|
||||
1016
docs/roadmap/implementation.md
Normal file
1016
docs/roadmap/implementation.md
Normal file
File diff suppressed because it is too large
Load Diff
1417
docs/roadmap/promptkit-v0.20.0.md
Normal file
1417
docs/roadmap/promptkit-v0.20.0.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -7,6 +7,7 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"text/template"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
)
|
||||
@@ -20,6 +21,15 @@ type reportInput struct {
|
||||
Scenario string
|
||||
}
|
||||
|
||||
type greetingReport struct {
|
||||
Count string `json:"count"`
|
||||
Tags string `json:"tags"`
|
||||
Entered string `json:"entered"`
|
||||
Canonical string `json:"canonical"`
|
||||
}
|
||||
|
||||
var greetingTemplate = template.Must(commandkit.ParseTextTemplate("greeting", "Hello; count={{.Count}}; tags={{.Tags}}; entered={{printf \"%q\" .Entered}}; canonical={{printf \"%q\" .Canonical}}\n", nil))
|
||||
|
||||
var (
|
||||
errRecoveredFixture = errors.New("a local read failed and was recovered")
|
||||
errWarningFixture = errors.New("a local warning has a cause")
|
||||
@@ -50,10 +60,7 @@ func newApp() (*commandkit.App, error) {
|
||||
if input.Tags.Set {
|
||||
tags = fmt.Sprintf("explicit %v", input.Tags.Value)
|
||||
}
|
||||
_ = reporter.RenderOutput(func(writer io.Writer) error {
|
||||
_, err := fmt.Fprintf(writer, "Hello; count=%s; tags=%s; entered=%q; canonical=%q\n", count, tags, invocation.EnteredPath(), invocation.CanonicalPath())
|
||||
return err
|
||||
})
|
||||
_ = reporter.Report(commandkit.Report{Value: greetingReport{Count: count, Tags: tags, Entered: invocation.EnteredPath(), Canonical: invocation.CanonicalPath()}, TextTemplate: greetingTemplate})
|
||||
return commandkit.Success()
|
||||
},
|
||||
})
|
||||
|
||||
@@ -59,13 +59,13 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco
|
||||
if !ok || payload == nil {
|
||||
outcome = current.renderHelp(parsed.Path)
|
||||
} else if parsed.HelpRequested || !payload.hasRun() {
|
||||
if _, err := payload.prepare(parsed.FlagValues, parsed.FlagSpellings, parsed.Operands, false); err != nil {
|
||||
if _, err := payload.prepare(parsed.FlagValues, parsed.FlagSpellings, parsed.FlagOccurrences, parsed.Operands, false); err != nil {
|
||||
outcome = classifyInputError(err)
|
||||
} else {
|
||||
outcome = current.renderHelp(parsed.Path)
|
||||
}
|
||||
} else {
|
||||
run, err := payload.prepare(parsed.FlagValues, parsed.FlagSpellings, parsed.Operands, true)
|
||||
run, err := payload.prepare(parsed.FlagValues, parsed.FlagSpellings, parsed.FlagOccurrences, parsed.Operands, true)
|
||||
if err != nil {
|
||||
outcome = classifyInputError(err)
|
||||
} else {
|
||||
@@ -107,6 +107,7 @@ func (current *execution) invocation() Invocation {
|
||||
reporter: current.reporter,
|
||||
enteredPath: current.route.enteredPath.String(),
|
||||
canonicalPath: current.route.canonicalPath.String(),
|
||||
renderHelp: func() Outcome { return current.renderHelp(nil) },
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -475,10 +475,15 @@ func TestVersionCommandFormatsApplicationAndCommandKitIdentity(t *testing.T) {
|
||||
}
|
||||
out.Reset()
|
||||
yamlOutcome := app.Execute(context.Background(), []string{"version", "--format=yaml"}, commandkit.Streams{Out: &out, Err: &diagnostic})
|
||||
if yamlOutcome.Kind != commandkit.OutcomeSuccess || out.String() != "name: ExampleApp\nversion: dev\nrevision: abc123\n" {
|
||||
if yamlOutcome.Kind != commandkit.OutcomeSuccess || !strings.Contains(out.String(), "name: ExampleApp\n") || !strings.Contains(out.String(), "version: dev\n") || !strings.Contains(out.String(), "revision: abc123\n") {
|
||||
t.Fatalf("YAML version = %#v, output %q", yamlOutcome, out.String())
|
||||
}
|
||||
out.Reset()
|
||||
jsonOutcome := app.Execute(context.Background(), []string{"version", "--format=json"}, commandkit.Streams{Out: &out, Err: &diagnostic})
|
||||
if jsonOutcome.Kind != commandkit.OutcomeSuccess || !strings.Contains(out.String(), `"revision": "abc123"`) {
|
||||
t.Fatalf("JSON version = %#v, output %q", jsonOutcome, out.String())
|
||||
}
|
||||
out.Reset()
|
||||
component := app.Execute(context.Background(), []string{"version", "--scope=commandkit"}, commandkit.Streams{Out: &out, Err: &diagnostic})
|
||||
if component.Kind != commandkit.OutcomeSuccess || !strings.HasPrefix(out.String(), "CommandKit ") || !strings.HasSuffix(out.String(), "\n") {
|
||||
t.Fatalf("CommandKit version = %#v, output %q", component, out.String())
|
||||
|
||||
@@ -23,8 +23,8 @@ func stringFlag(name, short string) Flag[struct{}] {
|
||||
}
|
||||
|
||||
func TestFlagAliasChainsUseScopedOverridesAndCanonicalEndpoints(t *testing.T) {
|
||||
inspect := flagAliasCommand("inspect", stringFlag("color", "c"), stringFlag("format", "f"))
|
||||
show := flagAliasCommand("show", stringFlag("color", "c"), stringFlag("format", "f"))
|
||||
inspect := flagAliasCommand("inspect", stringFlag("color", "c"), stringFlag("style", "f"))
|
||||
show := flagAliasCommand("show", stringFlag("color", "c"), stringFlag("style", "f"))
|
||||
group := Group("Tools", "tools", show)
|
||||
app, err := New(Identity{Name: "Example"},
|
||||
inspect,
|
||||
@@ -35,8 +35,8 @@ func TestFlagAliasChainsUseScopedOverridesAndCanonicalEndpoints(t *testing.T) {
|
||||
FlagAlias("-x", "--color"),
|
||||
FlagAlias("--tint", "-c"),
|
||||
FlagAliasFor("Tools", "--group-help", "--help"),
|
||||
FlagAliasFor("inspect", "--hue", "--format"),
|
||||
FlagAliasFor("inspect", "--local", "--format"),
|
||||
FlagAliasFor("inspect", "--hue", "--style"),
|
||||
FlagAliasFor("inspect", "--local", "--style"),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -44,11 +44,11 @@ func TestFlagAliasChainsUseScopedOverridesAndCanonicalEndpoints(t *testing.T) {
|
||||
|
||||
inspectAliases := app.flagAliases[commandpath.Path{"inspect"}.Key()].bySpelling
|
||||
for source, target := range map[string]string{
|
||||
"--colour": "--format",
|
||||
"--hue": "--format",
|
||||
"--colour": "--style",
|
||||
"--hue": "--style",
|
||||
"-x": "--color",
|
||||
"--tint": "-c",
|
||||
"--local": "--format",
|
||||
"--local": "--style",
|
||||
} {
|
||||
alias, ok := inspectAliases[flagSpellingKey(capturedSpelling(source))]
|
||||
if !ok || alias.target.token() != target {
|
||||
@@ -126,7 +126,7 @@ func TestFlagAliasDiscoveryContextsUseGlobalReportingAliases(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestReportingFlagsAreReservedAndAcceptApplicationShortAliases(t *testing.T) {
|
||||
for _, name := range []string{"quiet", "verbose", "debug", "progress"} {
|
||||
for _, name := range []string{"quiet", "verbose", "debug", "progress", "format"} {
|
||||
command := flagAliasCommand("reserved", stringFlag(name, ""))
|
||||
if len(command.record.issues) == 0 {
|
||||
t.Errorf("capturing --%s did not retain a declaration error", name)
|
||||
@@ -154,7 +154,7 @@ func TestReportingFlagsAreReservedAndAcceptApplicationShortAliases(t *testing.T)
|
||||
}
|
||||
|
||||
func TestReportingFlagSpellingsConflictWithAliasSources(t *testing.T) {
|
||||
for _, name := range []string{"quiet", "verbose", "debug", "progress"} {
|
||||
for _, name := range []string{"quiet", "verbose", "debug", "progress", "format"} {
|
||||
if _, err := New(Identity{Name: "Example"}, FlagAlias("--"+name, "--help")); err == nil || !strings.Contains(err.Error(), "conflicts with a canonical spelling") {
|
||||
t.Errorf("alias source --%s returned %v, want a canonical spelling collision", name, err)
|
||||
}
|
||||
@@ -166,7 +166,7 @@ func TestReportingFlagSpellingsConflictWithAliasSources(t *testing.T) {
|
||||
|
||||
func TestRoutingSnapshotCarriesReportingMetadataOutsideConsumerBindings(t *testing.T) {
|
||||
app, err := New(Identity{Name: "Example"},
|
||||
flagAliasCommand("run", stringFlag("format", "f")),
|
||||
flagAliasCommand("run", stringFlag("style", "f")),
|
||||
Group("tools", "", flagAliasCommand("show")),
|
||||
)
|
||||
if err != nil {
|
||||
@@ -174,7 +174,7 @@ func TestRoutingSnapshotCarriesReportingMetadataOutsideConsumerBindings(t *testi
|
||||
}
|
||||
var check func(*commandmeta.Command)
|
||||
check = func(node *commandmeta.Command) {
|
||||
if len(node.CoreFlags) != 4 {
|
||||
if len(node.CoreFlags) != 5 {
|
||||
t.Errorf("%s core reporting flags = %#v", node.Name, node.CoreFlags)
|
||||
}
|
||||
for _, flag := range node.Flags {
|
||||
@@ -190,15 +190,15 @@ func TestRoutingSnapshotCarriesReportingMetadataOutsideConsumerBindings(t *testi
|
||||
}
|
||||
|
||||
func TestFlagAliasDuplicatesAndScopesAreDeterministic(t *testing.T) {
|
||||
command := flagAliasCommand("inspect", stringFlag("color", "c"), stringFlag("format", "f"))
|
||||
command := flagAliasCommand("inspect", stringFlag("color", "c"), stringFlag("style", "f"))
|
||||
duplicate := FlagAlias("--colour", "--color")
|
||||
app, err := New(Identity{Name: "Example"}, command, flagAliasCommand("plain", stringFlag("color", "c")), duplicate, FlagAlias("--colour", "--color"),
|
||||
FlagAliasFor("inspect", "--colour", "--format"))
|
||||
FlagAliasFor("inspect", "--colour", "--style"))
|
||||
if err != nil {
|
||||
t.Fatalf("identical duplicates and scoped override were rejected: %v", err)
|
||||
}
|
||||
if got := app.flagAliases[commandpath.Path{"inspect"}.Key()].bySpelling[flagSpellingKey(capturedFlagSpelling{name: "colour"})].target.token(); got != "--format" {
|
||||
t.Fatalf("scoped alias target = %s, want --format", got)
|
||||
if got := app.flagAliases[commandpath.Path{"inspect"}.Key()].bySpelling[flagSpellingKey(capturedFlagSpelling{name: "colour"})].target.token(); got != "--style" {
|
||||
t.Fatalf("scoped alias target = %s, want --style", got)
|
||||
}
|
||||
if got := app.flagAliases[commandpath.Path{"plain"}.Key()].bySpelling[flagSpellingKey(capturedFlagSpelling{name: "colour"})].target.token(); got != "--color" {
|
||||
t.Fatalf("effective global alias target = %s, want --color", got)
|
||||
@@ -207,11 +207,11 @@ func TestFlagAliasDuplicatesAndScopesAreDeterministic(t *testing.T) {
|
||||
for name, rules := range map[string][]RoutingRule{
|
||||
"competing global targets": {
|
||||
FlagAlias("--colour", "--color"),
|
||||
FlagAlias("--colour", "--format"),
|
||||
FlagAlias("--colour", "--style"),
|
||||
},
|
||||
"competing scoped targets": {
|
||||
FlagAliasFor("inspect", "--colour", "--color"),
|
||||
FlagAliasFor("inspect", "--colour", "--format"),
|
||||
FlagAliasFor("inspect", "--colour", "--style"),
|
||||
},
|
||||
"unknown scope": {FlagAliasFor("missing", "--colour", "--color")},
|
||||
"missing scoped destination": {FlagAliasFor("inspect", "--colour", "--missing")},
|
||||
|
||||
@@ -3,6 +3,7 @@ package commandkit
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// ErrFlagInput identifies a missing required captured flag selected for an input.
|
||||
@@ -13,7 +14,8 @@ var ErrFlagWiring = errors.New("flag wiring is invalid")
|
||||
|
||||
// FlagValues stores invocation-local converted values and presence for captured
|
||||
// flags. It does not retain an input instance; values can be applied to
|
||||
// independently initialized destinations.
|
||||
// independently initialized destinations. Captured occurrence flags retain
|
||||
// their relative command-line order across the selected bindings.
|
||||
type FlagValues[I any] struct {
|
||||
values map[*bindingIdentity]preparedValue[I]
|
||||
}
|
||||
@@ -42,7 +44,7 @@ func CaptureFlags[Outer, I any](flags []Flag[I], target func(*Outer) *FlagValues
|
||||
if err != nil {
|
||||
return preparedValue[Outer]{}, err
|
||||
}
|
||||
return preparedValue[Outer]{
|
||||
result := preparedValue[Outer]{
|
||||
identity: identity,
|
||||
supplied: prepared.supplied,
|
||||
apply: func(outer *Outer) {
|
||||
@@ -55,7 +57,11 @@ func CaptureFlags[Outer, I any](flags []Flag[I], target func(*Outer) *FlagValues
|
||||
}
|
||||
store.values[inner.binding.identity] = prepared
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
for _, occurrence := range prepared.ordered {
|
||||
result.ordered = append(result.ordered, preparedOccurrence[Outer]{ordinal: occurrence.ordinal})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
captured[index] = Flag[Outer]{binding: binding}
|
||||
@@ -66,11 +72,25 @@ func CaptureFlags[Outer, I any](flags []Flag[I], target func(*Outer) *FlagValues
|
||||
// ApplyTo applies selected original captured flags to an initialized
|
||||
// destination. A missing captured binding or nil destination matches
|
||||
// ErrFlagWiring. A required selected value that was not supplied matches
|
||||
// ErrFlagInput. Repeated core-owned values are copied for each application.
|
||||
// ErrFlagInput. Ordinary selected values are applied first, followed by selected
|
||||
// occurrence values in command-line order. Repeated core-owned values are copied
|
||||
// for each application.
|
||||
func (values FlagValues[I]) ApplyTo(target *I, selected ...Flag[I]) error {
|
||||
return values.applyTo(target, false, selected...)
|
||||
}
|
||||
|
||||
// ApplySuppliedTo applies only explicitly supplied selected flags, preserving
|
||||
// the destination's existing values for omitted flags. It checks selected
|
||||
// bindings and required values like ApplyTo and preserves occurrence order.
|
||||
func (values FlagValues[I]) ApplySuppliedTo(target *I, selected ...Flag[I]) error {
|
||||
return values.applyTo(target, true, selected...)
|
||||
}
|
||||
|
||||
func (values FlagValues[I]) applyTo(target *I, suppliedOnly bool, selected ...Flag[I]) error {
|
||||
if target == nil {
|
||||
return fmt.Errorf("%w: destination is nil", ErrFlagWiring)
|
||||
}
|
||||
preparedValues := make([]preparedValue[I], 0, len(selected))
|
||||
for _, flag := range selected {
|
||||
binding := flag.binding
|
||||
if binding.identity == nil {
|
||||
@@ -83,7 +103,25 @@ func (values FlagValues[I]) ApplyTo(target *I, selected ...Flag[I]) error {
|
||||
if binding.meta.Required && !prepared.supplied {
|
||||
return fmt.Errorf("flag --%s: %w", binding.meta.Name, ErrFlagInput)
|
||||
}
|
||||
prepared.apply(target)
|
||||
if suppliedOnly && !prepared.supplied {
|
||||
continue
|
||||
}
|
||||
preparedValues = append(preparedValues, prepared)
|
||||
}
|
||||
var ordered []preparedOccurrence[I]
|
||||
for _, prepared := range preparedValues {
|
||||
if prepared.apply != nil {
|
||||
prepared.apply(target)
|
||||
}
|
||||
for _, occurrence := range prepared.ordered {
|
||||
if occurrence.apply != nil {
|
||||
ordered = append(ordered, occurrence)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.SliceStable(ordered, func(i, j int) bool { return *ordered[i].ordinal < *ordered[j].ordinal })
|
||||
for _, occurrence := range ordered {
|
||||
occurrence.apply(target)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
82
format_flag_test.go
Normal file
82
format_flag_test.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package commandkit
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
commandmeta "go.maximumdirect.net/commandkit/internal/commandmeta"
|
||||
)
|
||||
|
||||
func TestSharedFormatFlag(t *testing.T) {
|
||||
factories, runs := 0, 0
|
||||
command := NewCommand(CommandSpec[struct{}]{Name: "run", NewInput: func() struct{} { factories++; return struct{}{} }, Run: func(inv Invocation, _ struct{}) Outcome {
|
||||
runs++
|
||||
_ = inv.Reporter().Report(Report{Value: map[string]any{"answer": 42}})
|
||||
return Success()
|
||||
}})
|
||||
app, err := New(Identity{Name: "Example", Version: "1"}, command, FlagAlias("--fmt", "--format"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
args []string
|
||||
expected string
|
||||
}{
|
||||
{[]string{"run", "--format", "text"}, "yaml"},
|
||||
{[]string{"run", "--format=yaml"}, "yaml"},
|
||||
{[]string{"run", "--fmt=json"}, "json"},
|
||||
{[]string{"run", "--format=yaml", "--fmt", "json"}, "json"},
|
||||
{[]string{"run"}, "yaml"},
|
||||
} {
|
||||
var out bytes.Buffer
|
||||
got := app.Execute(context.Background(), tc.args, Streams{Out: &out})
|
||||
if got.Status != 0 {
|
||||
t.Fatalf("%v: %#v", tc.args, got)
|
||||
}
|
||||
var value any
|
||||
if tc.expected == "json" {
|
||||
dec := json.NewDecoder(&out)
|
||||
dec.UseNumber()
|
||||
err = dec.Decode(&value)
|
||||
} else {
|
||||
value, err = DecodeYAMLReport(&out)
|
||||
}
|
||||
if err != nil || !reflect.DeepEqual(value, map[string]any{"answer": json.Number("42")}) {
|
||||
t.Fatalf("%v: %#v %v", tc.args, value, err)
|
||||
}
|
||||
}
|
||||
beforeFactories, beforeRuns := factories, runs
|
||||
for _, args := range [][]string{{"run", "--format="}, {"run", "--fmt=xml"}, {"run", "--format=bad", "--format=json"}, {"run", "--format", "--quiet"}} {
|
||||
var diagnostics bytes.Buffer
|
||||
got := app.Execute(context.Background(), args, Streams{Err: &diagnostics})
|
||||
if got.Kind != OutcomeUsage || !strings.Contains(diagnostics.String(), "format") {
|
||||
t.Fatalf("%v: %#v %q", args, got, &diagnostics)
|
||||
}
|
||||
}
|
||||
if factories != beforeFactories || runs != beforeRuns {
|
||||
t.Fatalf("invalid formats ran domain code: factories %d, runs %d", factories, runs)
|
||||
}
|
||||
var help bytes.Buffer
|
||||
got := app.Execute(context.Background(), []string{"run", "--help"}, Streams{Out: &help})
|
||||
if got.Status != 0 || !strings.Contains(help.String(), "--format") || factories != beforeFactories || runs != beforeRuns {
|
||||
t.Fatalf("help: %#v, %q", got, &help)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharedFormatParseOrderAndTerminator(t *testing.T) {
|
||||
app, err := New(Identity{Name: "Example"}, flagAliasCommand("run", stringFlag("message", "")), FlagAlias("--fmt", "--format"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result := parseReportingArgs(app, []string{"run", "--verbose", "--fmt", "json", "--quiet", "--message=--format", "--", "--format=yaml"})
|
||||
if result.Failure != nil || result.Reporting.Format != "json" || result.Reporting.Mode != commandmeta.ReportingModeQuiet || !reflect.DeepEqual(result.Operands, []string{"--format=yaml"}) {
|
||||
t.Fatalf("%#v", result)
|
||||
}
|
||||
if result.FlagOccurrences[1].Spelling != "--fmt" || result.FlagOccurrences[1].RawValue != "json" {
|
||||
t.Fatalf("%#v", result.FlagOccurrences)
|
||||
}
|
||||
}
|
||||
10
identity.go
10
identity.go
@@ -52,12 +52,22 @@ type Invocation struct {
|
||||
reporter *Reporter
|
||||
enteredPath string
|
||||
canonicalPath string
|
||||
renderHelp func() Outcome
|
||||
}
|
||||
|
||||
// Reporter returns the reporting facility supplied for this invocation. A
|
||||
// manually constructed Invocation has no reporter.
|
||||
func (inv Invocation) Reporter() *Reporter { return inv.reporter }
|
||||
|
||||
// Help renders the selected command's help through this invocation's output.
|
||||
// It returns an operational failure when the invocation has no help renderer.
|
||||
func (inv Invocation) Help() Outcome {
|
||||
if inv.renderHelp == nil {
|
||||
return Failure("Command help is unavailable.")
|
||||
}
|
||||
return inv.renderHelp()
|
||||
}
|
||||
|
||||
// EnteredPath returns the command path used to invoke the selected command,
|
||||
// excluding the executable name, flags, and operands. It is empty for an
|
||||
// Invocation that was not created by command execution.
|
||||
|
||||
@@ -7,8 +7,8 @@ itself.
|
||||
|
||||
## Module
|
||||
|
||||
The module path is `go.maximumdirect.net/ckconfig`. The prepared v0.3.0
|
||||
candidate requires Go 1.27.0 and uses `go.maximumdirect.net/commandkit v0.3.0` and
|
||||
The module path is `go.maximumdirect.net/ckconfig`. Version v0.3.0 requires Go
|
||||
1.27.0 and uses `go.maximumdirect.net/commandkit v0.3.0` and
|
||||
`go.maximumdirect.net/configkit v1.1.0`; it does not import PromptKit. See the
|
||||
[consumer guide](https://gitea.maximumdirect.net/eric/CommandKit/src/branch/main/docs/consumers/guide.md#configkit-scopes)
|
||||
for exact callback and lifetime contracts.
|
||||
@@ -28,7 +28,7 @@ ConfigKit loader. The `config` command family exposes scope discovery and the
|
||||
validate, show, sources, explain, and diff operations supported by the declared
|
||||
scopes. Source reports include native destination, placement, destination
|
||||
fallback, version evidence, and empty-import selections. Comparison returns
|
||||
ConfigKit's native records to the YAML report path; the
|
||||
ConfigKit's native records to shared report rendering; the
|
||||
[CLI reference](https://gitea.maximumdirect.net/eric/CommandKit/src/branch/main/docs/cli.md#compare-configuration-selections)
|
||||
owns its operator details.
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -66,7 +67,7 @@ func TestFromConfigKitCompareReturnsNativeChangesAndLoadsEqualSelections(t *test
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(calls) != 2 || calls[0].selection != selection || calls[1].selection != selection {
|
||||
if len(calls) != 2 || !reflect.DeepEqual(calls[0].selection, selection) || !reflect.DeepEqual(calls[1].selection, selection) {
|
||||
t.Fatalf("loader calls = %#v", calls)
|
||||
}
|
||||
if calls[0].input.Label != "before" || calls[1].input.Label != "after" || calls[0].state != state || calls[1].state != state || *state != 2 {
|
||||
|
||||
@@ -3,6 +3,7 @@ package ckconfig
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -10,57 +11,6 @@ import (
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestComparisonSelectionInheritsFieldsIndependently(t *testing.T) {
|
||||
leftConfig := commandkit.Supplied[string]{Value: "before.yml", Set: true}
|
||||
leftOverlay := commandkit.Supplied[string]{Value: "base", Set: true}
|
||||
tests := []struct {
|
||||
name string
|
||||
left Selection
|
||||
right Selection
|
||||
want Selection
|
||||
}{
|
||||
{
|
||||
name: "omitted fields stay omitted",
|
||||
},
|
||||
{
|
||||
name: "both fields inherit supplied state",
|
||||
left: Selection{Config: leftConfig, Overlay: leftOverlay},
|
||||
want: Selection{Config: leftConfig, Overlay: leftOverlay},
|
||||
},
|
||||
{
|
||||
name: "explicit empty config overrides while overlay inherits",
|
||||
left: Selection{Config: leftConfig, Overlay: leftOverlay},
|
||||
right: Selection{Config: commandkit.Supplied[string]{Set: true}},
|
||||
want: Selection{Config: commandkit.Supplied[string]{Set: true}, Overlay: leftOverlay},
|
||||
},
|
||||
{
|
||||
name: "explicit overlay overrides while config inherits",
|
||||
left: Selection{Config: leftConfig, Overlay: leftOverlay},
|
||||
right: Selection{Overlay: commandkit.Supplied[string]{Value: "candidate", Set: true}},
|
||||
want: Selection{Config: leftConfig, Overlay: commandkit.Supplied[string]{Value: "candidate", Set: true}},
|
||||
},
|
||||
{
|
||||
name: "explicit empty overlay remains supplied",
|
||||
left: Selection{Config: leftConfig, Overlay: leftOverlay},
|
||||
right: Selection{Overlay: commandkit.Supplied[string]{Set: true}},
|
||||
want: Selection{Config: leftConfig, Overlay: commandkit.Supplied[string]{Set: true}},
|
||||
},
|
||||
{
|
||||
name: "both explicit right fields replace left",
|
||||
left: Selection{Config: leftConfig, Overlay: leftOverlay},
|
||||
right: Selection{Config: commandkit.Supplied[string]{Value: "after.yml", Set: true}, Overlay: commandkit.Supplied[string]{Value: "new", Set: true}},
|
||||
want: Selection{Config: commandkit.Supplied[string]{Value: "after.yml", Set: true}, Overlay: commandkit.Supplied[string]{Value: "new", Set: true}},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if got := inheritComparisonSelection(test.left, test.right); got != test.want {
|
||||
t.Fatalf("inherited selection = %#v, want %#v", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestComparisonHelpLimitsFlagsAndDefaultsFormatToYAML(t *testing.T) {
|
||||
scope := Scope[struct{}, struct{}]{
|
||||
Name: "app", Operations: []Operation{Diff, Show, Explain, Validate, Sources},
|
||||
@@ -83,21 +33,12 @@ func TestComparisonHelpLimitsFlagsAndDefaultsFormatToYAML(t *testing.T) {
|
||||
if !strings.Contains(diffHelp, "--against-config") || !strings.Contains(diffHelp, "--against-overlay") {
|
||||
t.Fatalf("diff help omits right-side selection flags:\n%s", diffHelp)
|
||||
}
|
||||
if !strings.Contains(diffHelp, "default: yaml") {
|
||||
t.Fatalf("diff help does not show the YAML default:\n%s", diffHelp)
|
||||
}
|
||||
for _, operation := range []string{"validate", "show", "sources", "explain"} {
|
||||
operationHelp := help("config", operation, "--help")
|
||||
if strings.Contains(operationHelp, "--against-config") || strings.Contains(operationHelp, "--against-overlay") {
|
||||
t.Errorf("%s exposes comparison-only flags:\n%s", operation, operationHelp)
|
||||
}
|
||||
if operation == "show" && !strings.Contains(operationHelp, "default: yaml") {
|
||||
t.Errorf("show format default changed:\n%s", operationHelp)
|
||||
}
|
||||
if operation != "show" && !strings.Contains(operationHelp, "default: text") {
|
||||
t.Errorf("%s format default changed:\n%s", operation, operationHelp)
|
||||
}
|
||||
if operation != "explain" && strings.Contains(operationHelp, "--path") {
|
||||
if operation != "explain" && operation != "show" && strings.Contains(operationHelp, "--path") {
|
||||
t.Errorf("%s exposes the explain-only path flag:\n%s", operation, operationHelp)
|
||||
}
|
||||
}
|
||||
@@ -107,7 +48,7 @@ func TestComparisonHelpLimitsFlagsAndDefaultsFormatToYAML(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestComparisonPreparationAcceptsOnlyYAML(t *testing.T) {
|
||||
func TestComparisonPreparation(t *testing.T) {
|
||||
inputCalls, stateCalls := 0, 0
|
||||
prepared := captureSuite(Suite[struct{}, struct{}]{
|
||||
NewInput: func() struct{} { inputCalls++; return struct{}{} },
|
||||
@@ -123,30 +64,22 @@ func TestComparisonPreparationAcceptsOnlyYAML(t *testing.T) {
|
||||
input := &configCommandInput[struct{}, struct{}]{
|
||||
selection: Selection{Config: commandkit.Supplied[string]{Value: "before.yml", Set: true}},
|
||||
against: Selection{Overlay: commandkit.Supplied[string]{Value: "candidate", Set: true}},
|
||||
format: commandkit.Supplied[string]{Value: "yaml", Set: true},
|
||||
}
|
||||
if err := prepareConfigOperation(prepared, Diff, input); err != nil {
|
||||
t.Fatalf("explicit YAML format rejected: %v", err)
|
||||
}
|
||||
if input.plan == nil || input.plan.format != "yaml" {
|
||||
if input.plan == nil {
|
||||
t.Fatalf("comparison plan = %#v", input.plan)
|
||||
}
|
||||
if input.plan.scopeName != "app" {
|
||||
t.Fatalf("comparison default scope = %q, want app", input.plan.scopeName)
|
||||
}
|
||||
if want := (Selection{
|
||||
Config: commandkit.Supplied[string]{Value: "before.yml", Set: true},
|
||||
Overlay: commandkit.Supplied[string]{Value: "candidate", Set: true},
|
||||
}); input.against != want {
|
||||
}); !reflect.DeepEqual(input.against, want) {
|
||||
t.Fatalf("resolved right selection = %#v, want %#v", input.against, want)
|
||||
}
|
||||
|
||||
for _, format := range []string{"text", "json"} {
|
||||
input := &configCommandInput[struct{}, struct{}]{format: commandkit.Supplied[string]{Value: format}}
|
||||
if err := prepareConfigOperation(prepared, Diff, input); err == nil {
|
||||
t.Errorf("comparison format %q was accepted", format)
|
||||
}
|
||||
}
|
||||
if inputCalls != 2 || stateCalls != 0 {
|
||||
t.Fatalf("comparison preparation calls input/state: %d/%d", inputCalls, stateCalls)
|
||||
}
|
||||
@@ -170,8 +103,7 @@ func TestComparisonAvailabilityPreflightPrecedesFactories(t *testing.T) {
|
||||
})
|
||||
for _, scope := range []string{"missing", "all", "plain"} {
|
||||
input := &configCommandInput[struct{}, struct{}]{
|
||||
scope: commandkit.Supplied[string]{Value: scope, Set: true},
|
||||
format: commandkit.Supplied[string]{Value: "yaml"},
|
||||
scope: commandkit.Supplied[string]{Value: scope, Set: true},
|
||||
}
|
||||
if err := prepareConfigOperation(prepared, Diff, input); err == nil {
|
||||
t.Errorf("comparison scope %q was accepted", scope)
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -62,7 +63,7 @@ func TestComparisonPreparesEqualSelectionsWithSeparateTypedInputs(t *testing.T)
|
||||
}
|
||||
return struct{}{}
|
||||
},
|
||||
Selectors: []Selector[*input]{{Binding: enabled}, {Binding: limit}, {Binding: tags}},
|
||||
Selectors: []Selector[*input]{{Binding: enabled, AgainstName: "against-enabled"}, {Binding: limit, AgainstName: "against-limit"}, {Binding: tags, AgainstName: "against-tag"}},
|
||||
CheckInput: func(scope string, selection Selection, value *input) error {
|
||||
checkCalls++
|
||||
preparedInputs = append(preparedInputs, value)
|
||||
@@ -91,7 +92,7 @@ func TestComparisonPreparesEqualSelectionsWithSeparateTypedInputs(t *testing.T)
|
||||
app := newConfigTestApp(t, Command(suite))
|
||||
outcome := app.Execute(context.Background(), []string{
|
||||
"config", "diff", "--config", "same.yml", "--against-config", "same.yml", "--overlay=",
|
||||
"--enabled=false", "--limit=0", "--tag", "alpha", "--tag", "beta",
|
||||
"--enabled=false", "--limit=0", "--tag", "alpha", "--tag", "beta", "--against-enabled=false", "--against-limit=0", "--against-tag", "alpha", "--against-tag", "beta", "--against-overlay=",
|
||||
}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if outcome.Kind != commandkit.OutcomeSuccess {
|
||||
t.Fatalf("valid comparison outcome = %#v", outcome)
|
||||
@@ -99,14 +100,14 @@ func TestComparisonPreparesEqualSelectionsWithSeparateTypedInputs(t *testing.T)
|
||||
if inputCalls != 2 || checkCalls != 2 || stateCalls != 1 {
|
||||
t.Fatalf("preparation calls input=%d check=%d state=%d", inputCalls, checkCalls, stateCalls)
|
||||
}
|
||||
if parseCalls != 3 {
|
||||
if parseCalls != 6 {
|
||||
t.Fatalf("typed values were converted %d times, want once per supplied occurrence", parseCalls)
|
||||
}
|
||||
wantSelection := Selection{
|
||||
Config: commandkit.Supplied[string]{Value: "same.yml", Set: true},
|
||||
Overlay: commandkit.Supplied[string]{Set: true},
|
||||
}
|
||||
if len(selections) != 2 || selections[0] != wantSelection || selections[1] != wantSelection {
|
||||
if len(selections) != 2 || !reflect.DeepEqual(selections[0], wantSelection) || !reflect.DeepEqual(selections[1], wantSelection) {
|
||||
t.Fatalf("side selections = %#v, want equal %#v values", selections, wantSelection)
|
||||
}
|
||||
}
|
||||
@@ -115,7 +116,7 @@ func TestComparisonProviderReceivesCheckedPairAndSharedState(t *testing.T) {
|
||||
type input struct{ ID int }
|
||||
type state struct{ Label string }
|
||||
inputCalls, checkCalls, stateCalls, compareCalls, acquireCalls := 0, 0, 0, 0, 0
|
||||
checked := make(map[Selection]input)
|
||||
var checked []input
|
||||
shared := &state{Label: "shared"}
|
||||
var request ComparisonRequest[input]
|
||||
app := newConfigTestApp(t, Command(Suite[input, *state]{
|
||||
@@ -135,7 +136,7 @@ func TestComparisonProviderReceivesCheckedPairAndSharedState(t *testing.T) {
|
||||
if scope != "app" {
|
||||
return errors.New("unexpected scope")
|
||||
}
|
||||
checked[selection] = value
|
||||
checked = append(checked, value)
|
||||
return nil
|
||||
},
|
||||
Scopes: []Scope[input, *state]{{
|
||||
@@ -161,11 +162,11 @@ func TestComparisonProviderReceivesCheckedPairAndSharedState(t *testing.T) {
|
||||
t.Fatalf("comparison outcome = %#v", outcome)
|
||||
}
|
||||
left := Selection{Config: commandkit.Supplied[string]{Value: "before.yml", Set: true}}
|
||||
right := Selection{Config: left.Config, Overlay: commandkit.Supplied[string]{Set: true}}
|
||||
if request.Left.Selection != left || request.Right.Selection != right {
|
||||
right := Selection{Overlay: commandkit.Supplied[string]{Set: true}}
|
||||
if !reflect.DeepEqual(request.Left.Selection, left) || !reflect.DeepEqual(request.Right.Selection, right) {
|
||||
t.Fatalf("provider selections = %#v", request)
|
||||
}
|
||||
if len(checked) != 2 || request.Left.Input != checked[left] || request.Right.Input != checked[right] {
|
||||
if len(checked) != 2 || request.Left.Input != checked[0] || request.Right.Input != checked[1] {
|
||||
t.Fatalf("provider inputs = %#v, checked = %#v", request, checked)
|
||||
}
|
||||
if inputCalls != 2 || checkCalls != 2 || stateCalls != 1 || compareCalls != 1 || acquireCalls != 0 {
|
||||
@@ -191,7 +192,7 @@ func TestComparisonDoesNotRetainPartialPlanAfterSideFailure(t *testing.T) {
|
||||
},
|
||||
}},
|
||||
})
|
||||
commandInput := &configCommandInput[struct{}, struct{}]{format: commandkit.Supplied[string]{Value: "yaml"}}
|
||||
commandInput := &configCommandInput[struct{}, struct{}]{}
|
||||
if err := prepareConfigOperation(prepared, Diff, commandInput); !errors.Is(err, failure) {
|
||||
t.Fatalf("right-side input failure = %v", err)
|
||||
}
|
||||
@@ -217,7 +218,7 @@ func TestComparisonNilInputFactoryUsesZeroValue(t *testing.T) {
|
||||
},
|
||||
}},
|
||||
})
|
||||
commandInput := &configCommandInput[*int, struct{}]{format: commandkit.Supplied[string]{Value: "yaml"}}
|
||||
commandInput := &configCommandInput[*int, struct{}]{}
|
||||
if err := prepareConfigOperation(prepared, Diff, commandInput); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -246,7 +247,7 @@ func TestComparisonPreservesCallerOwnedInputAliases(t *testing.T) {
|
||||
},
|
||||
}},
|
||||
})
|
||||
commandInput := &configCommandInput[*int, struct{}]{format: commandkit.Supplied[string]{Value: "yaml"}}
|
||||
commandInput := &configCommandInput[*int, struct{}]{}
|
||||
if err := prepareConfigOperation(prepared, Diff, commandInput); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ func TestCompletionUsesInstalledScopeCapabilitiesWithoutAcquisition(t *testing.T
|
||||
}{
|
||||
{[]string{"__complete", "config", "diff", "--scope="}, "app\n", "other\n"},
|
||||
{[]string{"__complete", "config", "validate", "--scope="}, "other\n", "all\n"},
|
||||
{[]string{"__complete", "config", "diff", "--format="}, "yaml\n", "text\n"},
|
||||
{[]string{"__complete", "config", "diff", "--format="}, "yaml\n", "invalid\n"},
|
||||
{[]string{"__complete", "config", "validate", "--format="}, "text\n", "invalid\n"},
|
||||
{[]string{"__complete", "config", "diff", "--against-config=fixtures/"}, ":0\n", ":4\n"},
|
||||
} {
|
||||
|
||||
@@ -26,6 +26,7 @@ func FromConfigKit[I, S, T any](
|
||||
Name: name,
|
||||
Summary: summary,
|
||||
Operations: []Operation{Validate, Show, Sources, Explain, Diff},
|
||||
Features: ScopeFeatures{PathDiscovery: true, PathShow: true},
|
||||
}
|
||||
if load == nil {
|
||||
return WithScopeError(scope, fmt.Errorf("ConfigKit scope %q loader must not be nil", name))
|
||||
@@ -34,22 +35,25 @@ func FromConfigKit[I, S, T any](
|
||||
scope.Acquire = func(ctx context.Context, request Request, input I, state S) (commandkit.Acquired[View], error) {
|
||||
result, err := load(ctx, request.Selection, input, state)
|
||||
acquired := commandkit.Acquired[View]{}
|
||||
if result != nil {
|
||||
acquired.Value = View{Effective: result, Sources: result, Explanation: result}
|
||||
acquired.Diagnostics, acquired.Explanation = configKitDiagnostics(name, result.Sources(), result.Diagnostics())
|
||||
}
|
||||
if err != nil {
|
||||
var loadError *configkit.LoadError
|
||||
if errors.As(err, &loadError) && loadError != nil {
|
||||
warnings, explanation := configKitDiagnostics(name, loadError.Sources(), loadError.Diagnostics())
|
||||
acquired.Diagnostics = append(acquired.Diagnostics, warnings...)
|
||||
acquired.Explanation = appendConfigKitExplanation(acquired.Explanation, explanation)
|
||||
records := loadError.Diagnostics()
|
||||
messages, explanation := configKitDiagnostics(name, loadError.Sources(), records)
|
||||
acquired.Value.Sources = loadError
|
||||
acquired.Value.Findings = &Findings{Records: records, Messages: messages}
|
||||
acquired.Explanation = explanation
|
||||
}
|
||||
return acquired, err
|
||||
}
|
||||
if result == nil {
|
||||
return commandkit.Acquired[View]{}, fmt.Errorf("ConfigKit scope %q returned a nil result", name)
|
||||
}
|
||||
metadata := result.Metadata()
|
||||
records := result.Diagnostics()
|
||||
messages, explanation := configKitDiagnostics(name, result.Sources(), records)
|
||||
acquired.Value = View{Effective: result, Sources: result, Explanation: result, Metadata: &metadata, Findings: &Findings{Records: records, Messages: messages}}
|
||||
acquired.Explanation = explanation
|
||||
return acquired, nil
|
||||
}
|
||||
scope.Compare = func(ctx context.Context, request ComparisonRequest[I], state S) (commandkit.Acquired[[]configkit.Difference], error) {
|
||||
@@ -99,11 +103,6 @@ func loadComparisonSide[I, S, T any](
|
||||
result, err := load(ctx, request.Selection, request.Input, state)
|
||||
var diagnostics []commandkit.Diagnostic
|
||||
var explanation commandkit.Explanation
|
||||
if result != nil {
|
||||
warnings, terminal := configKitComparisonDiagnostics(scope, side, result.Sources(), result.Diagnostics())
|
||||
diagnostics = append(diagnostics, warnings...)
|
||||
explanation = appendConfigKitExplanation(explanation, terminal)
|
||||
}
|
||||
if err != nil {
|
||||
var loadError *configkit.LoadError
|
||||
if errors.As(err, &loadError) && loadError != nil {
|
||||
@@ -116,6 +115,7 @@ func loadComparisonSide[I, S, T any](
|
||||
if result == nil {
|
||||
return nil, diagnostics, explanation, fmt.Errorf("ConfigKit scope %q %s loader returned a nil result", scope, side)
|
||||
}
|
||||
diagnostics, explanation = configKitComparisonDiagnostics(scope, side, result.Sources(), result.Diagnostics())
|
||||
return result, diagnostics, explanation, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ type Selection struct {
|
||||
Config commandkit.Supplied[string]
|
||||
// Overlay is the caller-supplied overlay path, if present.
|
||||
Overlay commandkit.Supplied[string]
|
||||
// Overrides contains ordered CLI override records, or nil when none were supplied.
|
||||
Overrides []configkit.Override
|
||||
}
|
||||
|
||||
// Operation identifies a supported standard configuration operation.
|
||||
@@ -45,7 +47,7 @@ type Request struct {
|
||||
// initialized and checked typed input. The supplied-state fields of Selection
|
||||
// are preserved for the scope's loader.
|
||||
type ComparisonSide[I any] struct {
|
||||
// Selection carries the explicit config and overlay inputs for this side.
|
||||
// Selection carries the explicit config, overlay, and override inputs for this side.
|
||||
Selection Selection
|
||||
// Input is initialized and checked for this side before comparison.
|
||||
Input I
|
||||
@@ -83,6 +85,29 @@ type View struct {
|
||||
Effective EffectiveWriter
|
||||
Sources SourceReader
|
||||
Explanation ExplanationReader
|
||||
// Metadata supplies native configuration path metadata when available.
|
||||
Metadata *configkit.Metadata
|
||||
// Findings supplies native diagnostics and their ordinary presentations.
|
||||
// Nil means unavailable; a nonnil value may contain no records.
|
||||
Findings *Findings
|
||||
}
|
||||
|
||||
// Findings associates native diagnostic records with their ordinary messages.
|
||||
type Findings struct {
|
||||
// Records contains the native diagnostic records, which may be empty.
|
||||
Records []configkit.Diagnostic
|
||||
// Messages contains ordinary presentations associated with Records.
|
||||
Messages []commandkit.Diagnostic
|
||||
}
|
||||
|
||||
// ScopeFeatures describes optional modes within configuration operations.
|
||||
type ScopeFeatures struct {
|
||||
// PathDiscovery indicates support for metadata-backed path discovery.
|
||||
PathDiscovery bool
|
||||
// PathShow indicates support for displaying a selected effective path.
|
||||
PathShow bool
|
||||
// Overrides indicates that the loader accepts explicit configuration overrides.
|
||||
Overrides bool
|
||||
}
|
||||
|
||||
// Scope declares the operations and providers for one named configuration.
|
||||
@@ -93,10 +118,12 @@ type View struct {
|
||||
type Scope[I, S any] struct {
|
||||
// Name identifies the scope in CLI selection and reports.
|
||||
Name string
|
||||
// Summary describes the scope. Scope discovery reports name and operations only.
|
||||
// Summary describes the scope.
|
||||
Summary string
|
||||
// Operations selects the standard handlers exposed for this scope.
|
||||
Operations []Operation
|
||||
// Features describes optional modes supported by this scope.
|
||||
Features ScopeFeatures
|
||||
// Acquire loads the selected configuration for one ordinary inspection
|
||||
// invocation. It returns independent diagnostics and terminal context
|
||||
// separately from the native value and optional operation error.
|
||||
@@ -116,6 +143,9 @@ type Selector[I any] struct {
|
||||
Binding commandkit.Flag[I]
|
||||
// Scopes lists the scope names that receive this flag's value.
|
||||
Scopes []string
|
||||
// AgainstName optionally declares the long name of an independent
|
||||
// right-side comparison flag using the same parser and setter.
|
||||
AgainstName string
|
||||
}
|
||||
|
||||
// Suite declares the typed input, shared state, selectors, and configuration
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -91,10 +92,10 @@ func TestFromConfigKitPassesInvocationValuesAndNativeFacets(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gotContext != ctx || gotSelection != selection || gotInput.Label != "typed" || gotState != stateValue || stateValue.Calls != 1 {
|
||||
if gotContext != ctx || !reflect.DeepEqual(gotSelection, selection) || gotInput.Label != "typed" || gotState != stateValue || stateValue.Calls != 1 {
|
||||
t.Fatalf("loader arguments/context/state = %v, %#v, %#v, %p, %d", gotContext, gotSelection, gotInput, gotState, stateValue.Calls)
|
||||
}
|
||||
if acquired.Value.Effective != result || acquired.Value.Sources != result || acquired.Value.Explanation != result {
|
||||
if acquired.Value.Effective != result || acquired.Value.Sources != result || acquired.Value.Explanation != result || acquired.Value.Metadata == nil || acquired.Value.Findings == nil {
|
||||
t.Fatal("adapter did not expose the native result facets directly")
|
||||
}
|
||||
|
||||
@@ -150,14 +151,14 @@ func TestFromConfigKitRetainsLoadErrorAndDiagnostics(t *testing.T) {
|
||||
if !errors.As(gotErr, &typed) {
|
||||
t.Fatalf("load error type was not retained: %T", gotErr)
|
||||
}
|
||||
if len(acquired.Diagnostics) != 1 || acquired.Diagnostics[0].Severity != commandkit.SeverityWarning {
|
||||
t.Fatalf("failure diagnostics = %#v", acquired.Diagnostics)
|
||||
if acquired.Value.Effective != nil || acquired.Value.Metadata != nil || acquired.Value.Sources == nil || acquired.Value.Findings == nil || len(acquired.Value.Findings.Messages) != 1 || acquired.Value.Findings.Messages[0].Severity != commandkit.SeverityWarning {
|
||||
t.Fatalf("failure evidence = %#v", acquired.Value)
|
||||
}
|
||||
if acquired.Explanation.Message != "" || len(acquired.Explanation.Details) != 1 {
|
||||
t.Fatalf("failure explanation = %#v", acquired.Explanation)
|
||||
}
|
||||
var warning, terminal bytes.Buffer
|
||||
if err := acquired.Diagnostics[0].Write(&warning); err != nil {
|
||||
if err := acquired.Value.Findings.Messages[0].Write(&warning); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := acquired.Explanation.Details[0](&terminal); err != nil {
|
||||
@@ -174,7 +175,7 @@ func TestFromConfigKitRetainsLoadErrorAndDiagnostics(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromConfigKitPreservesValueAndDiagnosticsAlongsideError(t *testing.T) {
|
||||
func TestFromConfigKitDoesNotExposeResultFromFailedLoad(t *testing.T) {
|
||||
result, err := adapterSettingsLoad(configkit.Mapping("partial source", map[string]any{"greeting": "Hello"}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -188,11 +189,8 @@ func TestFromConfigKitPreservesValueAndDiagnosticsAlongsideError(t *testing.T) {
|
||||
if gotErr != loadErr {
|
||||
t.Fatalf("load error identity = %v, want %v", gotErr, loadErr)
|
||||
}
|
||||
if acquired.Value.Effective != result || acquired.Value.Sources != result || acquired.Value.Explanation != result {
|
||||
t.Fatalf("acquired value facets were lost: %#v", acquired.Value)
|
||||
}
|
||||
if len(acquired.Diagnostics) != 1 || acquired.Diagnostics[0].Severity != commandkit.SeverityWarning {
|
||||
t.Fatalf("independent diagnostics = %#v", acquired.Diagnostics)
|
||||
if acquired.Value.Effective != nil || acquired.Value.Metadata != nil || acquired.Value.Sources != nil || acquired.Value.Explanation != nil || acquired.Value.Findings != nil {
|
||||
t.Fatalf("failed load exposed result facets: %#v", acquired.Value)
|
||||
}
|
||||
if len(acquired.Explanation.Details) != 0 {
|
||||
t.Fatalf("warning-only result acquired terminal context: %#v", acquired.Explanation)
|
||||
@@ -274,3 +272,23 @@ func (shortWriter) Write(value []byte) (int, error) { return len(value) - 1, nil
|
||||
type failingWriter struct{ err error }
|
||||
|
||||
func (w failingWriter) Write([]byte) (int, error) { return 0, w.err }
|
||||
|
||||
func TestFromConfigKitUsesFailureSnapshotInsteadOfReturnedResult(t *testing.T) {
|
||||
result, err := adapterSettingsLoad(configkit.Mapping("successful", map[string]any{"greeting": "Hello"}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, failure := configkit.Load[map[string]any](configkit.Bytes("failed", []byte("broken: [")))
|
||||
var snapshot *configkit.LoadError
|
||||
if !errors.As(failure, &snapshot) {
|
||||
t.Fatalf("load failure: %v", failure)
|
||||
}
|
||||
wrapped := fmt.Errorf("loading: %w", failure)
|
||||
scope := FromConfigKit[struct{}, struct{}, adapterSettings]("app", "", func(context.Context, Selection, struct{}, struct{}) (*configkit.Result[adapterSettings], error) {
|
||||
return result, wrapped
|
||||
})
|
||||
acquired, gotErr := scope.Acquire(context.Background(), Request{}, struct{}{}, struct{}{})
|
||||
if !errors.Is(gotErr, failure) || acquired.Value.Effective != nil || acquired.Value.Metadata != nil || acquired.Value.Explanation != nil || acquired.Value.Sources == nil || acquired.Value.Findings == nil || !reflect.DeepEqual(acquired.Value.Sources.Sources(), snapshot.Sources()) || !reflect.DeepEqual(acquired.Value.Findings.Records, snapshot.Diagnostics()) || len(acquired.Diagnostics) != 0 {
|
||||
t.Fatalf("failed acquisition = %#v, %v", acquired, gotErr)
|
||||
}
|
||||
}
|
||||
|
||||
104
integrations/ckconfig/detailed_diff_test.go
Normal file
104
integrations/ckconfig/detailed_diff_test.go
Normal file
@@ -0,0 +1,104 @@
|
||||
package ckconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestDetailedDiffPreservesNativeEvidenceAndAssertions(t *testing.T) {
|
||||
values := []configkit.Difference{
|
||||
{Path: configkit.Keys("added"), Right: configkit.ValueSnapshot{Present: true, YAML: "null\n"}},
|
||||
{Path: configkit.Keys("removed"), Left: configkit.ValueSnapshot{Present: true, YAML: "false\n"}},
|
||||
{Path: configkit.Keys("secret"), Left: configkit.ValueSnapshot{Present: true, Redacted: true, YAML: "'***'\n"}, Right: configkit.ValueSnapshot{Present: true, Redacted: true, YAML: "'***'\n"}, HiddenChanged: true},
|
||||
{Path: configkit.Keys("list"), Left: configkit.ValueSnapshot{Present: true, YAML: "[one, two]\n"}, Right: configkit.ValueSnapshot{Present: true, YAML: "[three]\n"}},
|
||||
{Path: configkit.Keys("marker"), Left: configkit.ValueSnapshot{Present: true, YAML: "'redacted'\n"}, Right: configkit.ValueSnapshot{Present: true, YAML: "'***'\n"}},
|
||||
}
|
||||
calls := 0
|
||||
scope := Scope[struct{}, struct{}]{Name: "app", Operations: []Operation{Diff}, Compare: func(context.Context, ComparisonRequest[struct{}], struct{}) (commandkit.Acquired[[]configkit.Difference], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[[]configkit.Difference]{Value: values}, nil
|
||||
}}
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
for _, format := range []string{"json", "yaml", "text"} {
|
||||
var out bytes.Buffer
|
||||
result := app.Execute(context.Background(), []string{"config", "diff", "--details", "--check", "--format=" + format}, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
var logical any
|
||||
var err error
|
||||
if format == "json" {
|
||||
err = json.Unmarshal(out.Bytes(), &logical)
|
||||
} else {
|
||||
logical, err = commandkit.DecodeYAMLReport(&out)
|
||||
}
|
||||
if result.Kind != commandkit.OutcomeDomain || result.Status != 3 || err != nil {
|
||||
t.Fatalf("format %s = %#v %v %q", format, result, err, out.String())
|
||||
}
|
||||
report := logical.(map[string]any)
|
||||
entries := report["differences"].([]any)
|
||||
if report["scope"] != "app" || len(entries) != len(values) {
|
||||
t.Fatalf("format %s report %#v", format, report)
|
||||
}
|
||||
added := entries[0].(map[string]any)
|
||||
before, after := added["before"].(map[string]any), added["after"].(map[string]any)
|
||||
if before["present"] != false || before["value"] != nil || after["present"] != true || after["value"] != nil {
|
||||
t.Fatalf("null/absence: %#v", added)
|
||||
}
|
||||
secret := entries[2].(map[string]any)
|
||||
if secret["hidden_changed"] != true || !reflect.DeepEqual(secret["before"].(map[string]any)["value"], secret["after"].(map[string]any)["value"]) {
|
||||
t.Fatalf("hidden change: %#v", secret)
|
||||
}
|
||||
list := entries[3].(map[string]any)["after"].(map[string]any)["value"]
|
||||
if !reflect.DeepEqual(list, []any{"three"}) {
|
||||
t.Fatalf("atomic sequence: %#v", list)
|
||||
}
|
||||
marker := entries[4].(map[string]any)["after"].(map[string]any)
|
||||
if marker["value"] != "***" || marker["redacted"] != false {
|
||||
t.Fatalf("marker string: %#v", marker)
|
||||
}
|
||||
}
|
||||
if calls != 3 {
|
||||
t.Fatalf("provider calls=%d", calls)
|
||||
}
|
||||
result := app.Execute(context.Background(), []string{"config", "diff"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || calls != 4 {
|
||||
t.Fatalf("ordinary diff: %#v calls=%d", result, calls)
|
||||
}
|
||||
values = nil
|
||||
var out bytes.Buffer
|
||||
result = app.Execute(context.Background(), []string{"config", "diff", "--check", "--details", "--format=json"}, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || !strings.Contains(out.String(), `"differences": []`) {
|
||||
t.Fatalf("equality: %#v %q", result, out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiffAssertionRetainsDomainOutcomeOnDeliveryFailures(t *testing.T) {
|
||||
values := []configkit.Difference{{Path: configkit.Keys("x"), Right: configkit.ValueSnapshot{Present: true, YAML: "true\n"}}}
|
||||
cause := errors.New("provider failed")
|
||||
var providerErr error
|
||||
scope := Scope[struct{}, struct{}]{Name: "app", Operations: []Operation{Diff}, Compare: func(context.Context, ComparisonRequest[struct{}], struct{}) (commandkit.Acquired[[]configkit.Difference], error) {
|
||||
return commandkit.Acquired[[]configkit.Difference]{Value: values}, providerErr
|
||||
}}
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
result := app.Execute(context.Background(), []string{"config", "diff", "--check", "--details"}, commandkit.Streams{Out: shortWriter{}, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeDomain || result.Status != 3 || result.Presentation.Output.State != commandkit.DeliveryIncomplete {
|
||||
t.Fatalf("writer failure: %#v", result)
|
||||
}
|
||||
values[0].Right.YAML = "[invalid"
|
||||
result = app.Execute(context.Background(), []string{"config", "diff", "--check", "--details"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeDomain || result.Status != 3 || result.Presentation.Output.RenderError == nil {
|
||||
t.Fatalf("render failure: %#v", result)
|
||||
}
|
||||
providerErr = cause
|
||||
result = app.Execute(context.Background(), []string{"config", "diff", "--check"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeOperational || !errors.Is(result.Cause, cause) {
|
||||
t.Fatalf("provider failure: %#v", result)
|
||||
}
|
||||
}
|
||||
136
integrations/ckconfig/detailed_validation_test.go
Normal file
136
integrations/ckconfig/detailed_validation_test.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package ckconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func validationDiagnostic(message string) commandkit.Diagnostic {
|
||||
return commandkit.Diagnostic{Severity: commandkit.SeverityWarning, Write: func(w io.Writer) error { _, err := io.WriteString(w, message+"\n"); return err }}
|
||||
}
|
||||
|
||||
func TestDetailedValidationFiltersAndRetainsFailureEvidence(t *testing.T) {
|
||||
cause := errors.New("second scope failed")
|
||||
calls := []string{}
|
||||
reader := &sourceInventory{values: []configkit.SourceInfo{{ID: "primary", Label: "main", Path: "main.yml"}, {ID: "related", Label: "included", Path: "include.yml"}, {ID: "unused", Label: "unused"}}}
|
||||
records := []configkit.Diagnostic{
|
||||
{Code: "chosen", Severity: configkit.SeverityWarning, Path: configkit.Keys("a/b"), Message: "selected warning", Primary: &configkit.Location{SourceID: "primary", Line: 2, Column: 3}, Related: []configkit.Location{{SourceID: "related", Line: 7, Column: 8}}},
|
||||
{Code: "other", Severity: configkit.SeverityWarning, Path: configkit.Keys("other"), Message: "other warning"},
|
||||
}
|
||||
scopes := []Scope[struct{}, struct{}]{
|
||||
{Name: "app", Operations: []Operation{Validate}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls = append(calls, "app")
|
||||
return commandkit.Acquired[View]{Value: View{Sources: reader, Findings: &Findings{Records: records, Messages: []commandkit.Diagnostic{validationDiagnostic("native warnings")}}}, Diagnostics: []commandkit.Diagnostic{validationDiagnostic("application warning")}}, nil
|
||||
}},
|
||||
{Name: "second", Operations: []Operation{Validate}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls = append(calls, "second")
|
||||
return commandkit.Acquired[View]{Value: View{Findings: &Findings{Records: []configkit.Diagnostic{{Code: "failed", Severity: configkit.SeverityError, Message: "failed finding"}}}}, Explanation: commandkit.Explanation{Message: "terminal failure"}}, cause
|
||||
}},
|
||||
{Name: "third", Operations: []Operation{Validate}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls = append(calls, "third")
|
||||
return commandkit.Acquired[View]{}, nil
|
||||
}},
|
||||
}
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: scopes}))
|
||||
var out, diag bytes.Buffer
|
||||
result := app.Execute(context.Background(), []string{"config", "validate", "--scope=all", "--details", "--severity=warning", "--code=chosen", "--format=json", "--verbose"}, commandkit.Streams{Out: &out, Err: &diag})
|
||||
decoder := json.NewDecoder(&out)
|
||||
var report validationReport
|
||||
if err := decoder.Decode(&report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
t.Fatalf("extra JSON: %v", err)
|
||||
}
|
||||
if !errors.Is(result.Cause, cause) || result.Kind != commandkit.OutcomeOperational || len(calls) != 2 || calls[0] != "app" || calls[1] != "second" || len(report.Scopes) != 2 || report.Scopes[0].Outcome != "valid" || report.Scopes[1].Outcome != "failed" {
|
||||
t.Fatalf("result=%#v calls=%v report=%#v", result, calls, report)
|
||||
}
|
||||
first, second := report.Scopes[0].Details, report.Scopes[1].Details
|
||||
if first == nil || first.State != "present" || len(first.Findings) != 1 || first.Findings[0].Path != "/a~1b" || len(first.Sources) != 2 || first.Sources[0].ID != "primary" || first.Sources[1].ID != "related" || second == nil || second.State != "filtered" || len(second.Findings) != 0 {
|
||||
t.Fatalf("details=%#v %#v", first, second)
|
||||
}
|
||||
if strings.Contains(diag.String(), "native warnings") || !strings.Contains(diag.String(), "application warning") || !strings.Contains(diag.String(), "terminal failure") {
|
||||
t.Fatalf("diagnostics=%q", diag.String())
|
||||
}
|
||||
before := len(calls)
|
||||
for _, args := range [][]string{{"--severity=warning"}, {"--code=x"}, {"--details", "--severity=unknown"}} {
|
||||
result = app.Execute(context.Background(), append([]string{"config", "validate"}, args...), commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeUsage || len(calls) != before {
|
||||
t.Fatalf("invalid %v: %#v", args, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidationCancellationAndDeliveryRetainReachedScopes(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
calls := 0
|
||||
scopes := []Scope[struct{}, struct{}]{
|
||||
{Name: "app", Operations: []Operation{Validate}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[View]{Value: View{Findings: &Findings{}}}, nil
|
||||
}},
|
||||
{Name: "second", Operations: []Operation{Validate}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls++
|
||||
cancel()
|
||||
return commandkit.Acquired[View]{}, nil
|
||||
}},
|
||||
{Name: "third", Operations: []Operation{Validate}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[View]{}, nil
|
||||
}},
|
||||
}
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: scopes}))
|
||||
var out bytes.Buffer
|
||||
result := app.Execute(ctx, []string{"config", "validate", "--scope=all", "--details", "--format=json"}, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
var report validationReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !errors.Is(result.Cause, context.Canceled) || calls != 2 || len(report.Scopes) != 2 || report.Scopes[0].Details.State != "empty" || report.Scopes[1].Details.State != "unavailable" || report.Scopes[1].Outcome != "canceled" {
|
||||
t.Fatalf("result=%#v calls=%d report=%#v", result, calls, report)
|
||||
}
|
||||
failure := errors.New("load failure")
|
||||
scope := Scope[struct{}, struct{}]{Name: "app", Operations: []Operation{Validate}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
return commandkit.Acquired[View]{}, failure
|
||||
}}
|
||||
app = newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
result = app.Execute(context.Background(), []string{"config", "validate", "--details"}, commandkit.Streams{Out: shortWriter{}, Err: io.Discard})
|
||||
if !errors.Is(result.Cause, failure) || result.Presentation.Output.State != commandkit.DeliveryIncomplete {
|
||||
t.Fatalf("failure and delivery: %#v", result)
|
||||
}
|
||||
out.Reset()
|
||||
result = app.Execute(context.Background(), []string{"config", "validate", "--details", "--quiet"}, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
if !errors.Is(result.Cause, failure) || out.Len() != 0 {
|
||||
t.Fatalf("quiet failure: %#v %q", result, out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetailedValidationReportsNativeLoadError(t *testing.T) {
|
||||
_, failure := configkit.Load[map[string]any](configkit.Bytes("invalid source", []byte("invalid: [")))
|
||||
var native *configkit.LoadError
|
||||
if !errors.As(failure, &native) {
|
||||
t.Fatalf("fixture: %v", failure)
|
||||
}
|
||||
scope := FromConfigKit("app", "", func(context.Context, Selection, struct{}, struct{}) (*configkit.Result[map[string]any], error) {
|
||||
return nil, failure
|
||||
})
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
var out bytes.Buffer
|
||||
result := app.Execute(context.Background(), []string{"config", "validate", "--details", "--format=json"}, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
var report validationReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !errors.Is(result.Cause, failure) || len(report.Scopes) != 1 || report.Scopes[0].Outcome != "failed" || report.Scopes[0].Details.State != "present" || len(report.Scopes[0].Details.Findings) != len(native.Diagnostics()) {
|
||||
t.Fatalf("native failure: %#v %q", result, out.String())
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,14 @@ func runConfigDiff[I, S any](invocation commandkit.Invocation, plan *configOpera
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return configFailure("Configuration comparison was canceled.", acquired.Explanation, err)
|
||||
}
|
||||
return renderPreparedConfigReport(invocation, acquired.Explanation, func() ([]byte, error) {
|
||||
outcome := renderPreparedConfigReport(invocation, acquired.Explanation, func() (any, error) {
|
||||
if plan.details {
|
||||
return renderDetailedDiff(selected.scope.scope.Name, acquired.Value)
|
||||
}
|
||||
return renderDiffReport(acquired.Value)
|
||||
})
|
||||
if outcome.Kind == commandkit.OutcomeSuccess && plan.check && len(acquired.Value) > 0 {
|
||||
return commandkit.Domain("configuration differences", 3)
|
||||
}
|
||||
return outcome
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
func TestConfigDiffExecutesWithDefaultAndExplicitYAMLAndInheritedSelections(t *testing.T) {
|
||||
func TestConfigDiffExecutesWithDefaultAndExplicitYAMLAndIndependentSelections(t *testing.T) {
|
||||
type settings struct {
|
||||
Greeting string `yaml:"greeting"`
|
||||
}
|
||||
@@ -32,7 +32,7 @@ func TestConfigDiffExecutesWithDefaultAndExplicitYAMLAndInheritedSelections(t *t
|
||||
if outcome.Kind != commandkit.OutcomeSuccess {
|
||||
t.Fatalf("default YAML comparison outcome = %#v", outcome)
|
||||
}
|
||||
if len(selections) != 2 || !selections[0].Config.Set || selections[0].Config.Value != "before.yml" || !selections[1].Config.Set || selections[1].Config.Value != "after.yml" || selections[1].Overlay != selections[0].Overlay {
|
||||
if len(selections) != 2 || !selections[0].Config.Set || selections[0].Config.Value != "before.yml" || !selections[1].Config.Set || selections[1].Config.Value != "after.yml" || selections[1].Overlay.Set {
|
||||
t.Fatalf("comparison selections = %#v", selections)
|
||||
}
|
||||
var document yaml.Node
|
||||
@@ -60,7 +60,7 @@ func TestConfigDiffExecutesWithDefaultAndExplicitYAMLAndInheritedSelections(t *t
|
||||
loadsBeforeText := len(selections)
|
||||
output.Reset()
|
||||
outcome = app.Execute(context.Background(), []string{"config", "diff", "--format", "text"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
if outcome.Kind != commandkit.OutcomeUsage || len(selections) != loadsBeforeText || output.Len() != 0 {
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || len(selections) != loadsBeforeText+2 || !strings.Contains(output.String(), "deletions:") {
|
||||
t.Fatalf("text format outcome/work/output = %#v / %d / %q", outcome, len(selections)-loadsBeforeText, output.String())
|
||||
}
|
||||
}
|
||||
@@ -256,7 +256,7 @@ func TestConfigDiffRepeatedInvocationsPrepareFreshInputsAndState(t *testing.T) {
|
||||
if len(observed) != 2 || observed[0].left.ID == observed[0].right.ID || observed[1].left.ID == observed[1].right.ID || observed[0].left.ID == observed[1].left.ID || observed[0].right.ID == observed[1].right.ID {
|
||||
t.Fatalf("input instances were reused: %#v", observed)
|
||||
}
|
||||
if observed[0].left.Label != "current" || observed[0].right.Label != "current" || observed[1].left.Label != "current" || observed[1].right.Label != "current" {
|
||||
if observed[0].left.Label != "current" || observed[0].right.Label != "" || observed[1].left.Label != "current" || observed[1].right.Label != "" {
|
||||
t.Fatalf("comparison inputs missed captured flag values: %#v", observed)
|
||||
}
|
||||
if observed[0].state == nil || observed[1].state == nil || observed[0].state == observed[1].state || observed[0].state.ID != 1 || observed[1].state.ID != 2 {
|
||||
|
||||
@@ -1,26 +1,13 @@
|
||||
package ckconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
func decodeSafeSnapshot(snapshot string) (*yaml.Node, error) {
|
||||
var document yaml.Node
|
||||
decoder := yaml.NewDecoder(strings.NewReader(snapshot))
|
||||
if err := decoder.Decode(&document); err != nil {
|
||||
return nil, fmt.Errorf("decode safe YAML snapshot: %w", err)
|
||||
}
|
||||
if document.Kind != yaml.DocumentNode || len(document.Content) == 0 {
|
||||
return nil, fmt.Errorf("decode safe YAML snapshot: document has no value")
|
||||
}
|
||||
return document.Content[0], nil
|
||||
}
|
||||
|
||||
func decodeJSONPointer(pointer string) ([]string, error) {
|
||||
if pointer == "" {
|
||||
return nil, nil
|
||||
@@ -56,139 +43,114 @@ func decodeJSONPointer(pointer string) ([]string, error) {
|
||||
return parts, nil
|
||||
}
|
||||
|
||||
// yamlValuePlacer indexes each mapping once while assembling one report.
|
||||
// Content remains the ordered representation used by the YAML encoder.
|
||||
type yamlValuePlacer struct {
|
||||
keys map[*yaml.Node]map[string]int
|
||||
}
|
||||
|
||||
func (placer *yamlValuePlacer) placeValue(category *yaml.Node, path []string, value *yaml.Node) (*yaml.Node, error) {
|
||||
if value == nil {
|
||||
return nil, fmt.Errorf("place YAML value: value node is nil")
|
||||
}
|
||||
func placeReportValue(root any, path []string, value any) (any, error) {
|
||||
if len(path) == 0 {
|
||||
return value, nil
|
||||
}
|
||||
if category == nil || category.Kind != yaml.MappingNode {
|
||||
return nil, fmt.Errorf("place YAML value at %q: category ancestor is not a mapping", pointerFromTokens(path[:1]))
|
||||
current, ok := root.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("report path ancestor is not a mapping")
|
||||
}
|
||||
|
||||
current := category
|
||||
for index, token := range path {
|
||||
keys := placer.mappingKeys(current)
|
||||
keyIndex, exists := keys[token]
|
||||
if index == len(path)-1 {
|
||||
if exists {
|
||||
current.Content[keyIndex+1] = value
|
||||
} else {
|
||||
keys[token] = len(current.Content)
|
||||
current.Content = append(current.Content, stringKey(token), value)
|
||||
}
|
||||
return category, nil
|
||||
current[token] = value
|
||||
return root, nil
|
||||
}
|
||||
|
||||
child, exists := current[token]
|
||||
if !exists {
|
||||
child := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
|
||||
keys[token] = len(current.Content)
|
||||
current.Content = append(current.Content, stringKey(token), child)
|
||||
current = child
|
||||
next := make(map[string]any)
|
||||
current[token] = next
|
||||
current = next
|
||||
continue
|
||||
}
|
||||
|
||||
child := current.Content[keyIndex+1]
|
||||
if child.Kind != yaml.MappingNode {
|
||||
return nil, fmt.Errorf("place YAML value at %q: ancestor %q is not a mapping", pointerFromTokens(path), pointerFromTokens(path[:index+1]))
|
||||
next, ok := child.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("report path ancestor %q is not a mapping", token)
|
||||
}
|
||||
current = child
|
||||
current = next
|
||||
}
|
||||
return category, nil
|
||||
return root, nil
|
||||
}
|
||||
|
||||
func (placer *yamlValuePlacer) mappingKeys(mapping *yaml.Node) map[string]int {
|
||||
if keys, exists := placer.keys[mapping]; exists {
|
||||
return keys
|
||||
}
|
||||
if placer.keys == nil {
|
||||
placer.keys = make(map[*yaml.Node]map[string]int)
|
||||
}
|
||||
keys := make(map[string]int, len(mapping.Content)/2)
|
||||
for index := 0; index+1 < len(mapping.Content); index += 2 {
|
||||
candidate := mapping.Content[index]
|
||||
if candidate.Kind == yaml.ScalarNode && candidate.Tag == "!!str" {
|
||||
if _, exists := keys[candidate.Value]; !exists {
|
||||
keys[candidate.Value] = index
|
||||
}
|
||||
type diffReport struct {
|
||||
Additions any `json:"additions"`
|
||||
Changes any `json:"changes"`
|
||||
Deletions []string `json:"deletions"`
|
||||
}
|
||||
|
||||
type detailedDiffReport struct {
|
||||
Scope string `json:"scope"`
|
||||
Differences []detailedDifference `json:"differences"`
|
||||
}
|
||||
|
||||
type detailedDifference struct {
|
||||
Path string `json:"path"`
|
||||
Before detailedDiffSnapshot `json:"before"`
|
||||
After detailedDiffSnapshot `json:"after"`
|
||||
HiddenChanged bool `json:"hidden_changed"`
|
||||
}
|
||||
|
||||
type detailedDiffSnapshot struct {
|
||||
Present bool `json:"present"`
|
||||
Redacted bool `json:"redacted"`
|
||||
Value any `json:"value"`
|
||||
}
|
||||
|
||||
func renderDetailedDiff(scope string, differences []configkit.Difference) (any, error) {
|
||||
report := detailedDiffReport{Scope: scope, Differences: make([]detailedDifference, 0, len(differences))}
|
||||
for _, difference := range differences {
|
||||
before, err := detailedSnapshot(difference.Left)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("difference at %q before: %w", difference.Path.String(), err)
|
||||
}
|
||||
after, err := detailedSnapshot(difference.Right)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("difference at %q after: %w", difference.Path.String(), err)
|
||||
}
|
||||
report.Differences = append(report.Differences, detailedDifference{Path: difference.Path.String(), Before: before, After: after, HiddenChanged: difference.HiddenChanged})
|
||||
}
|
||||
placer.keys[mapping] = keys
|
||||
return keys
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func stringKey(value string) *yaml.Node {
|
||||
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: value}
|
||||
func detailedSnapshot(snapshot configkit.ValueSnapshot) (detailedDiffSnapshot, error) {
|
||||
report := detailedDiffSnapshot{Present: snapshot.Present, Redacted: snapshot.Redacted}
|
||||
if snapshot.Present {
|
||||
value, err := commandkit.DecodeYAMLReport(strings.NewReader(snapshot.YAML))
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
report.Value = value
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func pointerFromTokens(tokens []string) string {
|
||||
if len(tokens) == 0 {
|
||||
return ""
|
||||
}
|
||||
var pointer strings.Builder
|
||||
for _, token := range tokens {
|
||||
pointer.WriteByte('/')
|
||||
pointer.WriteString(strings.ReplaceAll(strings.ReplaceAll(token, "~", "~0"), "/", "~1"))
|
||||
}
|
||||
return pointer.String()
|
||||
}
|
||||
|
||||
func renderDiffReport(differences []configkit.Difference) ([]byte, error) {
|
||||
var placer yamlValuePlacer
|
||||
additions := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
|
||||
changes := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
|
||||
deletions := &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq"}
|
||||
|
||||
func renderDiffReport(differences []configkit.Difference) (any, error) {
|
||||
report := diffReport{Additions: map[string]any{}, Changes: map[string]any{}, Deletions: []string{}}
|
||||
for _, difference := range differences {
|
||||
path := difference.Path.String()
|
||||
switch {
|
||||
case !difference.Left.Present && difference.Right.Present:
|
||||
tokens, err := decodeJSONPointer(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render addition at %q: %w", path, err)
|
||||
}
|
||||
value, err := decodeSafeSnapshot(difference.Right.YAML)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render addition at %q: %w", path, err)
|
||||
}
|
||||
additions, err = placer.placeValue(additions, tokens, value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render addition at %q: %w", path, err)
|
||||
}
|
||||
case difference.Left.Present && difference.Right.Present:
|
||||
tokens, err := decodeJSONPointer(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render change at %q: %w", path, err)
|
||||
}
|
||||
value, err := decodeSafeSnapshot(difference.Right.YAML)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render change at %q: %w", path, err)
|
||||
}
|
||||
changes, err = placer.placeValue(changes, tokens, value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render change at %q: %w", path, err)
|
||||
}
|
||||
case difference.Left.Present && !difference.Right.Present:
|
||||
deletions.Content = append(deletions.Content, stringKey(path))
|
||||
if difference.Left.Present && !difference.Right.Present {
|
||||
report.Deletions = append(report.Deletions, path)
|
||||
continue
|
||||
}
|
||||
if !difference.Right.Present {
|
||||
continue
|
||||
}
|
||||
tokens, err := decodeJSONPointer(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("difference at %q: %w", path, err)
|
||||
}
|
||||
value, err := commandkit.DecodeYAMLReport(strings.NewReader(difference.Right.YAML))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("difference at %q: %w", path, err)
|
||||
}
|
||||
if difference.Left.Present {
|
||||
report.Changes, err = placeReportValue(report.Changes, tokens, value)
|
||||
} else {
|
||||
report.Additions, err = placeReportValue(report.Additions, tokens, value)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("difference at %q: %w", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
root := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{
|
||||
stringKey("additions"), additions,
|
||||
stringKey("changes"), changes,
|
||||
stringKey("deletions"), deletions,
|
||||
}}
|
||||
document := &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{root}}
|
||||
var output bytes.Buffer
|
||||
if err := encodeYAML(&output, document); err != nil {
|
||||
return nil, fmt.Errorf("encode configuration diff report: %w", err)
|
||||
}
|
||||
return output.Bytes(), nil
|
||||
return report, nil
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@ package ckconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
@@ -16,11 +16,16 @@ func renderAndDecode(t *testing.T, differences []configkit.Difference) (*yaml.No
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var rendered bytes.Buffer
|
||||
if err := commandkit.RenderReport(&rendered, commandkit.Report{Value: report}, commandkit.FormatYAML); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := rendered.Bytes()
|
||||
var document yaml.Node
|
||||
if err := yaml.Unmarshal(report, &document); err != nil {
|
||||
if err := yaml.Unmarshal(data, &document); err != nil {
|
||||
t.Fatalf("decode rendered report %q: %v", report, err)
|
||||
}
|
||||
return document.Content[0], report
|
||||
return document.Content[0], data
|
||||
}
|
||||
|
||||
func reportField(mapping *yaml.Node, key string) *yaml.Node {
|
||||
@@ -43,18 +48,12 @@ func TestRenderDiffReportClassifiesAndOrdersNativeRecords(t *testing.T) {
|
||||
if root.Kind != yaml.MappingNode || len(root.Content) != 6 {
|
||||
t.Fatalf("report root = %#v", root)
|
||||
}
|
||||
if got := []string{root.Content[0].Value, root.Content[2].Value, root.Content[4].Value}; !reflect.DeepEqual(got, []string{"additions", "changes", "deletions"}) {
|
||||
t.Fatalf("report category order = %#v", got)
|
||||
}
|
||||
additions := reportField(root, "additions")
|
||||
if additions.Kind != yaml.MappingNode || additions.Content[0].Value != "z-added" || additions.Content[2].Value != "a-added" {
|
||||
t.Fatalf("addition order/value = %#v", additions)
|
||||
if value := reportField(additions, "z-added"); value == nil || value.Tag != "!!bool" || value.Value != "false" {
|
||||
t.Fatalf("boolean addition = %#v", value)
|
||||
}
|
||||
if additions.Content[1].Kind != yaml.ScalarNode || additions.Content[1].Tag != "!!bool" || additions.Content[1].Value != "false" {
|
||||
t.Fatalf("boolean addition lost its type: %#v", additions.Content[1])
|
||||
}
|
||||
if additions.Content[3].Tag != "!!str" || additions.Content[3].Value != "123" {
|
||||
t.Fatalf("numeric-looking string lost its type: %#v", additions.Content[3])
|
||||
if value := reportField(additions, "a-added"); value == nil || value.Tag != "!!str" || value.Value != "123" {
|
||||
t.Fatalf("string addition = %#v", value)
|
||||
}
|
||||
changes := reportField(root, "changes")
|
||||
if changes.Kind != yaml.MappingNode || changes.Content[1].Tag != "!!int" || changes.Content[1].Value != "9007199254740993" {
|
||||
@@ -68,9 +67,6 @@ func TestRenderDiffReportClassifiesAndOrdersNativeRecords(t *testing.T) {
|
||||
|
||||
func TestRenderDiffReportEmitsEmptyCategoriesAndRootValue(t *testing.T) {
|
||||
root, _ := renderAndDecode(t, nil)
|
||||
if got := []string{root.Content[0].Value, root.Content[2].Value, root.Content[4].Value}; !reflect.DeepEqual(got, []string{"additions", "changes", "deletions"}) {
|
||||
t.Fatalf("empty report keys = %#v", got)
|
||||
}
|
||||
if reportField(root, "additions").Kind != yaml.MappingNode || len(reportField(root, "additions").Content) != 0 || reportField(root, "changes").Kind != yaml.MappingNode || len(reportField(root, "changes").Content) != 0 || reportField(root, "deletions").Kind != yaml.SequenceNode || len(reportField(root, "deletions").Content) != 0 {
|
||||
t.Fatalf("empty report categories = %#v", root)
|
||||
}
|
||||
|
||||
@@ -2,49 +2,9 @@ package ckconfig
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
func TestDecodeSafeSnapshotPreservesYAMLTypes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
text string
|
||||
kind yaml.Kind
|
||||
tag string
|
||||
value string
|
||||
}{
|
||||
{name: "null", text: "null\n", kind: yaml.ScalarNode, tag: "!!null", value: "null"},
|
||||
{name: "boolean", text: "true\n", kind: yaml.ScalarNode, tag: "!!bool", value: "true"},
|
||||
{name: "large integer", text: "9007199254740993\n", kind: yaml.ScalarNode, tag: "!!int", value: "9007199254740993"},
|
||||
{name: "numeric string", text: "'123'\n", kind: yaml.ScalarNode, tag: "!!str", value: "123"},
|
||||
{name: "boolean-like string", text: "'false'\n", kind: yaml.ScalarNode, tag: "!!str", value: "false"},
|
||||
{name: "empty mapping", text: "{}\n", kind: yaml.MappingNode, tag: "!!map"},
|
||||
{name: "empty sequence", text: "[]\n", kind: yaml.SequenceNode, tag: "!!seq"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
node, err := decodeSafeSnapshot(test.text)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if node.Kind != test.kind || node.Tag != test.tag || node.Value != test.value {
|
||||
t.Fatalf("node kind/tag/value = %v/%q/%q, want %v/%q/%q", node.Kind, node.Tag, node.Value, test.kind, test.tag, test.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
nested, err := decodeSafeSnapshot("items:\n - name: example\n enabled: false\n")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if nested.Kind != yaml.MappingNode || nested.Content[1].Kind != yaml.SequenceNode || nested.Content[1].Content[0].Content[3].Tag != "!!bool" {
|
||||
t.Fatalf("nested collection/scalar tags were not preserved: %#v", nested)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONPointerPreservesSemanticTokens(t *testing.T) {
|
||||
tests := []struct {
|
||||
pointer string
|
||||
@@ -73,74 +33,25 @@ func TestDecodeJSONPointerPreservesSemanticTokens(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaceYAMLValueBuildsOrderedSemanticMappings(t *testing.T) {
|
||||
var placer yamlValuePlacer
|
||||
category := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
|
||||
paths := [][]string{
|
||||
{"parent", "0", "dot.name", "50%"},
|
||||
{"parent", "second"},
|
||||
{"a/b", "~1"},
|
||||
{""},
|
||||
}
|
||||
for index, path := range paths {
|
||||
value := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: string(rune('a' + index))}
|
||||
updated, err := placer.placeValue(category, path, value)
|
||||
if err != nil {
|
||||
t.Fatalf("place %q: %v", pointerFromTokens(path), err)
|
||||
}
|
||||
category = updated
|
||||
}
|
||||
|
||||
if len(category.Content) != 6 || category.Content[0].Value != "parent" || category.Content[2].Value != "a/b" || category.Content[4].Value != "" {
|
||||
t.Fatalf("mapping insertion order or empty key = %#v", category.Content)
|
||||
}
|
||||
parent := category.Content[1]
|
||||
if parent.Kind != yaml.MappingNode || len(parent.Content) != 4 || parent.Content[0].Value != "0" || parent.Content[2].Value != "second" {
|
||||
t.Fatalf("nested shared ancestor/order = %#v", parent)
|
||||
}
|
||||
numeric := parent.Content[1]
|
||||
dotted := numeric.Content[1]
|
||||
if numeric.Kind != yaml.MappingNode || numeric.Content[0].Value != "dot.name" || dotted.Kind != yaml.MappingNode || dotted.Content[0].Value != "50%" {
|
||||
t.Fatalf("semantic tokens were changed: numeric=%#v dotted=%#v", numeric, dotted)
|
||||
}
|
||||
if category.Content[1].Content[0].Tag != "!!str" || category.Content[2].Tag != "!!str" || category.Content[4].Tag != "!!str" {
|
||||
t.Fatal("mapping keys are not explicitly tagged as YAML strings")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaceYAMLValueHandlesRootAndEmptyKey(t *testing.T) {
|
||||
var placer yamlValuePlacer
|
||||
category := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
|
||||
root := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!null", Value: "null"}
|
||||
updated, err := placer.placeValue(category, nil, root)
|
||||
if err != nil || updated != root {
|
||||
t.Fatalf("root placement = %#v, %v", updated, err)
|
||||
}
|
||||
|
||||
category = &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
|
||||
value := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "empty-key"}
|
||||
updated, err = placer.placeValue(category, []string{""}, value)
|
||||
func TestPlaceReportValue(t *testing.T) {
|
||||
var root any = map[string]any{}
|
||||
var err error
|
||||
root, err = placeReportValue(root, []string{"a/b", "~1"}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if updated != category || len(category.Content) != 2 || category.Content[0].Value != "" || category.Content[0].Tag != "!!str" || category.Content[1] != value {
|
||||
t.Fatalf("slash path placement = %#v", category)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaceYAMLValueRejectsIncompatibleAncestors(t *testing.T) {
|
||||
var placer yamlValuePlacer
|
||||
category := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{
|
||||
stringKey("parent"), {Kind: yaml.ScalarNode, Tag: "!!str", Value: "leaf"},
|
||||
}}
|
||||
_, err := placer.placeValue(category, []string{"parent", "child"}, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!null", Value: "null"})
|
||||
if err == nil || !strings.Contains(err.Error(), "/parent/child") || !strings.Contains(err.Error(), "/parent") {
|
||||
t.Fatalf("incompatible ancestor error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeSafeSnapshotRejectsMalformedYAML(t *testing.T) {
|
||||
if _, err := decodeSafeSnapshot("value: [unterminated\n"); err == nil {
|
||||
t.Fatal("malformed snapshot unexpectedly decoded")
|
||||
root, err = placeReportValue(root, []string{""}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := map[string]any{"a/b": map[string]any{"~1": false}, "": nil}
|
||||
if !reflect.DeepEqual(root, want) {
|
||||
t.Fatalf("got %#v", root)
|
||||
}
|
||||
if _, err := placeReportValue(root, []string{"a/b", "~1", "child"}, 1); err == nil {
|
||||
t.Fatal("scalar ancestor accepted")
|
||||
}
|
||||
if value, err := placeReportValue(root, nil, "replacement"); err != nil || value != "replacement" {
|
||||
t.Fatalf("root: %#v, %v", value, err)
|
||||
}
|
||||
}
|
||||
|
||||
116
integrations/ckconfig/discovery_test.go
Normal file
116
integrations/ckconfig/discovery_test.go
Normal file
@@ -0,0 +1,116 @@
|
||||
package ckconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestExplainDiscoveryModesAndMetadata(t *testing.T) {
|
||||
loads, inputs, states := 0, 0, 0
|
||||
scope := FromConfigKit("app", "", func(_ context.Context, selection Selection, _, _ struct{}) (*configkit.Result[map[string]any], error) {
|
||||
loads++
|
||||
return configkit.Load(configkit.Mapping("fixture", map[string]any{"a/b": map[string]any{"x": 1}, "ab": 2, "abacus": 3, "gone": map[string]any{"x": 1}}), configkit.Options[map[string]any]{Overrides: selection.Overrides})
|
||||
})
|
||||
scope.Features.Overrides = true
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{NewInput: func() struct{} { inputs++; return struct{}{} }, NewState: func() struct{} { states++; return struct{}{} }, Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
run := func(args ...string) (commandkit.Outcome, string) {
|
||||
var out bytes.Buffer
|
||||
result := app.Execute(context.Background(), append([]string{"config", "explain"}, args...), commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
return result, out.String()
|
||||
}
|
||||
result, out := run()
|
||||
if result.Kind != commandkit.OutcomeSuccess || !strings.Contains(out, "--list") || !strings.Contains(out, "--path") || loads != 0 || inputs != 0 || states != 0 {
|
||||
t.Fatalf("bare help: %#v %q, %d/%d/%d", result, out, loads, inputs, states)
|
||||
}
|
||||
for _, args := range [][]string{{"--list", "--path=/ab"}, {"--historical"}, {"--under=/ab"}, {"--explicit=false"}, {"--path=/ab", "--under=/ab"}, {"--list", "--under=bad"}} {
|
||||
result, _ := run(args...)
|
||||
if result.Kind != commandkit.OutcomeUsage || loads != 0 || inputs != 0 || states != 0 {
|
||||
t.Fatalf("invalid %v: %#v, %d/%d/%d", args, result, loads, inputs, states)
|
||||
}
|
||||
}
|
||||
result, out = run("--list", "--under=/a~1b", "--format=json")
|
||||
var report pathDiscoveryReport
|
||||
if result.Kind != commandkit.OutcomeSuccess || json.Unmarshal([]byte(out), &report) != nil || len(report.Paths) != 2 {
|
||||
t.Fatalf("escaped subtree: %#v %q", result, out)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, entry := range report.Paths {
|
||||
seen[entry.Path] = true
|
||||
}
|
||||
if !seen["/a~1b"] || !seen["/a~1b/x"] {
|
||||
t.Fatalf("escaped paths: %#v", report.Paths)
|
||||
}
|
||||
result, out = run("--list", "--under=/ab", "--format=json")
|
||||
if result.Kind != commandkit.OutcomeSuccess || json.Unmarshal([]byte(out), &report) != nil || len(report.Paths) != 1 || report.Paths[0].Path != "/ab" {
|
||||
t.Fatalf("token boundary: %#v %q", result, out)
|
||||
}
|
||||
result, out = run("--list", "--historical", "--set=/gone=null", "--format=json")
|
||||
if result.Kind != commandkit.OutcomeSuccess || json.Unmarshal([]byte(out), &report) != nil {
|
||||
t.Fatalf("historical: %#v %q", result, out)
|
||||
}
|
||||
removed := false
|
||||
for _, entry := range report.Paths {
|
||||
if entry.Path == "/gone/x" && !entry.Present && entry.Metadata == nil {
|
||||
removed = true
|
||||
}
|
||||
}
|
||||
if !removed {
|
||||
t.Fatalf("missing historical entry: %q", out)
|
||||
}
|
||||
result, out = run("--list", "--historical", "--explicit=false", "--set=/gone=null", "--format=json")
|
||||
if result.Kind != commandkit.OutcomeSuccess || json.Unmarshal([]byte(out), &report) != nil {
|
||||
t.Fatalf("explicit filter: %#v %q", result, out)
|
||||
}
|
||||
for _, entry := range report.Paths {
|
||||
if !entry.Present || entry.Metadata == nil || entry.Metadata.Explicit {
|
||||
t.Fatalf("invalid filtered entry: %#v", entry)
|
||||
}
|
||||
}
|
||||
result, out = run("--path=", "--format=json")
|
||||
if result.Kind != commandkit.OutcomeSuccess || !strings.Contains(out, `"path": ""`) || !strings.Contains(out, `"metadata"`) {
|
||||
t.Fatalf("root explanation: %#v %q", result, out)
|
||||
}
|
||||
result, out = run("--path=/gone/x", "--set=/gone=null", "--format=json")
|
||||
if result.Kind != commandkit.OutcomeSuccess || !strings.Contains(out, `"metadata"`) || !strings.Contains(out, `"history"`) {
|
||||
t.Fatalf("historical explanation: %#v %q", result, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExplainDiscoveryCapabilityBeforeAcquisition(t *testing.T) {
|
||||
calls := 0
|
||||
scope := Scope[struct{}, struct{}]{Name: "app", Operations: []Operation{Explain}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[View]{}, nil
|
||||
}}
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
result := app.Execute(context.Background(), []string{"config", "explain", "--list"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeUsage || calls != 0 {
|
||||
t.Fatalf("unsupported discovery: %#v calls=%d", result, calls)
|
||||
}
|
||||
scope.Features.PathDiscovery = true
|
||||
app = newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
result = app.Execute(context.Background(), []string{"config", "explain", "--list"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeOperational || calls != 1 {
|
||||
t.Fatalf("missing metadata: %#v calls=%d", result, calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExplainBareHelpRecordsDeliveryFailure(t *testing.T) {
|
||||
inputs, states, calls := 0, 0, 0
|
||||
scope := Scope[struct{}, struct{}]{Name: "app", Operations: []Operation{Explain}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[View]{}, nil
|
||||
}}
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{NewInput: func() struct{} { inputs++; return struct{}{} }, NewState: func() struct{} { states++; return struct{}{} }, Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
result := app.Execute(context.Background(), []string{"config", "explain"}, commandkit.Streams{Out: shortWriter{}, Err: io.Discard})
|
||||
if result.Presentation.Output.State != commandkit.DeliveryIncomplete || inputs != 0 || states != 0 || calls != 0 {
|
||||
t.Fatalf("help delivery = %#v, input/state/acquire=%d/%d/%d", result, inputs, states, calls)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
# Simple consumer
|
||||
|
||||
This example imports `go.maximumdirect.net/ckconfig` and
|
||||
`go.maximumdirect.net/commandkit`; use the ckconfig v0.3.0 candidate with core
|
||||
`go.maximumdirect.net/commandkit`; use ckconfig v0.3.0 with core
|
||||
v0.3.0, ConfigKit v1.1.0, and Go 1.27.0. Set `GOWORK=off GOTOOLCHAIN=local`
|
||||
for the commands below.
|
||||
|
||||
@@ -11,7 +11,12 @@ Run the maintained example with:
|
||||
go run . config show
|
||||
go run . config show --config fixtures/before.yml --verbose
|
||||
go run . config show --config fixtures/before.yml --quiet
|
||||
go run . config explain --list --under /schema
|
||||
go run . config show --path /greeting --set '/greeting="Hi"'
|
||||
go run . config diff --config fixtures/before.yml --against-config fixtures/after.yml
|
||||
go run . config diff --set '/greeting="Hi"' --details --check
|
||||
go run . config validate --config fixtures/invalid.yml --details --severity error
|
||||
go run . config sources --config fixtures/invalid.yml --source-id source-1
|
||||
go run . greet
|
||||
go run . greet --count=0 --tag=first --tag second
|
||||
```
|
||||
@@ -25,3 +30,8 @@ command loads the two local fixtures and reports `changes.greeting: Goodbye`.
|
||||
The before fixture uses schema version 1, which ConfigKit reports as a provider
|
||||
warning in verbose mode. Ordinary mode hides the warning while preserving the
|
||||
effective YAML report; quiet mode suppresses that report.
|
||||
The invalid fixture demonstrates a failed-load report and captured source
|
||||
inventory; `source-1` is the ID from that fixture's acquisition. The scope opts
|
||||
in to transient overrides and passes them into its normal ConfigKit load. The
|
||||
diff example compares an overridden left side with ordinary configuration on
|
||||
the right and returns status 3 because the values differ.
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
schema:
|
||||
version: 2
|
||||
greeting: [invalid]
|
||||
@@ -49,10 +49,15 @@ func loadAppConfiguration(_ context.Context, selection ckconfig.Selection) (*con
|
||||
options.Overlay = selection.Overlay.Value
|
||||
options.Filesystem = &configkit.FilesystemContext{Root: ".", BaseDir: "."}
|
||||
}
|
||||
options.Overrides = append(options.Overrides, selection.Overrides...)
|
||||
return configkit.Load(source, options)
|
||||
}
|
||||
|
||||
func newApp() (*commandkit.App, error) {
|
||||
return newAppWithLoader(loadAppConfiguration)
|
||||
}
|
||||
|
||||
func newAppWithLoader(load func(context.Context, ckconfig.Selection) (*configkit.Result[appConfiguration], error)) (*commandkit.App, error) {
|
||||
countDefault := 1
|
||||
tagDefaults := []string{"example"}
|
||||
greet := commandkit.NewCommand(commandkit.CommandSpec[greetInput]{
|
||||
@@ -68,7 +73,7 @@ func newApp() (*commandkit.App, error) {
|
||||
},
|
||||
Run: func(invocation commandkit.Invocation, input greetInput) commandkit.Outcome {
|
||||
reporter := invocation.Reporter()
|
||||
configuration, err := loadAppConfiguration(invocation.Context, ckconfig.Selection{})
|
||||
configuration, err := load(invocation.Context, ckconfig.Selection{})
|
||||
if err != nil {
|
||||
return commandkit.Failure("Could not load application configuration.").WithCause(err)
|
||||
}
|
||||
@@ -87,9 +92,13 @@ func newApp() (*commandkit.App, error) {
|
||||
return commandkit.Success()
|
||||
},
|
||||
})
|
||||
scope := ckconfig.FromConfigKit("app", "Application configuration.", func(ctx context.Context, selection ckconfig.Selection, _, _ struct{}) (*configkit.Result[appConfiguration], error) {
|
||||
return load(ctx, selection)
|
||||
})
|
||||
scope.Features.Overrides = true
|
||||
return commandkit.New(
|
||||
commandkit.Identity{Name: "simple-example", Version: "1.0"},
|
||||
ckconfig.AppCommand(loadAppConfiguration),
|
||||
ckconfig.Command(ckconfig.Suite[struct{}, struct{}]{Scopes: []ckconfig.Scope[struct{}, struct{}]{scope}}),
|
||||
greet,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,12 +3,14 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
@@ -147,3 +149,55 @@ func decodeReport(data []byte) (*yaml.Node, error) {
|
||||
}
|
||||
return document.Content[0], nil
|
||||
}
|
||||
|
||||
func TestSimpleInspectionAndIndependentOverrides(t *testing.T) {
|
||||
outcome, output, _ := executeSimple(t, "config", "explain", "--list", "--under=/schema", "--format=json")
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || !strings.Contains(output, `"path": "/schema/version"`) {
|
||||
t.Fatalf("discovery = %#v %q", outcome, output)
|
||||
}
|
||||
outcome, output, _ = executeSimple(t, "config", "show", "--path=/greeting", "--set=/greeting=\"Hi\"")
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || output != "Hi\n" {
|
||||
t.Fatalf("focused override = %#v %q", outcome, output)
|
||||
}
|
||||
outcome, output, _ = executeSimple(t, "config", "diff", "--set=/greeting=\"Hi\"", "--details", "--check", "--format=json")
|
||||
if outcome.Kind != commandkit.OutcomeDomain || outcome.Status != 3 || !strings.Contains(output, `"before"`) || !strings.Contains(output, `"after"`) {
|
||||
t.Fatalf("independent diff = %#v %q", outcome, output)
|
||||
}
|
||||
outcome, output, _ = executeSimple(t, "config", "diff", "--set=/greeting=\"Hi\"", "--against-set=/greeting=\"Hi\"", "--details", "--check", "--format=json")
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || !strings.Contains(output, `"differences": []`) {
|
||||
t.Fatalf("equal overrides = %#v %q", outcome, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimpleFailedLoadReportsEvidence(t *testing.T) {
|
||||
_, failure := loadAppConfiguration(context.Background(), ckconfig.Selection{Config: commandkit.Supplied[string]{Value: "fixtures/invalid.yml", Set: true}})
|
||||
var native *configkit.LoadError
|
||||
if !errors.As(failure, &native) || len(native.Sources()) == 0 {
|
||||
t.Fatalf("fixture failure = %v", failure)
|
||||
}
|
||||
outcome, output, _ := executeSimple(t, "config", "validate", "--config=fixtures/invalid.yml", "--details", "--severity=error", "--format=json")
|
||||
if outcome.Kind != commandkit.OutcomeOperational || !strings.Contains(output, `"state": "present"`) || !strings.Contains(output, `"severity": "error"`) {
|
||||
t.Fatalf("detailed failure = %#v %q", outcome, output)
|
||||
}
|
||||
outcome, output, _ = executeSimple(t, "config", "sources", "--config=fixtures/invalid.yml", "--source-id="+native.Sources()[0].ID, "--format=json")
|
||||
if outcome.Kind != commandkit.OutcomeOperational || !strings.Contains(output, `"id":`) || !strings.Contains(output, "invalid.yml") {
|
||||
t.Fatalf("source failure = %#v %q", outcome, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimpleMetadataCommandsDoNotLoadConfiguration(t *testing.T) {
|
||||
loads := 0
|
||||
app, err := newAppWithLoader(func(context.Context, ckconfig.Selection) (*configkit.Result[appConfiguration], error) {
|
||||
loads++
|
||||
return nil, errors.New("unexpected load")
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, args := range [][]string{{"version"}, {"config", "scopes"}, {"config", "explain"}, {"config", "show", "--help"}} {
|
||||
result := app.Execute(context.Background(), args, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || loads != 0 {
|
||||
t.Fatalf("%v: %#v loads=%d", args, result, loads)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,51 +3,81 @@ package ckconfig
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
type explanationReport struct {
|
||||
Scope string `yaml:"scope"`
|
||||
Path string `yaml:"path"`
|
||||
Effective snapshotDTO `yaml:"effective"`
|
||||
Origin explanationOriginDTO `yaml:"origin"`
|
||||
History []explanationChangeDTO `yaml:"history"`
|
||||
SecretReference *secretReferenceDTO `yaml:"secret_reference"`
|
||||
Scope string `json:"scope"`
|
||||
Path string `json:"path"`
|
||||
Effective snapshotDTO `json:"effective"`
|
||||
Origin explanationOriginDTO `json:"origin"`
|
||||
History []explanationChangeDTO `json:"history"`
|
||||
SecretReference *secretReferenceDTO `json:"secret_reference"`
|
||||
Metadata *explanationMetadata `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type explanationMetadata struct {
|
||||
Explicit *bool `json:"explicit,omitempty"`
|
||||
Null *bool `json:"null,omitempty"`
|
||||
History []metadataHistoryRecord `json:"history,omitempty"`
|
||||
}
|
||||
|
||||
type metadataHistoryRecord struct {
|
||||
Path string `json:"path"`
|
||||
Previous []explanationOriginDTO `json:"previous,omitempty"`
|
||||
}
|
||||
|
||||
type pathDiscoveryReport struct {
|
||||
Scope string `json:"scope"`
|
||||
Paths []pathDiscoveryEntry `json:"paths"`
|
||||
}
|
||||
|
||||
type pathDiscoveryEntry struct {
|
||||
Path string `json:"path"`
|
||||
Present bool `json:"present"`
|
||||
Metadata *pathMetadata `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type pathMetadata struct {
|
||||
Explicit bool `json:"explicit"`
|
||||
}
|
||||
|
||||
var pathDiscoveryTemplate = template.Must(commandkit.ParseTextTemplate("paths", "{{range .Paths}}{{printf \"%q\" .Path}} {{if .Present}}{{if .Metadata.Explicit}}explicit{{else}}non-explicit{{end}}{{else}}historical{{end}}\n{{end}}", nil))
|
||||
|
||||
type snapshotDTO struct {
|
||||
Present bool `yaml:"present"`
|
||||
Redacted bool `yaml:"redacted"`
|
||||
YAML string `yaml:"yaml"`
|
||||
Present bool `json:"present"`
|
||||
Redacted bool `json:"redacted"`
|
||||
YAML string `json:"yaml"`
|
||||
}
|
||||
|
||||
type explanationOriginDTO struct {
|
||||
Layer string `yaml:"layer"`
|
||||
Locations []locationDTO `yaml:"locations"`
|
||||
Operation string `yaml:"operation"`
|
||||
Inheritance []inheritanceStepDTO `yaml:"inheritance"`
|
||||
Layer string `json:"layer"`
|
||||
Locations []locationDTO `json:"locations"`
|
||||
Operation string `json:"operation"`
|
||||
Inheritance []inheritanceStepDTO `json:"inheritance"`
|
||||
}
|
||||
|
||||
type inheritanceStepDTO struct {
|
||||
From string `yaml:"from"`
|
||||
To string `yaml:"to"`
|
||||
Reference string `yaml:"reference"`
|
||||
Locations []locationDTO `yaml:"locations"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Reference string `json:"reference"`
|
||||
Locations []locationDTO `json:"locations"`
|
||||
}
|
||||
|
||||
type explanationChangeDTO struct {
|
||||
Before snapshotDTO `yaml:"before"`
|
||||
After snapshotDTO `yaml:"after"`
|
||||
Origin explanationOriginDTO `yaml:"origin"`
|
||||
Reasons []string `yaml:"reasons"`
|
||||
Dependencies []string `yaml:"dependencies"`
|
||||
Before snapshotDTO `json:"before"`
|
||||
After snapshotDTO `json:"after"`
|
||||
Origin explanationOriginDTO `json:"origin"`
|
||||
Reasons []string `json:"reasons"`
|
||||
Dependencies []string `json:"dependencies"`
|
||||
}
|
||||
|
||||
type secretReferenceDTO struct {
|
||||
Name string `yaml:"name"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func runConfigExplanation[I, S any](invocation commandkit.Invocation, plan *configOperationPlan[I, S], state S) commandkit.Outcome {
|
||||
@@ -63,15 +93,40 @@ func runConfigExplanation[I, S any](invocation commandkit.Invocation, plan *conf
|
||||
}
|
||||
acquired, acquireErr := selected.scope.scope.Acquire(invocation.Context, Request{
|
||||
Operation: Explain,
|
||||
Selection: plan.selection,
|
||||
Selection: selected.selection,
|
||||
}, selected.input, state)
|
||||
queueConfigDiagnostics(reporter, acquired.Diagnostics)
|
||||
queueConfigAcquisition(reporter, acquired)
|
||||
if acquireErr != nil {
|
||||
return configFailure(fmt.Sprintf("Unable to explain configuration scope %q.", name), acquired.Explanation, acquireErr)
|
||||
}
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return configFailure("Configuration explanation was canceled.", acquired.Explanation, err)
|
||||
}
|
||||
if plan.list {
|
||||
if acquired.Value.Metadata == nil {
|
||||
return configFailure("Configuration scope did not provide path metadata.", acquired.Explanation, fmt.Errorf("configuration scope %q declared path discovery without metadata", name))
|
||||
}
|
||||
report := pathDiscoveryReport{Scope: name, Paths: []pathDiscoveryEntry{}}
|
||||
for _, path := range acquired.Value.Metadata.HistoricalPaths() {
|
||||
if plan.under != nil && !pathWithin(path, *plan.under) {
|
||||
continue
|
||||
}
|
||||
info, present := acquired.Value.Metadata.Lookup(path)
|
||||
if !present && (!plan.historical || plan.explicit.Set) {
|
||||
continue
|
||||
}
|
||||
if present && plan.explicit.Set && info.Explicit != plan.explicit.Value {
|
||||
continue
|
||||
}
|
||||
entry := pathDiscoveryEntry{Path: path.String(), Present: present}
|
||||
if present {
|
||||
entry.Metadata = &pathMetadata{Explicit: info.Explicit}
|
||||
}
|
||||
report.Paths = append(report.Paths, entry)
|
||||
}
|
||||
_ = reporter.Report(commandkit.Report{Value: report, TextTemplate: pathDiscoveryTemplate})
|
||||
return commandkit.Success()
|
||||
}
|
||||
if acquired.Value.Explanation == nil {
|
||||
cause := fmt.Errorf("configuration scope %q did not provide an explanation reader", name)
|
||||
return configFailure("Configuration scope did not provide explanation data.", acquired.Explanation, cause)
|
||||
@@ -85,22 +140,57 @@ func runConfigExplanation[I, S any](invocation commandkit.Invocation, plan *conf
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return configFailure("Configuration explanation was canceled.", acquired.Explanation, err)
|
||||
}
|
||||
if plan.format != "yaml" {
|
||||
err := reporter.RenderOutput(func(writer io.Writer) error {
|
||||
return acquired.Value.Explanation.WriteExplanation(writer, plan.path)
|
||||
})
|
||||
if err != nil && invocation.Context.Err() != nil {
|
||||
return configFailure("Configuration explanation was canceled.", acquired.Explanation, invocation.Context.Err())
|
||||
report := makeExplanationReport(name, explanation)
|
||||
if acquired.Value.Metadata != nil {
|
||||
metadata := &explanationMetadata{}
|
||||
if info, ok := acquired.Value.Metadata.Lookup(plan.path); ok {
|
||||
metadata.Explicit, metadata.Null = &info.Explicit, &info.Null
|
||||
}
|
||||
for _, change := range acquired.Value.Metadata.History(plan.path) {
|
||||
entry := metadataHistoryRecord{Path: change.Path.String()}
|
||||
for _, previous := range change.Previous {
|
||||
entry.Previous = append(entry.Previous, originReport(previous))
|
||||
}
|
||||
metadata.History = append(metadata.History, entry)
|
||||
}
|
||||
if metadata.Explicit != nil || len(metadata.History) > 0 {
|
||||
report.Metadata = metadata
|
||||
}
|
||||
return commandkit.Success()
|
||||
}
|
||||
return renderPreparedConfigReport(invocation, acquired.Explanation, func() ([]byte, error) {
|
||||
var report bytes.Buffer
|
||||
if err := encodeYAML(&report, makeExplanationReport(name, explanation)); err != nil {
|
||||
return nil, err
|
||||
text := template.Must(commandkit.ParseTextTemplate("explanation", "{{render .}}", template.FuncMap{
|
||||
"render": func(report explanationReport) (string, error) {
|
||||
var output bytes.Buffer
|
||||
err := acquired.Value.Explanation.WriteExplanation(&output, plan.path)
|
||||
if err == nil && report.Metadata != nil && report.Metadata.Explicit != nil {
|
||||
_, err = fmt.Fprintf(&output, "Explicit: %t\nNull: %t\n", *report.Metadata.Explicit, *report.Metadata.Null)
|
||||
}
|
||||
return output.String(), err
|
||||
},
|
||||
}))
|
||||
renderErr := reporter.Report(commandkit.Report{Value: report, TextTemplate: text})
|
||||
if renderErr != nil && invocation.Context.Err() != nil {
|
||||
return configFailure("Configuration explanation was canceled.", acquired.Explanation, invocation.Context.Err())
|
||||
}
|
||||
return commandkit.Success()
|
||||
}
|
||||
|
||||
func pathWithin(path, parent configkit.Path) bool {
|
||||
tokens := func(value string) []string {
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
return report.Bytes(), nil
|
||||
})
|
||||
return strings.Split(strings.TrimPrefix(value, "/"), "/")
|
||||
}
|
||||
child, prefix := tokens(path.String()), tokens(parent.String())
|
||||
if len(prefix) > len(child) {
|
||||
return false
|
||||
}
|
||||
for index := range prefix {
|
||||
if prefix[index] != child[index] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func makeExplanationReport(scope string, explanation configkit.Explanation) explanationReport {
|
||||
|
||||
@@ -1,30 +1,31 @@
|
||||
package ckconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
type scopeMetadata struct {
|
||||
Name string `yaml:"name"`
|
||||
Operations []Operation `yaml:"operations"`
|
||||
Name string `json:"name"`
|
||||
Operations []Operation `json:"operations"`
|
||||
Features []string `json:"features,omitempty"`
|
||||
}
|
||||
|
||||
type scopeInventory struct {
|
||||
Scopes []scopeMetadata `yaml:"scopes"`
|
||||
Scopes []scopeMetadata `json:"scopes"`
|
||||
}
|
||||
|
||||
type preparedScope[I, S any] struct {
|
||||
scope Scope[I, S]
|
||||
bindings []commandkit.Flag[I]
|
||||
scope Scope[I, S]
|
||||
bindings []commandkit.Flag[I]
|
||||
againstBindings []commandkit.Flag[I]
|
||||
}
|
||||
|
||||
type preparedSuite[I, S any] struct {
|
||||
@@ -34,6 +35,7 @@ type preparedSuite[I, S any] struct {
|
||||
scopes []*preparedScope[I, S]
|
||||
byName map[string]*preparedScope[I, S]
|
||||
bindingsByOperation map[Operation][]commandkit.Flag[I]
|
||||
againstBindings []commandkit.Flag[I]
|
||||
scopeChoices string
|
||||
operations []Operation
|
||||
inventory scopeInventory
|
||||
@@ -90,9 +92,13 @@ func captureSuite[I, S any](suite Suite[I, S]) *preparedSuite[I, S] {
|
||||
bindingsByOperation: make(map[Operation][]commandkit.Flag[I]),
|
||||
}
|
||||
selectors := make([]Selector[I], len(suite.Selectors))
|
||||
against := make([]commandkit.Flag[I], len(suite.Selectors))
|
||||
for index, selector := range suite.Selectors {
|
||||
selector.Scopes = append([]string(nil), selector.Scopes...)
|
||||
selectors[index] = selector
|
||||
if selector.AgainstName != "" {
|
||||
against[index] = commandkit.RenameFlag(selector.Binding, selector.AgainstName)
|
||||
}
|
||||
}
|
||||
|
||||
seenNames := make(map[string]struct{}, len(suite.Scopes))
|
||||
@@ -158,12 +164,18 @@ func captureSuite[I, S any](suite Suite[I, S]) *preparedSuite[I, S] {
|
||||
for scopeIndex := range prepared.scopes {
|
||||
if len(prepared.scopes[scopeIndex].scope.Operations) > 0 {
|
||||
prepared.scopes[scopeIndex].bindings = append(prepared.scopes[scopeIndex].bindings, selector.Binding)
|
||||
if selector.AgainstName != "" && containsOperation(prepared.scopes[scopeIndex].scope.Operations, Diff) {
|
||||
prepared.scopes[scopeIndex].againstBindings = append(prepared.scopes[scopeIndex].againstBindings, against[index])
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, name := range uniqueScopes {
|
||||
if scope, exists := prepared.byName[name]; exists && len(scope.scope.Operations) > 0 {
|
||||
scope.bindings = append(scope.bindings, selector.Binding)
|
||||
if selector.AgainstName != "" && containsOperation(scope.scope.Operations, Diff) {
|
||||
scope.againstBindings = append(scope.againstBindings, against[index])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -176,10 +188,13 @@ func captureSuite[I, S any](suite Suite[I, S]) *preparedSuite[I, S] {
|
||||
break
|
||||
}
|
||||
}
|
||||
for _, selector := range selectors {
|
||||
for index, selector := range selectors {
|
||||
for _, scope := range prepared.scopes {
|
||||
if containsOperation(scope.scope.Operations, operation) && selectorApplies(selector.Scopes, scope.scope.Name) {
|
||||
prepared.bindingsByOperation[operation] = append(prepared.bindingsByOperation[operation], selector.Binding)
|
||||
if operation == Diff && selector.AgainstName != "" {
|
||||
prepared.againstBindings = append(prepared.againstBindings, against[index])
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -189,6 +204,7 @@ func captureSuite[I, S any](suite Suite[I, S]) *preparedSuite[I, S] {
|
||||
prepared.inventory.Scopes = append(prepared.inventory.Scopes, scopeMetadata{
|
||||
Name: scope.scope.Name,
|
||||
Operations: append([]Operation(nil), scope.scope.Operations...),
|
||||
Features: featureNames(scope.scope.Features),
|
||||
})
|
||||
}
|
||||
return prepared
|
||||
@@ -254,62 +270,37 @@ func joinNames(names []string) string {
|
||||
return strings.Join(ordered, ", ")
|
||||
}
|
||||
|
||||
func featureNames(features ScopeFeatures) []string {
|
||||
var names []string
|
||||
if features.PathDiscovery {
|
||||
names = append(names, "path_discovery")
|
||||
}
|
||||
if features.PathShow {
|
||||
names = append(names, "path_show")
|
||||
}
|
||||
if features.Overrides {
|
||||
names = append(names, "overrides")
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
var scopeInventoryTemplate = template.Must(commandkit.ParseTextTemplate("scopes", `{{range .Scopes}}{{.Name}}: {{range $index, $operation := .Operations}}{{if $index}}, {{end}}{{$operation}}{{end}}{{if .Features}} (features: {{range $index, $feature := .Features}}{{if $index}}, {{end}}{{$feature}}{{end}}){{end}}
|
||||
{{end}}`, nil))
|
||||
|
||||
func newConfigScopesCommand[I, S any](prepared *preparedSuite[I, S]) commandkit.Command {
|
||||
formatDefault := "text"
|
||||
spec := commandkit.CommandSpec[scopeInventoryInput]{
|
||||
Name: "scopes",
|
||||
Summary: "List configuration scopes and supported operations.",
|
||||
Flags: []commandkit.Flag[scopeInventoryInput]{commandkit.ValueFlag(
|
||||
commandkit.FlagMeta{Name: "format", Usage: "Output format: text or yaml.", Completion: completionChoices("text", "yaml")}, &formatDefault, parseConfigString,
|
||||
func(input *scopeInventoryInput, value commandkit.Supplied[string]) { input.Format = value.Value },
|
||||
)},
|
||||
CheckInput: func(input scopeInventoryInput) error { return checkConfigFormat(input.Format) },
|
||||
Run: func(invocation commandkit.Invocation, input scopeInventoryInput) commandkit.Outcome {
|
||||
_ = invocation.Reporter().RenderOutput(func(writer io.Writer) error {
|
||||
var report bytes.Buffer
|
||||
if input.Format == "yaml" {
|
||||
if err := encodeYAML(&report, prepared.inventory); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
_, _ = report.WriteString(formatScopeInventory(prepared.inventory))
|
||||
}
|
||||
_, err := writer.Write(report.Bytes())
|
||||
return err
|
||||
})
|
||||
var description strings.Builder
|
||||
for _, scope := range prepared.inventory.Scopes {
|
||||
if len(scope.Features) > 0 {
|
||||
fmt.Fprintf(&description, "%s: %s\n", scope.Name, strings.Join(scope.Features, ", "))
|
||||
}
|
||||
}
|
||||
return commandkit.NewCommand(commandkit.CommandSpec[struct{}]{
|
||||
Name: "scopes", Summary: "List configuration scopes, operations, and supported features.", Description: description.String(),
|
||||
Run: func(invocation commandkit.Invocation, _ struct{}) commandkit.Outcome {
|
||||
_ = invocation.Reporter().Report(commandkit.Report{Value: prepared.inventory, TextTemplate: scopeInventoryTemplate})
|
||||
return commandkit.Success()
|
||||
},
|
||||
}
|
||||
return commandkit.NewCommand(spec)
|
||||
}
|
||||
|
||||
type scopeInventoryInput struct{ Format string }
|
||||
|
||||
type scopeInventoryYAML struct {
|
||||
Scopes []scopeMetadata `yaml:"scopes"`
|
||||
}
|
||||
|
||||
func formatScopeInventory(inventory scopeInventory) string {
|
||||
var output strings.Builder
|
||||
for _, scope := range inventory.Scopes {
|
||||
output.WriteString(scope.Name)
|
||||
output.WriteString(": ")
|
||||
for index, operation := range scope.Operations {
|
||||
if index > 0 {
|
||||
output.WriteString(", ")
|
||||
}
|
||||
output.WriteString(string(operation))
|
||||
}
|
||||
output.WriteByte('\n')
|
||||
}
|
||||
return output.String()
|
||||
}
|
||||
|
||||
func checkConfigFormat(format string) error {
|
||||
if format != "text" && format != "yaml" {
|
||||
return fmt.Errorf("unsupported configuration format %q", format)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func parseConfigString(value string) (string, error) { return value, nil }
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -270,7 +271,7 @@ func TestConfigAliasesForwardSelectedTenantAndGlobalHelp(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestShowAcquiresAllViewsBeforeRenderingAndFramesNativeYAML(t *testing.T) {
|
||||
func TestShowAcquiresAllViewsBeforeRenderingAggregate(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
var acquisitionOutputLengths []int
|
||||
makeScope := func(name, native string, acquireErr error) Scope[struct{}, *int] {
|
||||
@@ -306,9 +307,13 @@ func TestShowAcquiresAllViewsBeforeRenderingAndFramesNativeYAML(t *testing.T) {
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || outcome.Presentation.Output.State != commandkit.DeliveryComplete {
|
||||
t.Fatalf("aggregate show outcome = %#v", outcome)
|
||||
}
|
||||
want := "---\n# scope: app\nname: app\n---\n# scope: promptkit\nname: promptkit\n"
|
||||
if output.String() != want {
|
||||
t.Fatalf("aggregate show output = %q, want %q", output.String(), want)
|
||||
decoded, err := commandkit.DecodeYAMLReport(&output)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := map[string]any{"app": map[string]any{"name": "app"}, "promptkit": map[string]any{"name": "promptkit"}}
|
||||
if !reflect.DeepEqual(decoded, want) {
|
||||
t.Fatalf("aggregate = %#v, want %#v", decoded, want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -483,7 +488,7 @@ func TestExplainTracksNativeRenderFailureWithoutReplacingOperationCause(t *testi
|
||||
}}}))
|
||||
var output bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"config", "explain", "--path", "/token"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
if outcome.Kind != commandkit.OutcomeOperational || outcome.Cause != nil || !errors.Is(outcome.Presentation.Output.RenderError, renderErr) || output.String() != "partial native explanation\n" {
|
||||
if outcome.Kind != commandkit.OutcomeOperational || outcome.Cause != nil || !errors.Is(outcome.Presentation.Output.RenderError, renderErr) || output.Len() != 0 {
|
||||
t.Fatalf("native explanation failure outcome/output = %#v / %q", outcome, output.String())
|
||||
}
|
||||
}
|
||||
@@ -513,7 +518,7 @@ func TestReportWriteFailureIsRecordedByReporterAndPreservesCancellation(t *testi
|
||||
}}))
|
||||
var output bytes.Buffer
|
||||
outcome = app.Execute(ctx, []string{"config", "validate", "--scope", "all"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
if !errors.Is(outcome.Cause, context.Canceled) || outcome.Presentation.Output.State != commandkit.DeliveryComplete || calls != 2 || output.String() != "app: valid\n" {
|
||||
if !errors.Is(outcome.Cause, context.Canceled) || outcome.Presentation.Output.State != commandkit.DeliveryComplete || calls != 2 || output.String() != "app: valid\npromptkit: canceled\n" {
|
||||
t.Fatalf("cancelled aggregate validation outcome=%#v calls=%d output=%q", outcome, calls, output.String())
|
||||
}
|
||||
}
|
||||
@@ -588,3 +593,30 @@ func newConfigTestApp(t *testing.T, command commandkit.Command) *commandkit.App
|
||||
}
|
||||
return app
|
||||
}
|
||||
|
||||
func TestScopeFeaturesAndAcquisitionMessages(t *testing.T) {
|
||||
calls := 0
|
||||
message := func(text string) commandkit.Diagnostic {
|
||||
return commandkit.Diagnostic{Severity: commandkit.SeverityWarning, Write: func(w io.Writer) error { _, err := io.WriteString(w, text); return err }}
|
||||
}
|
||||
scope := Scope[struct{}, struct{}]{Name: "app", Operations: []Operation{Validate}, Features: ScopeFeatures{PathDiscovery: true, PathShow: true}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[View]{Value: View{Findings: &Findings{Messages: []commandkit.Diagnostic{message("native warning\n")}}}, Diagnostics: []commandkit.Diagnostic{message("application warning\n")}}, nil
|
||||
}}
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
var out, diagnostic bytes.Buffer
|
||||
result := app.Execute(context.Background(), []string{"config", "scopes", "--format=json"}, commandkit.Streams{Out: &out, Err: &diagnostic})
|
||||
if result.Kind != commandkit.OutcomeSuccess || calls != 0 || !strings.Contains(out.String(), "path_discovery") || !strings.Contains(out.String(), "path_show") {
|
||||
t.Fatalf("discovery = %#v %q", result, out.String())
|
||||
}
|
||||
out.Reset()
|
||||
result = app.Execute(context.Background(), []string{"config", "scopes", "--help"}, commandkit.Streams{Out: &out, Err: &diagnostic})
|
||||
if result.Kind != commandkit.OutcomeSuccess || calls != 0 || !strings.Contains(out.String(), "path_discovery") {
|
||||
t.Fatalf("help = %#v %q", result, out.String())
|
||||
}
|
||||
out.Reset()
|
||||
result = app.Execute(context.Background(), []string{"config", "validate", "--verbose"}, commandkit.Streams{Out: &out, Err: &diagnostic})
|
||||
if result.Kind != commandkit.OutcomeSuccess || calls != 1 || strings.Count(diagnostic.String(), "native warning") != 1 || strings.Count(diagnostic.String(), "application warning") != 1 {
|
||||
t.Fatalf("diagnostics = %#v %q", result, diagnostic.String())
|
||||
}
|
||||
}
|
||||
|
||||
126
integrations/ckconfig/focused_reports_test.go
Normal file
126
integrations/ckconfig/focused_reports_test.go
Normal file
@@ -0,0 +1,126 @@
|
||||
package ckconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestFocusedShowUsesSafeNativeValue(t *testing.T) {
|
||||
loads := 0
|
||||
scope := FromConfigKit("app", "", func(_ context.Context, selection Selection, _, _ struct{}) (*configkit.Result[map[string]any], error) {
|
||||
loads++
|
||||
return configkit.Load(configkit.Mapping("fixture", map[string]any{"object": map[string]any{"x": "y"}, "text": "hello", "false": false, "zero": 0, "null": nil, "gone": map[string]any{"x": 1}}), configkit.Options[map[string]any]{Overrides: selection.Overrides})
|
||||
})
|
||||
scope.Features.Overrides = true
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
for _, test := range []struct {
|
||||
path string
|
||||
want any
|
||||
}{{"/object", map[string]any{"x": "y"}}, {"/text", "hello"}, {"/false", false}, {"/zero", float64(0)}, {"/null", nil}} {
|
||||
var out bytes.Buffer
|
||||
result := app.Execute(context.Background(), []string{"config", "show", "--path=" + test.path, "--format=json"}, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
var got any
|
||||
if result.Kind != commandkit.OutcomeSuccess || json.Unmarshal(out.Bytes(), &got) != nil || !reflect.DeepEqual(got, test.want) {
|
||||
t.Fatalf("%s: %#v %q", test.path, result, out.String())
|
||||
}
|
||||
}
|
||||
var out bytes.Buffer
|
||||
result := app.Execute(context.Background(), []string{"config", "show", "--path=/text"}, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || out.String() != "hello\n" {
|
||||
t.Fatalf("automatic text: %#v %q", result, out.String())
|
||||
}
|
||||
out.Reset()
|
||||
result = app.Execute(context.Background(), []string{"config", "show", "--path=/false", "--format=yaml"}, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || strings.TrimSpace(out.String()) != "false" {
|
||||
t.Fatalf("yaml false: %#v %q", result, out.String())
|
||||
}
|
||||
for _, args := range [][]string{{"--path=/missing"}, {"--path=/gone/x", "--set=/gone=null"}} {
|
||||
result = app.Execute(context.Background(), append([]string{"config", "show"}, args...), commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeOperational {
|
||||
t.Fatalf("missing %v: %#v", args, result)
|
||||
}
|
||||
}
|
||||
before := loads
|
||||
for _, args := range [][]string{{"--path=bad"}, {"--scope=all", "--path=/text"}} {
|
||||
result = app.Execute(context.Background(), append([]string{"config", "show"}, args...), commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeUsage || loads != before {
|
||||
t.Fatalf("preflight %v: %#v", args, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFocusedShowChecksCapabilityAndFacet(t *testing.T) {
|
||||
calls := 0
|
||||
scope := Scope[struct{}, struct{}]{Name: "app", Operations: []Operation{Show}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[View]{}, nil
|
||||
}}
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
result := app.Execute(context.Background(), []string{"config", "show", "--path=/x"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeUsage || calls != 0 {
|
||||
t.Fatalf("unsupported: %#v", result)
|
||||
}
|
||||
scope.Features.PathShow = true
|
||||
app = newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
result = app.Execute(context.Background(), []string{"config", "show", "--path=/x"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeOperational || calls != 1 {
|
||||
t.Fatalf("missing facet: %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourcesFilterAndFailureEvidence(t *testing.T) {
|
||||
cause := errors.New("load failed")
|
||||
reader := &sourceInventory{values: []configkit.SourceInfo{{ID: "one", Label: "first"}, {ID: "two", Label: "second"}}}
|
||||
var returnedErr error
|
||||
var source SourceReader = reader
|
||||
scope := Scope[struct{}, struct{}]{Name: "app", Operations: []Operation{Sources}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
return commandkit.Acquired[View]{Value: View{Sources: source}}, returnedErr
|
||||
}}
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
run := func(args ...string) (commandkit.Outcome, string, string) {
|
||||
var out, diag bytes.Buffer
|
||||
result := app.Execute(context.Background(), append([]string{"config", "sources"}, args...), commandkit.Streams{Out: &out, Err: &diag})
|
||||
return result, out.String(), diag.String()
|
||||
}
|
||||
result, out, _ := run("--source-id=two", "--format=json")
|
||||
if result.Kind != commandkit.OutcomeSuccess || !strings.Contains(out, `"id": "two"`) || strings.Contains(out, `"id": "one"`) {
|
||||
t.Fatalf("selected source: %#v %q", result, out)
|
||||
}
|
||||
result, _, _ = run("--source-id=missing")
|
||||
if result.Kind != commandkit.OutcomeOperational {
|
||||
t.Fatalf("unknown source: %#v", result)
|
||||
}
|
||||
returnedErr = cause
|
||||
result, out, _ = run("--source-id=one", "--format=json")
|
||||
if !errors.Is(result.Cause, cause) || !strings.Contains(out, `"id": "one"`) || strings.Contains(out, `"id": "two"`) {
|
||||
t.Fatalf("failed selection: %#v %q", result, out)
|
||||
}
|
||||
result, _, diag := run("--source-id=missing")
|
||||
if !errors.Is(result.Cause, cause) || !strings.Contains(diag, "not found") {
|
||||
t.Fatalf("failed missing source: %#v %q", result, diag)
|
||||
}
|
||||
source = &sourceInventory{}
|
||||
result, out, _ = run("--format=json")
|
||||
if !errors.Is(result.Cause, cause) || !strings.Contains(out, `"sources": []`) {
|
||||
t.Fatalf("empty evidence: %#v %q", result, out)
|
||||
}
|
||||
source = nil
|
||||
result, out, diag = run()
|
||||
if !errors.Is(result.Cause, cause) || out != "" || !strings.Contains(diag, "unavailable") {
|
||||
t.Fatalf("unavailable evidence: %#v %q %q", result, out, diag)
|
||||
}
|
||||
source = reader
|
||||
result = app.Execute(context.Background(), []string{"config", "sources"}, commandkit.Streams{Out: shortWriter{}, Err: io.Discard})
|
||||
if !errors.Is(result.Cause, cause) || result.Presentation.Output.State != commandkit.DeliveryIncomplete {
|
||||
t.Fatalf("delivery failure: %#v", result)
|
||||
}
|
||||
}
|
||||
79
integrations/ckconfig/independent_comparison_test.go
Normal file
79
integrations/ckconfig/independent_comparison_test.go
Normal file
@@ -0,0 +1,79 @@
|
||||
package ckconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestComparisonSidesKeepIndependentSelectionsAndDefaults(t *testing.T) {
|
||||
type input struct {
|
||||
Label commandkit.Supplied[string]
|
||||
Tags []string
|
||||
}
|
||||
label := commandkit.ValueFlag(commandkit.FlagMeta{Name: "label"}, (*string)(nil), parseConfigString, func(i *input, value commandkit.Supplied[string]) { i.Label = value })
|
||||
tags := commandkit.RepeatFlag(commandkit.FlagMeta{Name: "tag"}, []string(nil), parseConfigString, func(i *input, value commandkit.Supplied[[]string]) { i.Tags = value.Value })
|
||||
var pair ComparisonRequest[input]
|
||||
calls := 0
|
||||
suite := Suite[input, struct{}]{
|
||||
NewInput: func() input {
|
||||
return input{Label: commandkit.Supplied[string]{Value: "factory"}, Tags: []string{"factory"}}
|
||||
},
|
||||
Selectors: []Selector[input]{{Binding: label, AgainstName: "against-label"}, {Binding: tags, AgainstName: "against-tag"}},
|
||||
Scopes: []Scope[input, struct{}]{{Name: "app", Operations: []Operation{Diff}, Compare: func(_ context.Context, request ComparisonRequest[input], _ struct{}) (commandkit.Acquired[[]configkit.Difference], error) {
|
||||
calls++
|
||||
pair = request
|
||||
return commandkit.Acquired[[]configkit.Difference]{}, nil
|
||||
}}},
|
||||
}
|
||||
app := newConfigTestApp(t, Command(suite))
|
||||
tests := []struct {
|
||||
args []string
|
||||
left, right Selection
|
||||
leftLabel, rightLabel commandkit.Supplied[string]
|
||||
leftTags, rightTags []string
|
||||
}{
|
||||
{leftLabel: commandkit.Supplied[string]{Value: "factory"}, rightLabel: commandkit.Supplied[string]{Value: "factory"}, leftTags: []string{"factory"}, rightTags: []string{"factory"}},
|
||||
{args: []string{"--config=left", "--overlay=base", "--label=", "--tag=a", "--tag=b"}, left: Selection{Config: commandkit.Supplied[string]{Value: "left", Set: true}, Overlay: commandkit.Supplied[string]{Value: "base", Set: true}}, leftLabel: commandkit.Supplied[string]{Set: true}, rightLabel: commandkit.Supplied[string]{Value: "factory"}, leftTags: []string{"a", "b"}, rightTags: []string{"factory"}},
|
||||
{args: []string{"--against-config=right", "--against-label=r", "--against-tag=x"}, right: Selection{Config: commandkit.Supplied[string]{Value: "right", Set: true}}, leftLabel: commandkit.Supplied[string]{Value: "factory"}, rightLabel: commandkit.Supplied[string]{Value: "r", Set: true}, leftTags: []string{"factory"}, rightTags: []string{"x"}},
|
||||
{args: []string{"--config=left", "--against-overlay=", "--label=l", "--against-label=r", "--tag=a", "--against-tag=b"}, left: Selection{Config: commandkit.Supplied[string]{Value: "left", Set: true}}, right: Selection{Overlay: commandkit.Supplied[string]{Set: true}}, leftLabel: commandkit.Supplied[string]{Value: "l", Set: true}, rightLabel: commandkit.Supplied[string]{Value: "r", Set: true}, leftTags: []string{"a"}, rightTags: []string{"b"}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
result := app.Execute(context.Background(), append([]string{"config", "diff"}, test.args...), commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || !reflect.DeepEqual(pair.Left.Selection, test.left) || !reflect.DeepEqual(pair.Right.Selection, test.right) || pair.Left.Input.Label != test.leftLabel || pair.Right.Input.Label != test.rightLabel || !reflect.DeepEqual(pair.Left.Input.Tags, test.leftTags) || !reflect.DeepEqual(pair.Right.Input.Tags, test.rightTags) {
|
||||
t.Fatalf("args=%v outcome=%#v pair=%#v", test.args, result, pair)
|
||||
}
|
||||
}
|
||||
if calls != len(tests) {
|
||||
t.Fatalf("provider calls = %d", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestComparisonRequiredCounterpartsAndCollisions(t *testing.T) {
|
||||
flag := commandkit.ValueFlag(commandkit.FlagMeta{Name: "choice", Required: true}, (*string)(nil), parseConfigString, func(i *string, value commandkit.Supplied[string]) { *i = value.Value })
|
||||
calls := 0
|
||||
scope := Scope[string, struct{}]{Name: "app", Operations: []Operation{Diff}, Compare: func(context.Context, ComparisonRequest[string], struct{}) (commandkit.Acquired[[]configkit.Difference], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[[]configkit.Difference]{}, nil
|
||||
}}
|
||||
suite := Suite[string, struct{}]{Selectors: []Selector[string]{{Binding: flag, AgainstName: "against-choice"}}, Scopes: []Scope[string, struct{}]{scope}}
|
||||
app := newConfigTestApp(t, Command(suite))
|
||||
for _, args := range [][]string{{"--choice=x"}, {"--against-choice=x"}} {
|
||||
result := app.Execute(context.Background(), append([]string{"config", "diff"}, args...), commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeUsage || calls != 0 {
|
||||
t.Fatalf("missing side %v: %#v", args, result)
|
||||
}
|
||||
}
|
||||
result := app.Execute(context.Background(), []string{"config", "diff", "--choice=x", "--against-choice=y"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || calls != 1 {
|
||||
t.Fatalf("complete sides: %#v", result)
|
||||
}
|
||||
suite.Selectors[0].AgainstName = "against-config"
|
||||
if _, err := commandkit.New(commandkit.Identity{Name: "app"}, Command(suite)); err == nil {
|
||||
t.Fatal("conflicting counterpart accepted")
|
||||
}
|
||||
}
|
||||
@@ -9,18 +9,28 @@ import (
|
||||
)
|
||||
|
||||
type configCommandInput[I, S any] struct {
|
||||
selection Selection
|
||||
against Selection
|
||||
scope commandkit.Supplied[string]
|
||||
format commandkit.Supplied[string]
|
||||
path commandkit.Supplied[string]
|
||||
values commandkit.FlagValues[I]
|
||||
plan *configOperationPlan[I, S]
|
||||
selection Selection
|
||||
against Selection
|
||||
scope commandkit.Supplied[string]
|
||||
path commandkit.Supplied[string]
|
||||
list commandkit.Supplied[bool]
|
||||
historical commandkit.Supplied[bool]
|
||||
under commandkit.Supplied[string]
|
||||
explicit commandkit.Supplied[bool]
|
||||
sourceID commandkit.Supplied[string]
|
||||
details commandkit.Supplied[bool]
|
||||
check commandkit.Supplied[bool]
|
||||
severities []configkit.Severity
|
||||
codes []string
|
||||
values commandkit.FlagValues[I]
|
||||
againstValues commandkit.FlagValues[I]
|
||||
plan *configOperationPlan[I, S]
|
||||
}
|
||||
|
||||
type selectedScopeInput[I, S any] struct {
|
||||
scope *preparedScope[I, S]
|
||||
input I
|
||||
scope *preparedScope[I, S]
|
||||
input I
|
||||
selection Selection
|
||||
}
|
||||
|
||||
type preparedComparison[I, S any] struct {
|
||||
@@ -31,24 +41,25 @@ type preparedComparison[I, S any] struct {
|
||||
type configOperationPlan[I, S any] struct {
|
||||
prepared *preparedSuite[I, S]
|
||||
operation Operation
|
||||
selection Selection
|
||||
scopeName string
|
||||
format string
|
||||
path configkit.Path
|
||||
pathSet bool
|
||||
sourceID commandkit.Supplied[string]
|
||||
details bool
|
||||
check bool
|
||||
severities []configkit.Severity
|
||||
codes []string
|
||||
list bool
|
||||
help bool
|
||||
historical bool
|
||||
under *configkit.Path
|
||||
explicit commandkit.Supplied[bool]
|
||||
scopes []selectedScopeInput[I, S]
|
||||
comparison *preparedComparison[I, S]
|
||||
}
|
||||
|
||||
func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operation Operation) commandkit.Command {
|
||||
defaultScope := "app"
|
||||
defaultFormat := "text"
|
||||
if operation == Show || operation == Diff {
|
||||
defaultFormat = "yaml"
|
||||
}
|
||||
formats := completionChoices("text", "yaml")
|
||||
if operation == Show || operation == Diff {
|
||||
formats = completionChoices("yaml")
|
||||
}
|
||||
var scopeChoices []commandkit.CompletionChoice
|
||||
allSupported := len(prepared.scopes) > 0
|
||||
for _, scope := range prepared.scopes {
|
||||
@@ -64,8 +75,6 @@ func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operatio
|
||||
flags := []commandkit.Flag[*configCommandInput[I, S]]{
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "scope", Usage: "Configuration scope name or all where supported.", Completion: commandkit.CompleteChoices(scopeChoices...)}, &defaultScope, parseConfigString,
|
||||
func(input **configCommandInput[I, S], value commandkit.Supplied[string]) { (*input).scope = value }),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "format", Usage: "Output format.", Completion: formats}, &defaultFormat, parseConfigString,
|
||||
func(input **configCommandInput[I, S], value commandkit.Supplied[string]) { (*input).format = value }),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "config", Usage: "Configuration source.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseConfigString,
|
||||
func(input **configCommandInput[I, S], value commandkit.Supplied[string]) {
|
||||
(*input).selection.Config = value
|
||||
@@ -77,6 +86,8 @@ func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operatio
|
||||
}
|
||||
if operation == Diff {
|
||||
flags = append(flags,
|
||||
commandkit.BoolFlag(commandkit.FlagMeta{Name: "details", Usage: "Show native before and after difference evidence."}, false, func(input **configCommandInput[I, S], value commandkit.Supplied[bool]) { (*input).details = value }),
|
||||
commandkit.BoolFlag(commandkit.FlagMeta{Name: "check", Usage: "Return status 3 when differences are found."}, false, func(input **configCommandInput[I, S], value commandkit.Supplied[bool]) { (*input).check = value }),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "against-config", Usage: "Configuration source for the right side.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseConfigString,
|
||||
func(input **configCommandInput[I, S], value commandkit.Supplied[string]) {
|
||||
(*input).against.Config = value
|
||||
@@ -87,9 +98,43 @@ func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operatio
|
||||
}),
|
||||
)
|
||||
}
|
||||
if operation == Validate {
|
||||
flags = append(flags,
|
||||
commandkit.BoolFlag(commandkit.FlagMeta{Name: "details", Usage: "Show native validation findings."}, false, func(input **configCommandInput[I, S], value commandkit.Supplied[bool]) { (*input).details = value }),
|
||||
commandkit.RepeatFlag(commandkit.FlagMeta{Name: "severity", Usage: "Filter detailed findings by error or warning."}, []configkit.Severity(nil), parseValidationSeverity, func(input **configCommandInput[I, S], value commandkit.Supplied[[]configkit.Severity]) {
|
||||
(*input).severities = value.Value
|
||||
}),
|
||||
commandkit.RepeatFlag(commandkit.FlagMeta{Name: "code", Usage: "Filter detailed findings by exact native code."}, []string(nil), parseConfigString, func(input **configCommandInput[I, S], value commandkit.Supplied[[]string]) {
|
||||
(*input).codes = value.Value
|
||||
}),
|
||||
)
|
||||
}
|
||||
if supportsOverrides(prepared, operation) {
|
||||
flags = append(flags, commandkit.RepeatFlag(commandkit.FlagMeta{Name: "set", Usage: "Override POINTER=JSON (pointer keys cannot contain =)."}, []configkit.Override(nil), overrideParser("--set"),
|
||||
func(input **configCommandInput[I, S], value commandkit.Supplied[[]configkit.Override]) {
|
||||
(*input).selection.Overrides = value.Value
|
||||
}))
|
||||
if operation == Diff {
|
||||
flags = append(flags, commandkit.RepeatFlag(commandkit.FlagMeta{Name: "against-set", Usage: "Right-side override POINTER=JSON (pointer keys cannot contain =)."}, []configkit.Override(nil), overrideParser("--against-set"),
|
||||
func(input **configCommandInput[I, S], value commandkit.Supplied[[]configkit.Override]) {
|
||||
(*input).against.Overrides = value.Value
|
||||
}))
|
||||
}
|
||||
}
|
||||
if operation == Explain {
|
||||
flags = append(flags, commandkit.ValueFlag(commandkit.FlagMeta{Name: "path", Usage: "JSON Pointer path to explain.", Required: true}, (*string)(nil), parseConfigString,
|
||||
func(input **configCommandInput[I, S], value commandkit.Supplied[string]) { (*input).path = value }))
|
||||
flags = append(flags,
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "path", Usage: "JSON Pointer path to explain."}, (*string)(nil), parseConfigString, func(input **configCommandInput[I, S], value commandkit.Supplied[string]) { (*input).path = value }),
|
||||
commandkit.BoolFlag(commandkit.FlagMeta{Name: "list", Usage: "List configuration paths."}, false, func(input **configCommandInput[I, S], value commandkit.Supplied[bool]) { (*input).list = value }),
|
||||
commandkit.BoolFlag(commandkit.FlagMeta{Name: "historical", Usage: "Include historical-only paths when listing."}, false, func(input **configCommandInput[I, S], value commandkit.Supplied[bool]) { (*input).historical = value }),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "under", Usage: "List paths under a JSON Pointer."}, (*string)(nil), parseConfigString, func(input **configCommandInput[I, S], value commandkit.Supplied[string]) { (*input).under = value }),
|
||||
commandkit.BoolFlag(commandkit.FlagMeta{Name: "explicit", Usage: "Filter listed current paths by explicitness."}, false, func(input **configCommandInput[I, S], value commandkit.Supplied[bool]) { (*input).explicit = value }),
|
||||
)
|
||||
}
|
||||
if operation == Show {
|
||||
flags = append(flags, commandkit.ValueFlag(commandkit.FlagMeta{Name: "path", Usage: "JSON Pointer to one effective value."}, (*string)(nil), parseConfigString, func(input **configCommandInput[I, S], value commandkit.Supplied[string]) { (*input).path = value }))
|
||||
}
|
||||
if operation == Sources {
|
||||
flags = append(flags, commandkit.ValueFlag(commandkit.FlagMeta{Name: "source-id", Usage: "Select one source ID from this acquisition."}, (*string)(nil), parseConfigString, func(input **configCommandInput[I, S], value commandkit.Supplied[string]) { (*input).sourceID = value }))
|
||||
}
|
||||
flags = append(flags, commandkit.CaptureFlags(prepared.bindingsByOperation[operation], func(input **configCommandInput[I, S]) *commandkit.FlagValues[I] {
|
||||
if input == nil || *input == nil {
|
||||
@@ -97,12 +142,21 @@ func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operatio
|
||||
}
|
||||
return &(*input).values
|
||||
})...)
|
||||
if operation == Diff {
|
||||
flags = append(flags, commandkit.CaptureFlags(prepared.againstBindings, func(input **configCommandInput[I, S]) *commandkit.FlagValues[I] {
|
||||
if input == nil || *input == nil {
|
||||
return nil
|
||||
}
|
||||
return &(*input).againstValues
|
||||
})...)
|
||||
}
|
||||
|
||||
name, summary := operationDeclaration(operation)
|
||||
return commandkit.NewCommand(commandkit.CommandSpec[*configCommandInput[I, S]]{
|
||||
Name: name, Summary: summary,
|
||||
NewInput: func() *configCommandInput[I, S] { return &configCommandInput[I, S]{} },
|
||||
Flags: flags,
|
||||
Description: operationDescription(operation),
|
||||
NewInput: func() *configCommandInput[I, S] { return &configCommandInput[I, S]{} },
|
||||
Flags: flags,
|
||||
CheckInput: func(input *configCommandInput[I, S]) error {
|
||||
if input == nil {
|
||||
return fmt.Errorf("configuration input must not be nil")
|
||||
@@ -115,6 +169,13 @@ func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operatio
|
||||
})
|
||||
}
|
||||
|
||||
func operationDescription(operation Operation) string {
|
||||
if operation == Explain {
|
||||
return "Use --list to discover paths or --path POINTER to explain one path."
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func operationDeclaration(operation Operation) (string, string) {
|
||||
switch operation {
|
||||
case Validate:
|
||||
@@ -133,15 +194,20 @@ func operationDeclaration(operation Operation) (string, string) {
|
||||
}
|
||||
|
||||
func prepareConfigOperation[I, S any](prepared *preparedSuite[I, S], operation Operation, input *configCommandInput[I, S]) error {
|
||||
format := input.format.Value
|
||||
if err := checkConfigFormat(format); err != nil {
|
||||
return err
|
||||
if operation == Validate && !input.details.Value && (len(input.severities) > 0 || len(input.codes) > 0) {
|
||||
return fmt.Errorf("--severity and --code require --details")
|
||||
}
|
||||
if operation == Show && format != "yaml" {
|
||||
return fmt.Errorf("unsupported configuration show format %q", format)
|
||||
}
|
||||
if operation == Diff && format != "yaml" {
|
||||
return fmt.Errorf("unsupported configuration diff format %q", format)
|
||||
if operation == Explain {
|
||||
if input.list.Value && input.path.Set {
|
||||
return fmt.Errorf("--list and --path cannot be combined")
|
||||
}
|
||||
if !input.list.Value && (input.historical.Set || input.under.Set || input.explicit.Set) {
|
||||
return fmt.Errorf("--historical, --under, and --explicit require --list")
|
||||
}
|
||||
if !input.list.Value && !input.path.Set {
|
||||
input.plan = &configOperationPlan[I, S]{prepared: prepared, operation: operation, help: true}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
scopeName := "app"
|
||||
@@ -154,6 +220,9 @@ func prepareConfigOperation[I, S any](prepared *preparedSuite[I, S], operation O
|
||||
if scopeName == "all" && operation != Validate && operation != Show {
|
||||
return fmt.Errorf("scope all is supported only for validate and show")
|
||||
}
|
||||
if scopeName == "all" && operation == Show && input.path.Set {
|
||||
return fmt.Errorf("path-selected show requires one scope")
|
||||
}
|
||||
|
||||
var selected []*preparedScope[I, S]
|
||||
if scopeName == "all" {
|
||||
@@ -168,37 +237,60 @@ func prepareConfigOperation[I, S any](prepared *preparedSuite[I, S], operation O
|
||||
if !containsOperation(scope.scope.Operations, operation) {
|
||||
return fmt.Errorf("configuration scope %q does not support %s (available: %s)", scope.scope.Name, operation, joinOperations(scope.scope.Operations))
|
||||
}
|
||||
if (len(input.selection.Overrides) > 0 || len(input.against.Overrides) > 0) && !scope.scope.Features.Overrides {
|
||||
return fmt.Errorf("configuration scope %q does not support overrides", scope.scope.Name)
|
||||
}
|
||||
if operation == Explain && input.list.Value && !scope.scope.Features.PathDiscovery {
|
||||
return fmt.Errorf("configuration scope %q does not support path discovery", scope.scope.Name)
|
||||
}
|
||||
if operation == Show && input.path.Set && !scope.scope.Features.PathShow {
|
||||
return fmt.Errorf("configuration scope %q does not support path-selected show", scope.scope.Name)
|
||||
}
|
||||
}
|
||||
|
||||
var path configkit.Path
|
||||
if operation == Explain {
|
||||
if !input.path.Set {
|
||||
return fmt.Errorf("configuration explanation requires --path")
|
||||
}
|
||||
if (operation == Explain || operation == Show) && input.path.Set {
|
||||
parsed, err := configkit.ParsePath(input.path.Value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid configuration path: %w", err)
|
||||
}
|
||||
path = parsed
|
||||
}
|
||||
var under *configkit.Path
|
||||
if input.under.Set {
|
||||
parsed, err := configkit.ParsePath(input.under.Value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid subtree path: %w", err)
|
||||
}
|
||||
under = &parsed
|
||||
}
|
||||
|
||||
plan := &configOperationPlan[I, S]{
|
||||
prepared: prepared,
|
||||
operation: operation,
|
||||
selection: input.selection,
|
||||
scopeName: scopeName,
|
||||
format: format,
|
||||
path: path,
|
||||
scopes: make([]selectedScopeInput[I, S], 0, len(selected)),
|
||||
prepared: prepared,
|
||||
operation: operation,
|
||||
scopeName: scopeName,
|
||||
path: path,
|
||||
pathSet: input.path.Set,
|
||||
sourceID: input.sourceID,
|
||||
details: input.details.Value,
|
||||
check: input.check.Value,
|
||||
severities: append([]configkit.Severity(nil), input.severities...),
|
||||
codes: append([]string(nil), input.codes...),
|
||||
list: input.list.Value,
|
||||
historical: input.historical.Value,
|
||||
under: under,
|
||||
explicit: input.explicit,
|
||||
scopes: make([]selectedScopeInput[I, S], 0, len(selected)),
|
||||
}
|
||||
if operation == Diff {
|
||||
input.against = inheritComparisonSelection(input.selection, input.against)
|
||||
scope := selected[0]
|
||||
left, err := prepareScopeInput(prepared, input.values, scope, input.selection)
|
||||
input.selection = cloneSelection(input.selection)
|
||||
input.against = cloneSelection(input.against)
|
||||
left, err := prepareScopeInput(prepared, input.values, scope, scope.bindings, input.selection, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("configuration scope %q left input: %w", scope.scope.Name, err)
|
||||
}
|
||||
right, err := prepareScopeInput(prepared, input.values, scope, input.against)
|
||||
right, err := prepareScopeInput(prepared, input.againstValues, scope, scope.againstBindings, input.against, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("configuration scope %q right input: %w", scope.scope.Name, err)
|
||||
}
|
||||
@@ -213,24 +305,29 @@ func prepareConfigOperation[I, S any](prepared *preparedSuite[I, S], operation O
|
||||
return nil
|
||||
}
|
||||
for _, scope := range selected {
|
||||
value, err := prepareScopeInput(prepared, input.values, scope, input.selection)
|
||||
selection := cloneSelection(input.selection)
|
||||
value, err := prepareScopeInput(prepared, input.values, scope, scope.bindings, selection, false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("configuration scope %q: %w", scope.scope.Name, err)
|
||||
}
|
||||
plan.scopes = append(plan.scopes, selectedScopeInput[I, S]{scope: scope, input: value})
|
||||
plan.scopes = append(plan.scopes, selectedScopeInput[I, S]{scope: scope, input: value, selection: selection})
|
||||
}
|
||||
input.plan = plan
|
||||
return nil
|
||||
}
|
||||
|
||||
func prepareScopeInput[I, S any](prepared *preparedSuite[I, S], values commandkit.FlagValues[I], scope *preparedScope[I, S], selection Selection) (I, error) {
|
||||
func prepareScopeInput[I, S any](prepared *preparedSuite[I, S], values commandkit.FlagValues[I], scope *preparedScope[I, S], bindings []commandkit.Flag[I], selection Selection, suppliedOnly bool) (I, error) {
|
||||
var value I
|
||||
if prepared.newInput != nil {
|
||||
value = prepared.newInput()
|
||||
}
|
||||
// Availability was checked before this helper, so every binding for the
|
||||
// selected scope belongs to the operation's captured union.
|
||||
if err := values.ApplyTo(&value, scope.bindings...); err != nil {
|
||||
apply := values.ApplyTo
|
||||
if suppliedOnly {
|
||||
apply = values.ApplySuppliedTo
|
||||
}
|
||||
if err := apply(&value, bindings...); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if prepared.checkInput != nil {
|
||||
@@ -241,16 +338,6 @@ func prepareScopeInput[I, S any](prepared *preparedSuite[I, S], values commandki
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func inheritComparisonSelection(left, right Selection) Selection {
|
||||
if !right.Config.Set {
|
||||
right.Config = left.Config
|
||||
}
|
||||
if !right.Overlay.Set {
|
||||
right.Overlay = left.Overlay
|
||||
}
|
||||
return right
|
||||
}
|
||||
|
||||
func joinOperations(operations []Operation) string {
|
||||
values := make([]string, len(operations))
|
||||
for index, operation := range operations {
|
||||
|
||||
@@ -11,6 +11,9 @@ func runConfigOperation[I, S any](invocation commandkit.Invocation, operation Op
|
||||
if input == nil || input.plan == nil {
|
||||
return commandkit.Failure("Configuration operation was not prepared.")
|
||||
}
|
||||
if input.plan.help {
|
||||
return invocation.Help()
|
||||
}
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return configFailure("Configuration operation was canceled.", commandkit.Explanation{}, err)
|
||||
}
|
||||
@@ -54,6 +57,13 @@ func queueConfigDiagnostics(reporter *commandkit.Reporter, diagnostics []command
|
||||
}
|
||||
}
|
||||
|
||||
func queueConfigAcquisition(reporter *commandkit.Reporter, acquired commandkit.Acquired[View]) {
|
||||
queueConfigDiagnostics(reporter, acquired.Diagnostics)
|
||||
if acquired.Value.Findings != nil {
|
||||
queueConfigDiagnostics(reporter, acquired.Value.Findings.Messages)
|
||||
}
|
||||
}
|
||||
|
||||
func configFailure(message string, explanation commandkit.Explanation, cause error) commandkit.Outcome {
|
||||
if explanation.Message != "" || len(explanation.Details) > 0 {
|
||||
message = explanation.Message
|
||||
@@ -71,14 +81,15 @@ func configAcquisitionFailure(
|
||||
acquired commandkit.Acquired[View],
|
||||
cause error,
|
||||
) commandkit.Outcome {
|
||||
queueConfigDiagnostics(reporter, acquired.Diagnostics)
|
||||
queueConfigAcquisition(reporter, acquired)
|
||||
message := fmt.Sprintf("Unable to %s configuration scope %q.", operation, scope)
|
||||
return configFailure(message, acquired.Explanation, cause)
|
||||
}
|
||||
|
||||
// Preserve the preparation/delivery cancellation checkpoint for buffered reports.
|
||||
func renderPreparedConfigReport(invocation commandkit.Invocation, explanation commandkit.Explanation, prepare func() ([]byte, error)) commandkit.Outcome {
|
||||
func renderPreparedConfigReport(invocation commandkit.Invocation, explanation commandkit.Explanation, prepare func() (any, error)) commandkit.Outcome {
|
||||
var canceled error
|
||||
var value any
|
||||
renderErr := invocation.Reporter().RenderOutput(func(writer io.Writer) error {
|
||||
report, err := prepare()
|
||||
if err != nil {
|
||||
@@ -87,8 +98,8 @@ func renderPreparedConfigReport(invocation commandkit.Invocation, explanation co
|
||||
if canceled = invocation.Context.Err(); canceled != nil {
|
||||
return nil
|
||||
}
|
||||
_, err = writer.Write(report)
|
||||
return err
|
||||
value = report
|
||||
return nil
|
||||
})
|
||||
if canceled == nil && renderErr != nil {
|
||||
canceled = invocation.Context.Err()
|
||||
@@ -96,5 +107,8 @@ func renderPreparedConfigReport(invocation commandkit.Invocation, explanation co
|
||||
if canceled != nil {
|
||||
return configFailure("Configuration report preparation was canceled.", explanation, canceled)
|
||||
}
|
||||
if renderErr == nil {
|
||||
_ = invocation.Reporter().Report(commandkit.Report{Value: value})
|
||||
}
|
||||
return commandkit.Success()
|
||||
}
|
||||
|
||||
65
integrations/ckconfig/overrides.go
Normal file
65
integrations/ckconfig/overrides.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package ckconfig
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func supportsOverrides[I, S any](prepared *preparedSuite[I, S], operation Operation) bool {
|
||||
for _, scope := range prepared.scopes {
|
||||
if scope.scope.Features.Overrides && containsOperation(scope.scope.Operations, operation) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func overrideParser(flag string) func(string) (configkit.Override, error) {
|
||||
return func(raw string) (configkit.Override, error) {
|
||||
pointer, jsonText, ok := strings.Cut(raw, "=")
|
||||
if !ok {
|
||||
return configkit.Override{}, fmt.Errorf("override requires POINTER=JSON")
|
||||
}
|
||||
path, err := configkit.ParsePath(pointer)
|
||||
if err != nil {
|
||||
return configkit.Override{}, fmt.Errorf("invalid override path: %w", err)
|
||||
}
|
||||
value, err := commandkit.ParseCLIJSON(jsonText)
|
||||
if err != nil {
|
||||
return configkit.Override{}, fmt.Errorf("invalid override JSON: %w", err)
|
||||
}
|
||||
return configkit.Override{Path: path, Value: value, Flag: flag}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func cloneSelection(selection Selection) Selection {
|
||||
if selection.Overrides != nil {
|
||||
selection.Overrides = append([]configkit.Override(nil), selection.Overrides...)
|
||||
for index := range selection.Overrides {
|
||||
selection.Overrides[index].Value = cloneCLIValue(selection.Overrides[index].Value)
|
||||
}
|
||||
}
|
||||
return selection
|
||||
}
|
||||
|
||||
func cloneCLIValue(value any) any {
|
||||
switch value := value.(type) {
|
||||
case []any:
|
||||
copy := make([]any, len(value))
|
||||
for index, element := range value {
|
||||
copy[index] = cloneCLIValue(element)
|
||||
}
|
||||
return copy
|
||||
case map[string]any:
|
||||
copy := make(map[string]any, len(value))
|
||||
for key, element := range value {
|
||||
copy[key] = cloneCLIValue(element)
|
||||
}
|
||||
return copy
|
||||
default:
|
||||
return value
|
||||
}
|
||||
}
|
||||
94
integrations/ckconfig/overrides_test.go
Normal file
94
integrations/ckconfig/overrides_test.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package ckconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestOverrideAssignmentsAreCopiedPerScopeAndPreservedInOrder(t *testing.T) {
|
||||
var received []Selection
|
||||
makeScope := func(name string) Scope[struct{}, struct{}] {
|
||||
return Scope[struct{}, struct{}]{Name: name, Operations: []Operation{Validate}, Features: ScopeFeatures{Overrides: true}, Acquire: func(_ context.Context, req Request, _, _ struct{}) (commandkit.Acquired[View], error) {
|
||||
received = append(received, cloneSelection(req.Selection))
|
||||
if name == "app" {
|
||||
req.Selection.Overrides[0].Value.(map[string]any)["numbers"].([]any)[0] = int64(999)
|
||||
}
|
||||
return commandkit.Acquired[View]{}, nil
|
||||
}}
|
||||
}
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{makeScope("app"), makeScope("other")}}))
|
||||
result := app.Execute(context.Background(), []string{"config", "validate", "--scope=all", "--set=/nested={\"numbers\":[1,2.5],\"v\":\"a=b\"}", "--set=/nested=null", "--set=/false=false", "--set=/zero=0", "--set=/empty=\"\""}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || len(received) != 2 || !reflect.DeepEqual(received[0].Overrides, received[1].Overrides) || len(received[0].Overrides) != 5 {
|
||||
t.Fatalf("result=%#v selections=%#v", result, received)
|
||||
}
|
||||
first := received[1].Overrides
|
||||
object, ok := first[0].Value.(map[string]any)
|
||||
if !ok || !reflect.DeepEqual(object["numbers"], []any{int64(1), float64(2.5)}) || object["v"] != "a=b" || first[0].Flag != "--set" || first[1].Path.String() != "/nested" || first[1].Value != nil || first[2].Value != false || first[3].Value != int64(0) || first[4].Value != "" {
|
||||
t.Fatalf("records=%#v", first)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverridePreflightAndComparisonSides(t *testing.T) {
|
||||
calls, factories := 0, 0
|
||||
var pair ComparisonRequest[struct{}]
|
||||
supported := Scope[struct{}, struct{}]{Name: "app", Operations: []Operation{Validate, Diff}, Features: ScopeFeatures{Overrides: true}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[View]{}, nil
|
||||
}, Compare: func(_ context.Context, value ComparisonRequest[struct{}], _ struct{}) (commandkit.Acquired[[]configkit.Difference], error) {
|
||||
calls++
|
||||
pair = value
|
||||
return commandkit.Acquired[[]configkit.Difference]{}, nil
|
||||
}}
|
||||
unsupported := Scope[struct{}, struct{}]{Name: "other", Operations: []Operation{Validate}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[View]{}, nil
|
||||
}}
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{NewInput: func() struct{} { factories++; return struct{}{} }, Scopes: []Scope[struct{}, struct{}]{supported, unsupported}}))
|
||||
for _, args := range [][]string{{"config", "validate", "--scope=other", "--set=/x=1"}, {"config", "validate", "--scope=all", "--set=/x=1"}, {"config", "validate", "--set=/bad"}, {"config", "validate", "--set=/bad={"}, {"config", "validate", "--set=bad=1"}} {
|
||||
result := app.Execute(context.Background(), args, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeUsage || calls != 0 || factories != 0 {
|
||||
t.Fatalf("preflight %v: %#v, calls=%d factories=%d", args, result, calls, factories)
|
||||
}
|
||||
}
|
||||
result := app.Execute(context.Background(), []string{"config", "diff", "--set=/x=1", "--against-set=/x=2", "--against-set=/y=[]"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || len(pair.Left.Selection.Overrides) != 1 || len(pair.Right.Selection.Overrides) != 2 || pair.Left.Selection.Overrides[0].Flag != "--set" || pair.Right.Selection.Overrides[0].Flag != "--against-set" || pair.Left.Selection.Overrides[0].Value != int64(1) || pair.Right.Selection.Overrides[0].Value != int64(2) {
|
||||
t.Fatalf("pair=%#v outcome=%#v", pair, result)
|
||||
}
|
||||
result = app.Execute(context.Background(), []string{"config", "diff", "--set=/x=1"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || pair.Right.Selection.Overrides != nil {
|
||||
t.Fatalf("omitted right = %#v", pair.Right.Selection)
|
||||
}
|
||||
without := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{unsupported}}))
|
||||
if result := without.Execute(context.Background(), []string{"config", "validate", "--set=/x=1"}, commandkit.Streams{Out: io.Discard, Err: io.Discard}); result.Kind != commandkit.OutcomeUsage {
|
||||
t.Fatalf("unavailable flag: %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverrideNativeLoadErrorAndProvenance(t *testing.T) {
|
||||
type settings struct {
|
||||
Name string `yaml:"name"`
|
||||
}
|
||||
scope := FromConfigKit("app", "", func(_ context.Context, selection Selection, _, _ struct{}) (*configkit.Result[settings], error) {
|
||||
return configkit.Load(configkit.Mapping("input", map[string]any{"name": "before"}), configkit.Options[settings]{Overrides: selection.Overrides})
|
||||
})
|
||||
scope.Features.Overrides = true
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
|
||||
var out bytes.Buffer
|
||||
result := app.Execute(context.Background(), []string{"config", "explain", "--path=/name", "--set=/name=\"after\""}, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || !strings.Contains(out.String(), "--set") {
|
||||
t.Fatalf("provenance: %#v %q", result, out.String())
|
||||
}
|
||||
result = app.Execute(context.Background(), []string{"config", "validate", "--set==1"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
var loadErr *configkit.LoadError
|
||||
if result.Kind != commandkit.OutcomeOperational || !errors.As(result.Cause, &loadErr) {
|
||||
t.Fatalf("native invalid root override: %#v", result)
|
||||
}
|
||||
}
|
||||
@@ -18,10 +18,10 @@ func TestBufferedReportCancellationBeforeDelivery(t *testing.T) {
|
||||
app := newConfigTestApp(t, commandkit.NewCommand(commandkit.CommandSpec[struct{}]{
|
||||
Name: "report",
|
||||
Run: func(invocation commandkit.Invocation, _ struct{}) commandkit.Outcome {
|
||||
return renderPreparedConfigReport(invocation, commandkit.Explanation{Message: "selected context"}, func() ([]byte, error) {
|
||||
return renderPreparedConfigReport(invocation, commandkit.Explanation{Message: "selected context"}, func() (any, error) {
|
||||
prepared = true
|
||||
cancel()
|
||||
return []byte("prepared report"), nil
|
||||
return "prepared report", nil
|
||||
})
|
||||
},
|
||||
}))
|
||||
@@ -54,8 +54,8 @@ func TestBufferedReportDoesNotRejectCancellationAfterDeliveryStarts(t *testing.T
|
||||
app := newConfigTestApp(t, commandkit.NewCommand(commandkit.CommandSpec[struct{}]{
|
||||
Name: "report",
|
||||
Run: func(invocation commandkit.Invocation, _ struct{}) commandkit.Outcome {
|
||||
return renderPreparedConfigReport(invocation, commandkit.Explanation{}, func() ([]byte, error) {
|
||||
return []byte("report"), nil
|
||||
return renderPreparedConfigReport(invocation, commandkit.Explanation{}, func() (any, error) {
|
||||
return "report", nil
|
||||
})
|
||||
},
|
||||
}))
|
||||
|
||||
152
integrations/ckconfig/shared_report_test.go
Normal file
152
integrations/ckconfig/shared_report_test.go
Normal file
@@ -0,0 +1,152 @@
|
||||
package ckconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestShowSharedFormatsAndScopeShape(t *testing.T) {
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{{
|
||||
Name: "app", Operations: []Operation{Show}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
return commandkit.Acquired[View]{Value: View{Effective: effectiveValue("'false'\n")}}, nil
|
||||
},
|
||||
}}}))
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
args []string
|
||||
want string
|
||||
}{
|
||||
{"automatic", []string{"config", "show"}, "false\n"},
|
||||
{"text", []string{"config", "show", "--format=text"}, "false\n"},
|
||||
{"yaml", []string{"config", "show", "--format=yaml"}, "\"false\"\n"},
|
||||
{"json", []string{"config", "show", "--format=json"}, "\"false\"\n"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
result := app.Execute(t.Context(), tc.args, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
if tc.name == "yaml" {
|
||||
value, err := commandkit.DecodeYAMLReport(&out)
|
||||
if err != nil || value != "false" || result.Status != 0 {
|
||||
t.Fatalf("%#v value=%#v err=%v", result, value, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if result.Status != 0 || out.String() != tc.want {
|
||||
t.Fatalf("%#v output=%q", result, out.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
var out bytes.Buffer
|
||||
result := app.Execute(t.Context(), []string{"config", "show", "--scope=all", "--format=json"}, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
var decoded map[string]any
|
||||
if err := json.Unmarshal(out.Bytes(), &decoded); err != nil || result.Status != 0 || !reflect.DeepEqual(decoded, map[string]any{"app": "false"}) {
|
||||
t.Fatalf("%#v output=%q decoded=%#v err=%v", result, out.String(), decoded, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShowConversionFailureIsPresentationEvidence(t *testing.T) {
|
||||
for _, quiet := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "ordinary", true: "quiet"}[quiet], func(t *testing.T) {
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{{Name: "app", Operations: []Operation{Show}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
return commandkit.Acquired[View]{Value: View{Effective: effectiveValue("x: [invalid\n")}}, nil
|
||||
}}}}))
|
||||
args := []string{"config", "show"}
|
||||
if quiet {
|
||||
args = append(args, "--quiet")
|
||||
}
|
||||
var out bytes.Buffer
|
||||
result := app.Execute(t.Context(), args, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeOperational || result.Presentation.Output.RenderError == nil || out.Len() != 0 {
|
||||
t.Fatalf("%#v output=%q", result, out.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidationSubmitsOneReportAfterAcquisitionStops(t *testing.T) {
|
||||
failure := errors.New("invalid configuration")
|
||||
calls := 0
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{
|
||||
{Name: "app", Operations: []Operation{Validate}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[View]{}, nil
|
||||
}},
|
||||
{Name: "middle", Operations: []Operation{Validate}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[View]{}, failure
|
||||
}},
|
||||
{Name: "third", Operations: []Operation{Validate}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[View]{}, nil
|
||||
}},
|
||||
}}))
|
||||
var out bytes.Buffer
|
||||
result := app.Execute(t.Context(), []string{"config", "validate", "--scope=all", "--format=json"}, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
var report struct {
|
||||
Scopes []struct{ Scope, Outcome string }
|
||||
}
|
||||
dec := json.NewDecoder(&out)
|
||||
if err := dec.Decode(&report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := dec.Decode(new(any)); err != io.EOF {
|
||||
t.Fatalf("additional JSON: %v", err)
|
||||
}
|
||||
if !errors.Is(result.Cause, failure) || calls != 2 || len(report.Scopes) != 2 || report.Scopes[0].Outcome != "valid" || report.Scopes[1].Outcome != "failed" {
|
||||
t.Fatalf("result=%#v calls=%d report=%#v", result, calls, report)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidationDeliveryFailureDoesNotStopAcquisition(t *testing.T) {
|
||||
writeErr := errors.New("write failed")
|
||||
calls := 0
|
||||
acquire := func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
|
||||
calls++
|
||||
return commandkit.Acquired[View]{}, nil
|
||||
}
|
||||
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{{Name: "app", Operations: []Operation{Validate}, Acquire: acquire}, {Name: "second", Operations: []Operation{Validate}, Acquire: acquire}}}))
|
||||
result := app.Execute(t.Context(), []string{"config", "validate", "--scope=all"}, commandkit.Streams{Out: failingOutput{err: writeErr}, Err: io.Discard})
|
||||
if calls != 2 || !errors.Is(result.Presentation.Output.WriteError, writeErr) || result.Status == 0 {
|
||||
t.Fatalf("result=%#v calls=%d", result, calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigurationReportsSupportSharedFormats(t *testing.T) {
|
||||
type settings struct {
|
||||
Greeting string `yaml:"greeting"`
|
||||
}
|
||||
app := newConfigTestApp(t, AppCommand(func(context.Context, Selection) (*configkit.Result[settings], error) {
|
||||
return configkit.Load(configkit.Mapping("fixture", map[string]any{"greeting": "hello"}), configkit.Options[settings]{})
|
||||
}))
|
||||
for _, args := range [][]string{{"scopes"}, {"show"}, {"sources"}, {"explain", "--path=/greeting"}, {"diff"}, {"validate"}} {
|
||||
for _, format := range []string{"text", "yaml", "json"} {
|
||||
t.Run(args[0]+"/"+format, func(t *testing.T) {
|
||||
argv := append([]string{"config"}, args...)
|
||||
argv = append(argv, "--format="+format)
|
||||
var out bytes.Buffer
|
||||
result := app.Execute(t.Context(), argv, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
if result.Status != 0 {
|
||||
t.Fatalf("%#v output=%q", result, out.String())
|
||||
}
|
||||
if format == "json" {
|
||||
dec := json.NewDecoder(&out)
|
||||
var value any
|
||||
if err := dec.Decode(&value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := dec.Decode(&value); err != io.EOF {
|
||||
t.Fatalf("extra JSON: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,7 @@ import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"unicode"
|
||||
"strings"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
)
|
||||
@@ -23,41 +22,53 @@ func runConfigShow[I, S any](invocation commandkit.Invocation, plan *configOpera
|
||||
return configFailure("Configuration show was canceled.", commandkit.Explanation{}, err)
|
||||
}
|
||||
if selected.scope.scope.Acquire == nil {
|
||||
message := fmt.Sprintf("Configuration scope %q has no acquisition callback.", selected.scope.scope.Name)
|
||||
return commandkit.Failure(message)
|
||||
return commandkit.Failure(fmt.Sprintf("Configuration scope %q has no acquisition callback.", selected.scope.scope.Name))
|
||||
}
|
||||
acquired, acquireErr := selected.scope.scope.Acquire(invocation.Context, Request{
|
||||
Operation: Show,
|
||||
Selection: plan.selection,
|
||||
}, selected.input, state)
|
||||
acquired, acquireErr := selected.scope.scope.Acquire(invocation.Context, Request{Operation: Show, Selection: selected.selection}, selected.input, state)
|
||||
if acquireErr != nil {
|
||||
return configAcquisitionFailure(reporter, "show", selected.scope.scope.Name, acquired, acquireErr)
|
||||
}
|
||||
queueConfigDiagnostics(reporter, acquired.Diagnostics)
|
||||
queueConfigAcquisition(reporter, acquired)
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return configFailure("Configuration show was canceled.", acquired.Explanation, err)
|
||||
}
|
||||
if plan.pathSet {
|
||||
if acquired.Value.Explanation == nil {
|
||||
return configFailure("Configuration scope did not provide explanation data.", acquired.Explanation, fmt.Errorf("configuration scope %q declared path show without an explanation reader", selected.scope.scope.Name))
|
||||
}
|
||||
explanation, found := acquired.Value.Explanation.Explain(plan.path)
|
||||
if !found || !explanation.Effective.Present {
|
||||
return configFailure("The requested effective configuration path is not available.", acquired.Explanation, fmt.Errorf("configuration path %q is not effective in scope %q", plan.path.String(), selected.scope.scope.Name))
|
||||
}
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return configFailure("Configuration show was canceled.", acquired.Explanation, err)
|
||||
}
|
||||
var value any
|
||||
err := reporter.RenderOutput(func(io.Writer) error {
|
||||
var err error
|
||||
value, err = commandkit.DecodeYAMLReport(strings.NewReader(explanation.Effective.YAML))
|
||||
return err
|
||||
})
|
||||
if err == nil {
|
||||
if canceled := invocation.Context.Err(); canceled != nil {
|
||||
return configFailure("Configuration show was canceled.", acquired.Explanation, canceled)
|
||||
}
|
||||
_ = reporter.Report(commandkit.Report{Value: value})
|
||||
}
|
||||
return commandkit.Success()
|
||||
}
|
||||
if acquired.Value.Effective == nil {
|
||||
message := fmt.Sprintf("Configuration scope %q did not provide an effective configuration writer.", selected.scope.scope.Name)
|
||||
return commandkit.Failure(message)
|
||||
return commandkit.Failure(fmt.Sprintf("Configuration scope %q did not provide an effective configuration writer.", selected.scope.scope.Name))
|
||||
}
|
||||
documents = append(documents, effectiveDocument{name: selected.scope.scope.Name, view: acquired.Value})
|
||||
}
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return configFailure("Configuration show was canceled.", commandkit.Explanation{}, err)
|
||||
}
|
||||
if len(documents) == 1 && plan.scopeName != "all" {
|
||||
err := reporter.RenderOutput(func(writer io.Writer) error {
|
||||
return documents[0].view.Effective.WriteEffective(writer)
|
||||
})
|
||||
if err != nil && invocation.Context.Err() != nil {
|
||||
return configFailure("Configuration show was canceled.", commandkit.Explanation{}, invocation.Context.Err())
|
||||
}
|
||||
return commandkit.Success()
|
||||
}
|
||||
|
||||
err := reporter.RenderOutput(func(writer io.Writer) error {
|
||||
for index, document := range documents {
|
||||
var value any
|
||||
err := reporter.RenderOutput(func(io.Writer) error {
|
||||
values := make(map[string]any, len(documents))
|
||||
for _, document := range documents {
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -65,112 +76,28 @@ func runConfigShow[I, S any](invocation commandkit.Invocation, plan *configOpera
|
||||
if err := document.view.Effective.WriteEffective(&native); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
framed, hasDirective := frameEffectiveYAML(document.name, native.Bytes())
|
||||
if index > 0 && hasDirective {
|
||||
if _, err := io.WriteString(writer, "...\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if index < len(documents)-1 && len(framed) > 0 && framed[len(framed)-1] != '\n' {
|
||||
framed = append(framed, '\n')
|
||||
}
|
||||
if _, err := writer.Write(framed); err != nil {
|
||||
decoded, err := commandkit.DecodeYAMLReport(&native)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
values[document.name] = decoded
|
||||
}
|
||||
if plan.scopeName == "all" {
|
||||
value = values
|
||||
} else {
|
||||
value = values[documents[0].name]
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil && invocation.Context.Err() != nil {
|
||||
return configFailure("Configuration show was canceled.", commandkit.Explanation{}, invocation.Context.Err())
|
||||
if err != nil {
|
||||
if canceled := invocation.Context.Err(); canceled != nil {
|
||||
return configFailure("Configuration show was canceled.", commandkit.Explanation{}, canceled)
|
||||
}
|
||||
return commandkit.Success()
|
||||
}
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return configFailure("Configuration show was canceled.", commandkit.Explanation{}, err)
|
||||
}
|
||||
_ = reporter.Report(commandkit.Report{Value: value})
|
||||
return commandkit.Success()
|
||||
}
|
||||
|
||||
type yamlPreamble struct {
|
||||
markerStart int
|
||||
markerEnd int
|
||||
markerFound bool
|
||||
inlineMarker bool
|
||||
preambleEnd int
|
||||
hasDirective bool
|
||||
}
|
||||
|
||||
func analyzeYAMLPreamble(native []byte) yamlPreamble {
|
||||
var analysis yamlPreamble
|
||||
for start := 0; start < len(native); {
|
||||
end := len(native)
|
||||
if newline := bytes.IndexByte(native[start:], '\n'); newline >= 0 {
|
||||
end = start + newline + 1
|
||||
}
|
||||
lineEnd := end
|
||||
if lineEnd > start && native[lineEnd-1] == '\n' {
|
||||
lineEnd--
|
||||
}
|
||||
trimmed := bytes.TrimSpace(native[start:lineEnd])
|
||||
if isYAMLDocumentStart(trimmed) {
|
||||
content := bytes.TrimSpace(trimmed[3:])
|
||||
analysis.markerStart = start
|
||||
analysis.markerEnd = end
|
||||
analysis.markerFound = true
|
||||
analysis.inlineMarker = len(content) > 0 && content[0] != '#'
|
||||
return analysis
|
||||
}
|
||||
if bytes.HasPrefix(trimmed, []byte("%YAML ")) || bytes.HasPrefix(trimmed, []byte("%TAG ")) {
|
||||
analysis.hasDirective = true
|
||||
}
|
||||
if len(trimmed) == 0 || trimmed[0] == '#' || bytes.HasPrefix(trimmed, []byte("%YAML ")) || bytes.HasPrefix(trimmed, []byte("%TAG ")) {
|
||||
analysis.preambleEnd = end
|
||||
} else {
|
||||
return analysis
|
||||
}
|
||||
start = end
|
||||
}
|
||||
return analysis
|
||||
}
|
||||
|
||||
func frameEffectiveYAML(scope string, native []byte) ([]byte, bool) {
|
||||
analysis := analyzeYAMLPreamble(native)
|
||||
label := scope
|
||||
for _, character := range scope {
|
||||
if unicode.IsControl(character) {
|
||||
label = strconv.Quote(scope)
|
||||
break
|
||||
}
|
||||
}
|
||||
comment := []byte("# scope: " + label + "\n")
|
||||
if analysis.markerFound {
|
||||
out := make([]byte, 0, len(native)+len(comment))
|
||||
if analysis.inlineMarker {
|
||||
out = append(out, native[:analysis.markerStart]...)
|
||||
out = append(out, comment...)
|
||||
out = append(out, native[analysis.markerStart:]...)
|
||||
return out, analysis.hasDirective
|
||||
}
|
||||
out = append(out, native[:analysis.markerEnd]...)
|
||||
if analysis.markerEnd > analysis.markerStart && native[analysis.markerEnd-1] != '\n' {
|
||||
out = append(out, '\n')
|
||||
}
|
||||
out = append(out, comment...)
|
||||
out = append(out, native[analysis.markerEnd:]...)
|
||||
return out, analysis.hasDirective
|
||||
}
|
||||
result := make([]byte, 0, len(native)+len(comment)+5)
|
||||
if analysis.hasDirective {
|
||||
result = append(result, native[:analysis.preambleEnd]...)
|
||||
}
|
||||
result = append(result, []byte("---\n")...)
|
||||
result = append(result, comment...)
|
||||
if analysis.hasDirective {
|
||||
result = append(result, native[analysis.preambleEnd:]...)
|
||||
} else {
|
||||
result = append(result, native...)
|
||||
}
|
||||
return result, analysis.hasDirective
|
||||
}
|
||||
|
||||
func isYAMLDocumentStart(line []byte) bool {
|
||||
return bytes.HasPrefix(line, []byte("---")) && (len(line) == 3 || line[3] == ' ' || line[3] == '\t')
|
||||
}
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
package ckconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
func TestEffectiveYAMLFramingPreservesOneNativeDocument(t *testing.T) {
|
||||
for _, native := range []string{
|
||||
"--- {setting: value}\n", "---\t{setting: value}\n", "--- value\n",
|
||||
"--- |\n first\n second\n", "--- # authored\nsetting: value\n",
|
||||
"setting: value\n", "%YAML 1.1\n--- {setting: value}\n",
|
||||
} {
|
||||
t.Run(native, func(t *testing.T) {
|
||||
var want any
|
||||
if err := yaml.Unmarshal([]byte(native), &want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
framed, _ := frameEffectiveYAML("app", []byte(native))
|
||||
withoutLabel := bytes.Replace(framed, []byte("# scope: app\n"), nil, 1)
|
||||
if !strings.HasPrefix(native, "---") && !strings.HasPrefix(native, "%") {
|
||||
withoutLabel = bytes.TrimPrefix(withoutLabel, []byte("---\n"))
|
||||
}
|
||||
if !bytes.Equal(withoutLabel, []byte(native)) {
|
||||
t.Fatalf("native content changed: %q", framed)
|
||||
}
|
||||
if !bytes.Contains(framed, []byte("# scope: app\n")) {
|
||||
t.Fatalf("missing label: %q", framed)
|
||||
}
|
||||
decoder := yaml.NewDecoder(bytes.NewReader(framed))
|
||||
var got any
|
||||
if err := decoder.Decode(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got=%#v want=%#v", got, want)
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
t.Fatalf("extra document: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEffectiveYAMLFramingPreservesBoundariesAndDirectives(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
scope string
|
||||
native string
|
||||
directive bool
|
||||
label string
|
||||
}{
|
||||
{name: "no trailing newline", scope: "app", native: "value: plain", label: "# scope: app\n"},
|
||||
{name: "CRLF", scope: "app", native: "# authored\r\n---\r\nvalue: yes\r\n", label: "# scope: app\n"},
|
||||
{name: "directive preamble", scope: "app", native: "%YAML 1.1\n# authored\n---\nvalue: yes", directive: true, label: "# scope: app\n"},
|
||||
{name: "control character label", scope: "line\nbreak", native: "value: yes", label: "# scope: \"line\\nbreak\"\n"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var want any
|
||||
if err := yaml.Unmarshal([]byte(test.native), &want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
framed, hasDirective := frameEffectiveYAML(test.scope, []byte(test.native))
|
||||
if hasDirective != test.directive {
|
||||
t.Fatalf("hasDirective = %t, want %t", hasDirective, test.directive)
|
||||
}
|
||||
withoutLabel := bytes.Replace(framed, []byte(test.label), nil, 1)
|
||||
if !strings.HasPrefix(test.native, "---") && !strings.HasPrefix(test.native, "%") {
|
||||
withoutLabel = bytes.TrimPrefix(withoutLabel, []byte("---\n"))
|
||||
}
|
||||
if !bytes.Equal(withoutLabel, []byte(test.native)) {
|
||||
t.Fatalf("native content changed: got %q want %q", withoutLabel, test.native)
|
||||
}
|
||||
if !bytes.Contains(framed, []byte(test.label)) {
|
||||
t.Fatalf("missing scope label %q in %q", test.label, framed)
|
||||
}
|
||||
decoder := yaml.NewDecoder(bytes.NewReader(framed))
|
||||
var first any
|
||||
if err := decoder.Decode(&first); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(first, want) {
|
||||
t.Fatalf("decoded value = %#v, want %#v", first, want)
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
t.Fatalf("unexpected extra YAML document: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,59 +1,57 @@
|
||||
package ckconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"text/template"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
type sourceReport struct {
|
||||
Scope string `yaml:"scope"`
|
||||
Sources []sourceDTO `yaml:"sources"`
|
||||
Scope string `json:"scope"`
|
||||
Sources []sourceDTO `json:"sources"`
|
||||
}
|
||||
|
||||
type sourceDTO struct {
|
||||
ID string `yaml:"id"`
|
||||
Label string `yaml:"label"`
|
||||
Path string `yaml:"path"`
|
||||
Destination string `yaml:"destination"`
|
||||
Placement string `yaml:"placement"`
|
||||
DestinationIsFallback bool `yaml:"destination_is_fallback"`
|
||||
Layer string `yaml:"layer"`
|
||||
Kind string `yaml:"kind"`
|
||||
UnderlayIndex int `yaml:"underlay_index"`
|
||||
ImportedFrom *locationDTO `yaml:"imported_from"`
|
||||
VersionEvidence *sourceVersionEvidenceDTO `yaml:"version_evidence"`
|
||||
EmptyImportSelections []emptyImportSelectionDTO `yaml:"empty_import_selections"`
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
Path string `json:"path"`
|
||||
Destination string `json:"destination"`
|
||||
Placement string `json:"placement"`
|
||||
DestinationIsFallback bool `json:"destination_is_fallback"`
|
||||
Layer string `json:"layer"`
|
||||
Kind string `json:"kind"`
|
||||
UnderlayIndex int `json:"underlay_index"`
|
||||
ImportedFrom *locationDTO `json:"imported_from"`
|
||||
VersionEvidence *sourceVersionEvidenceDTO `json:"version_evidence"`
|
||||
EmptyImportSelections []emptyImportSelectionDTO `json:"empty_import_selections"`
|
||||
}
|
||||
|
||||
type emptyImportSelectionDTO struct {
|
||||
Path string `yaml:"path"`
|
||||
Location locationDTO `yaml:"location"`
|
||||
Selector string `yaml:"selector"`
|
||||
Path string `json:"path"`
|
||||
Location locationDTO `json:"location"`
|
||||
Selector string `json:"selector"`
|
||||
}
|
||||
|
||||
type locationDTO struct {
|
||||
SourceID string `yaml:"source_id"`
|
||||
Line int `yaml:"line"`
|
||||
Column int `yaml:"column"`
|
||||
SourceID string `json:"source_id"`
|
||||
Line int `json:"line"`
|
||||
Column int `json:"column"`
|
||||
}
|
||||
|
||||
type sourceVersionEvidenceDTO struct {
|
||||
Path string `yaml:"path"`
|
||||
Version versionDTO `yaml:"version"`
|
||||
Location *locationDTO `yaml:"location"`
|
||||
Redacted bool `yaml:"redacted"`
|
||||
Path string `json:"path"`
|
||||
Version versionDTO `json:"version"`
|
||||
Location *locationDTO `json:"location"`
|
||||
Redacted bool `json:"redacted"`
|
||||
}
|
||||
|
||||
type versionDTO struct {
|
||||
Present bool `yaml:"present"`
|
||||
Null bool `yaml:"null"`
|
||||
Text string `yaml:"text"`
|
||||
Present bool `json:"present"`
|
||||
Null bool `json:"null"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func runConfigSources[I, S any](invocation commandkit.Invocation, plan *configOperationPlan[I, S], state S) commandkit.Outcome {
|
||||
@@ -69,16 +67,18 @@ func runConfigSources[I, S any](invocation commandkit.Invocation, plan *configOp
|
||||
}
|
||||
acquired, acquireErr := selected.scope.scope.Acquire(invocation.Context, Request{
|
||||
Operation: Sources,
|
||||
Selection: plan.selection,
|
||||
Selection: selected.selection,
|
||||
}, selected.input, state)
|
||||
queueConfigDiagnostics(reporter, acquired.Diagnostics)
|
||||
if acquireErr != nil {
|
||||
return configFailure(fmt.Sprintf("Unable to list sources for configuration scope %q.", name), acquired.Explanation, acquireErr)
|
||||
}
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
queueConfigAcquisition(reporter, acquired)
|
||||
if acquireErr == nil && invocation.Context.Err() != nil {
|
||||
err := invocation.Context.Err()
|
||||
return configFailure("Configuration source listing was canceled.", acquired.Explanation, err)
|
||||
}
|
||||
if acquired.Value.Sources == nil {
|
||||
if acquireErr != nil {
|
||||
explanation := sourceSelectionExplanation(acquired.Explanation, "Source inventory is unavailable.")
|
||||
return configFailure(fmt.Sprintf("Unable to list sources for configuration scope %q.", name), explanation, acquireErr)
|
||||
}
|
||||
cause := fmt.Errorf("configuration scope %q did not provide a source reader", name)
|
||||
return configFailure("Configuration scope did not provide source information.", acquired.Explanation, cause)
|
||||
}
|
||||
@@ -86,6 +86,9 @@ func runConfigSources[I, S any](invocation commandkit.Invocation, plan *configOp
|
||||
sources := acquired.Value.Sources.Sources()
|
||||
document := sourceReport{Scope: name, Sources: make([]sourceDTO, 0, len(sources))}
|
||||
for _, source := range sources {
|
||||
if plan.sourceID.Set && source.ID != plan.sourceID.Value {
|
||||
continue
|
||||
}
|
||||
placement := "mapping"
|
||||
if source.PlacementMode == configkit.PlacementModeSequenceItem {
|
||||
placement = "sequence_item"
|
||||
@@ -124,77 +127,66 @@ func runConfigSources[I, S any](invocation commandkit.Invocation, plan *configOp
|
||||
item.EmptyImportSelections = append(item.EmptyImportSelections, emptyImportSelectionDTO{Path: selection.Path.String(), Location: locationDTO{SourceID: selection.Location.SourceID, Line: selection.Location.Line, Column: selection.Location.Column}, Selector: string(selection.Selector)})
|
||||
}
|
||||
document.Sources = append(document.Sources, item)
|
||||
if plan.sourceID.Set {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
if plan.sourceID.Set && len(document.Sources) == 0 {
|
||||
message := fmt.Sprintf("Source ID %q was not found in configuration scope %q.", plan.sourceID.Value, name)
|
||||
if acquireErr != nil {
|
||||
return configFailure(fmt.Sprintf("Unable to list sources for configuration scope %q.", name), sourceSelectionExplanation(acquired.Explanation, message), acquireErr)
|
||||
}
|
||||
return configFailure(message, acquired.Explanation, fmt.Errorf("source ID %q was not found", plan.sourceID.Value))
|
||||
}
|
||||
if acquireErr == nil && invocation.Context.Err() != nil {
|
||||
err := invocation.Context.Err()
|
||||
return configFailure("Configuration source listing was canceled.", acquired.Explanation, err)
|
||||
}
|
||||
return renderPreparedConfigReport(invocation, acquired.Explanation, func() ([]byte, error) {
|
||||
var report bytes.Buffer
|
||||
if plan.format == "yaml" {
|
||||
if err := encodeYAML(&report, document); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
writeSourceReportText(&report, document)
|
||||
}
|
||||
return report.Bytes(), nil
|
||||
_ = reporter.Report(commandkit.Report{Value: document, TextTemplate: sourceTextTemplate})
|
||||
if acquireErr != nil {
|
||||
return configFailure(fmt.Sprintf("Unable to list sources for configuration scope %q.", name), acquired.Explanation, acquireErr)
|
||||
}
|
||||
return commandkit.Success()
|
||||
}
|
||||
|
||||
func sourceSelectionExplanation(explanation commandkit.Explanation, message string) commandkit.Explanation {
|
||||
explanation.Details = append(append([]commandkit.Detail(nil), explanation.Details...), func(writer io.Writer) error {
|
||||
_, err := fmt.Fprintln(writer, message)
|
||||
return err
|
||||
})
|
||||
return explanation
|
||||
}
|
||||
|
||||
func writeSourceReportText(writer *bytes.Buffer, document sourceReport) {
|
||||
_, _ = fmt.Fprintf(writer, "Scope: %s\n", strconv.Quote(document.Scope))
|
||||
if len(document.Sources) == 0 {
|
||||
_, _ = writer.WriteString("Sources: []\n")
|
||||
return
|
||||
}
|
||||
_, _ = writer.WriteString("Sources:\n")
|
||||
for _, source := range document.Sources {
|
||||
_, _ = fmt.Fprintf(writer, " - id: %s\n", strconv.Quote(source.ID))
|
||||
_, _ = fmt.Fprintf(writer, " label: %s\n", strconv.Quote(source.Label))
|
||||
_, _ = fmt.Fprintf(writer, " path: %s\n", strconv.Quote(source.Path))
|
||||
_, _ = fmt.Fprintf(writer, " destination: %s\n", strconv.Quote(source.Destination))
|
||||
_, _ = fmt.Fprintf(writer, " placement: %s\n", strconv.Quote(source.Placement))
|
||||
_, _ = fmt.Fprintf(writer, " destination_is_fallback: %t\n", source.DestinationIsFallback)
|
||||
_, _ = fmt.Fprintf(writer, " layer: %s\n", strconv.Quote(source.Layer))
|
||||
_, _ = fmt.Fprintf(writer, " kind: %s\n", strconv.Quote(source.Kind))
|
||||
_, _ = fmt.Fprintf(writer, " underlay_index: %d\n", source.UnderlayIndex)
|
||||
if source.ImportedFrom == nil {
|
||||
_, _ = writer.WriteString(" imported_from: null\n")
|
||||
} else {
|
||||
_, _ = fmt.Fprintf(writer, " imported_from: {source_id: %s, line: %d, column: %d}\n",
|
||||
strconv.Quote(source.ImportedFrom.SourceID), source.ImportedFrom.Line, source.ImportedFrom.Column)
|
||||
}
|
||||
if source.VersionEvidence == nil {
|
||||
_, _ = writer.WriteString(" version_evidence: null\n")
|
||||
} else {
|
||||
check := source.VersionEvidence
|
||||
_, _ = fmt.Fprintf(writer, " version_evidence:\n path: %s\n", strconv.Quote(check.Path))
|
||||
_, _ = fmt.Fprintf(writer, " version:\n present: %t\n null: %t\n text: %s\n",
|
||||
check.Version.Present, check.Version.Null, strconv.Quote(check.Version.Text))
|
||||
if check.Location == nil {
|
||||
_, _ = writer.WriteString(" location: null\n")
|
||||
} else {
|
||||
_, _ = fmt.Fprintf(writer, " location: {source_id: %s, line: %d, column: %d}\n",
|
||||
strconv.Quote(check.Location.SourceID), check.Location.Line, check.Location.Column)
|
||||
}
|
||||
_, _ = fmt.Fprintf(writer, " redacted: %t\n", check.Redacted)
|
||||
}
|
||||
if len(source.EmptyImportSelections) == 0 {
|
||||
_, _ = writer.WriteString(" empty_import_selections: []\n")
|
||||
} else {
|
||||
_, _ = writer.WriteString(" empty_import_selections:\n")
|
||||
for _, selection := range source.EmptyImportSelections {
|
||||
_, _ = fmt.Fprintf(writer, " - path: %s\n location: {source_id: %s, line: %d, column: %d}\n selector: %s\n", strconv.Quote(selection.Path), strconv.Quote(selection.Location.SourceID), selection.Location.Line, selection.Location.Column, strconv.Quote(selection.Selector))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func encodeYAML(writer io.Writer, document any) error {
|
||||
encoder := yaml.NewEncoder(writer)
|
||||
encoder.SetIndent(2)
|
||||
return encoder.Encode(document)
|
||||
}
|
||||
var sourceTextTemplate = template.Must(commandkit.ParseTextTemplate("sources", `Scope: {{printf "%q" .Scope}}
|
||||
{{if .Sources}}Sources:
|
||||
{{range .Sources}} - id: {{printf "%q" .ID}}
|
||||
label: {{printf "%q" .Label}}
|
||||
path: {{printf "%q" .Path}}
|
||||
destination: {{printf "%q" .Destination}}
|
||||
placement: {{printf "%q" .Placement}}
|
||||
destination_is_fallback: {{.DestinationIsFallback}}
|
||||
layer: {{printf "%q" .Layer}}
|
||||
kind: {{printf "%q" .Kind}}
|
||||
underlay_index: {{.UnderlayIndex}}
|
||||
{{if .ImportedFrom}} imported_from: {source_id: {{printf "%q" .ImportedFrom.SourceID}}, line: {{.ImportedFrom.Line}}, column: {{.ImportedFrom.Column}}}
|
||||
{{else}} imported_from: null
|
||||
{{end}}{{if .VersionEvidence}} version_evidence:
|
||||
path: {{printf "%q" .VersionEvidence.Path}}
|
||||
version:
|
||||
present: {{.VersionEvidence.Version.Present}}
|
||||
null: {{.VersionEvidence.Version.Null}}
|
||||
text: {{printf "%q" .VersionEvidence.Version.Text}}
|
||||
{{if .VersionEvidence.Location}} location: {source_id: {{printf "%q" .VersionEvidence.Location.SourceID}}, line: {{.VersionEvidence.Location.Line}}, column: {{.VersionEvidence.Location.Column}}}
|
||||
{{else}} location: null
|
||||
{{end}} redacted: {{.VersionEvidence.Redacted}}
|
||||
{{else}} version_evidence: null
|
||||
{{end}}{{if .EmptyImportSelections}} empty_import_selections:
|
||||
{{range .EmptyImportSelections}} - path: {{printf "%q" .Path}}
|
||||
location: {source_id: {{printf "%q" .Location.SourceID}}, line: {{.Location.Line}}, column: {{.Location.Column}}}
|
||||
selector: {{printf "%q" .Selector}}
|
||||
{{end}}{{else}} empty_import_selections: []
|
||||
{{end}}{{end}}{{else}}Sources: []
|
||||
{{end}}`, nil))
|
||||
|
||||
func locationReports(locations []configkit.Location) []locationDTO {
|
||||
report := make([]locationDTO, 0, len(locations))
|
||||
|
||||
@@ -74,12 +74,20 @@ func TestSourcesProjectNativeEvidenceInTextAndYAML(t *testing.T) {
|
||||
var report struct {
|
||||
Scope string `yaml:"scope"`
|
||||
Sources []struct {
|
||||
ID string `yaml:"id"`
|
||||
Destination string `yaml:"destination"`
|
||||
Placement string `yaml:"placement"`
|
||||
Layer string `yaml:"layer"`
|
||||
EmptyImportSelections []emptyImportSelectionDTO `yaml:"empty_import_selections"`
|
||||
DestinationIsFallback bool `yaml:"destination_is_fallback"`
|
||||
ID string `yaml:"id"`
|
||||
Destination string `yaml:"destination"`
|
||||
Placement string `yaml:"placement"`
|
||||
Layer string `yaml:"layer"`
|
||||
EmptyImportSelections []struct {
|
||||
Path string `yaml:"path"`
|
||||
Location struct {
|
||||
SourceID string `yaml:"source_id"`
|
||||
Line int `yaml:"line"`
|
||||
Column int `yaml:"column"`
|
||||
} `yaml:"location"`
|
||||
Selector string `yaml:"selector"`
|
||||
} `yaml:"empty_import_selections"`
|
||||
DestinationIsFallback bool `yaml:"destination_is_fallback"`
|
||||
VersionEvidence *struct {
|
||||
Path string `yaml:"path"`
|
||||
Version struct {
|
||||
@@ -108,11 +116,8 @@ func TestSourcesProjectNativeEvidenceInTextAndYAML(t *testing.T) {
|
||||
if root := report.Sources[0]; root.Destination != "" || root.Placement != "mapping" || root.DestinationIsFallback || root.VersionEvidence != nil || root.Layer != "main" {
|
||||
t.Errorf("root source projection = %#v", root)
|
||||
}
|
||||
wantSelections := []emptyImportSelectionDTO{
|
||||
{Path: "/imports/first", Location: locationDTO{SourceID: "root.yml", Line: 3, Column: 4}, Selector: "glob"},
|
||||
{Path: "/imports/second", Location: locationDTO{}, Selector: "path"},
|
||||
}
|
||||
if !reflect.DeepEqual(report.Sources[0].EmptyImportSelections, wantSelections) || report.Sources[1].EmptyImportSelections == nil || len(report.Sources[1].EmptyImportSelections) != 0 {
|
||||
selections := report.Sources[0].EmptyImportSelections
|
||||
if len(selections) != 2 || selections[0].Path != "/imports/first" || selections[0].Location.SourceID != "root.yml" || selections[0].Location.Line != 3 || selections[0].Location.Column != 4 || selections[0].Selector != "glob" || selections[1].Path != "/imports/second" || selections[1].Selector != "path" || report.Sources[1].EmptyImportSelections == nil || len(report.Sources[1].EmptyImportSelections) != 0 {
|
||||
t.Fatalf("import selections: %#v", report.Sources)
|
||||
}
|
||||
if strings.Contains(yamlOutput.String(), "destination_unresolved:") || strings.Contains(yamlOutput.String(), "version_check:") {
|
||||
|
||||
@@ -1,83 +1,156 @@
|
||||
package ckconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"slices"
|
||||
"text/template"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
"go.yaml.in/yaml/v4"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
type validationReport struct {
|
||||
Scopes []validationScope `json:"scopes"`
|
||||
}
|
||||
|
||||
type validationScope struct {
|
||||
Scope string `json:"scope"`
|
||||
Outcome string `json:"outcome"`
|
||||
Details *validationDetails `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
type validationDetails struct {
|
||||
State string `json:"state"`
|
||||
Findings []validationFinding `json:"findings"`
|
||||
Sources []validationSource `json:"sources"`
|
||||
}
|
||||
|
||||
type validationFinding struct {
|
||||
Code string `json:"code"`
|
||||
Severity string `json:"severity"`
|
||||
Path string `json:"path"`
|
||||
Message string `json:"message"`
|
||||
Primary *locationDTO `json:"primary"`
|
||||
Related []locationDTO `json:"related"`
|
||||
}
|
||||
|
||||
type validationSource struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
|
||||
var validationTextTemplate = template.Must(commandkit.ParseTextTemplate("validation", "{{range .Scopes}}{{.Scope}}: {{.Outcome}}\n{{end}}", nil))
|
||||
var validationDetailsTemplate = template.Must(commandkit.ParseTextTemplate("validation-details", `{{range .Scopes}}{{.Scope}}: {{.Outcome}} ({{.Details.State}})
|
||||
{{range .Details.Findings}} {{.Severity}} {{.Code}} {{printf "%q" .Path}}: {{.Message}}
|
||||
{{if .Primary}} {{.Primary.SourceID}}:{{.Primary.Line}}:{{.Primary.Column}}
|
||||
{{end}}{{range .Related}} {{.SourceID}}:{{.Line}}:{{.Column}}
|
||||
{{end}}{{end}}{{range .Details.Sources}} source {{printf "%q" .ID}}: {{.Label}} {{.Path}}
|
||||
{{end}}{{end}}`, nil))
|
||||
|
||||
func parseValidationSeverity(raw string) (configkit.Severity, error) {
|
||||
switch configkit.Severity(raw) {
|
||||
case configkit.SeverityError, configkit.SeverityWarning:
|
||||
return configkit.Severity(raw), nil
|
||||
default:
|
||||
return "", fmt.Errorf("unknown validation severity %q", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func runConfigValidation[I, S any](invocation commandkit.Invocation, plan *configOperationPlan[I, S], state S) commandkit.Outcome {
|
||||
reporter := invocation.Reporter()
|
||||
writtenRecord := false
|
||||
report := validationReport{Scopes: make([]validationScope, 0, len(plan.scopes))}
|
||||
outcome := commandkit.Success()
|
||||
for _, selected := range plan.scopes {
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return configFailure("Configuration validation was canceled.", commandkit.Explanation{}, err)
|
||||
outcome = configFailure("Configuration validation was canceled.", commandkit.Explanation{}, err)
|
||||
break
|
||||
}
|
||||
name := selected.scope.scope.Name
|
||||
if selected.scope.scope.Acquire == nil {
|
||||
message := fmt.Sprintf("Configuration scope %q has no acquisition callback.", selected.scope.scope.Name)
|
||||
return commandkit.Failure(message)
|
||||
}
|
||||
acquired, acquireErr := selected.scope.scope.Acquire(invocation.Context, Request{
|
||||
Operation: Validate,
|
||||
Selection: plan.selection,
|
||||
}, selected.input, state)
|
||||
if acquireErr != nil {
|
||||
return configAcquisitionFailure(reporter, "validate", selected.scope.scope.Name, acquired, acquireErr)
|
||||
entry := validationScope{Scope: name, Outcome: "failed"}
|
||||
if plan.details {
|
||||
entry.Details = projectValidationDetails(View{}, plan.severities, plan.codes)
|
||||
}
|
||||
report.Scopes = append(report.Scopes, entry)
|
||||
outcome = commandkit.Failure(fmt.Sprintf("Configuration scope %q has no acquisition callback.", name))
|
||||
break
|
||||
}
|
||||
acquired, err := selected.scope.scope.Acquire(invocation.Context, Request{Operation: Validate, Selection: selected.selection}, selected.input, state)
|
||||
queueConfigDiagnostics(reporter, acquired.Diagnostics)
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return configFailure("Configuration validation was canceled.", acquired.Explanation, err)
|
||||
if !plan.details && acquired.Value.Findings != nil {
|
||||
queueConfigDiagnostics(reporter, acquired.Value.Findings.Messages)
|
||||
}
|
||||
|
||||
err := reporter.RenderOutput(func(writer io.Writer) error {
|
||||
record, err := validationSuccessRecord(selected.scope.scope.Name, plan.format)
|
||||
if err != nil {
|
||||
return err
|
||||
entry := validationScope{Scope: name, Outcome: "valid"}
|
||||
if plan.details {
|
||||
entry.Details = projectValidationDetails(acquired.Value, plan.severities, plan.codes)
|
||||
}
|
||||
if canceled := invocation.Context.Err(); canceled != nil {
|
||||
entry.Outcome = "canceled"
|
||||
if err != nil && !errors.Is(err, canceled) {
|
||||
err = errors.Join(err, canceled)
|
||||
} else if err == nil {
|
||||
err = canceled
|
||||
}
|
||||
if plan.format == "yaml" && !writtenRecord {
|
||||
if _, err := io.WriteString(writer, "scopes:\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = writer.Write(record)
|
||||
return err
|
||||
})
|
||||
} else if err != nil {
|
||||
entry.Outcome = "failed"
|
||||
}
|
||||
report.Scopes = append(report.Scopes, entry)
|
||||
if err != nil {
|
||||
if ctxErr := invocation.Context.Err(); ctxErr != nil {
|
||||
return configFailure("Configuration validation was canceled.", acquired.Explanation, ctxErr)
|
||||
message := fmt.Sprintf("Unable to validate configuration scope %q.", name)
|
||||
if entry.Outcome == "canceled" {
|
||||
message = "Configuration validation was canceled."
|
||||
}
|
||||
return commandkit.Success()
|
||||
outcome = configFailure(message, acquired.Explanation, err)
|
||||
break
|
||||
}
|
||||
writtenRecord = true
|
||||
}
|
||||
return commandkit.Success()
|
||||
text := validationTextTemplate
|
||||
if plan.details {
|
||||
text = validationDetailsTemplate
|
||||
}
|
||||
_ = reporter.Report(commandkit.Report{Value: report, TextTemplate: text})
|
||||
return outcome
|
||||
}
|
||||
|
||||
func validationSuccessRecord(scope, format string) ([]byte, error) {
|
||||
if format == "text" {
|
||||
return []byte(scope + ": valid\n"), nil
|
||||
func projectValidationDetails(view View, severities []configkit.Severity, codes []string) *validationDetails {
|
||||
details := &validationDetails{State: "unavailable", Findings: []validationFinding{}, Sources: []validationSource{}}
|
||||
if view.Findings == nil {
|
||||
return details
|
||||
}
|
||||
encoded, err := yaml.Marshal(struct {
|
||||
Name string `yaml:"name"`
|
||||
Valid bool `yaml:"valid"`
|
||||
}{Name: scope, Valid: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if len(view.Findings.Records) == 0 {
|
||||
details.State = "empty"
|
||||
return details
|
||||
}
|
||||
lines := strings.Split(strings.TrimSuffix(string(encoded), "\n"), "\n")
|
||||
var record bytes.Buffer
|
||||
for index, line := range lines {
|
||||
if index == 0 {
|
||||
record.WriteString(" - ")
|
||||
} else {
|
||||
record.WriteString(" ")
|
||||
details.State = "filtered"
|
||||
references := make(map[string]bool)
|
||||
for _, record := range view.Findings.Records {
|
||||
if len(severities) > 0 && !slices.Contains(severities, record.Severity) {
|
||||
continue
|
||||
}
|
||||
record.WriteString(line)
|
||||
record.WriteByte('\n')
|
||||
if len(codes) > 0 && !slices.Contains(codes, string(record.Code)) {
|
||||
continue
|
||||
}
|
||||
finding := validationFinding{Code: string(record.Code), Severity: string(record.Severity), Path: record.Path.String(), Message: record.Message, Related: locationReports(record.Related)}
|
||||
if record.Primary != nil {
|
||||
finding.Primary = &locationDTO{SourceID: record.Primary.SourceID, Line: record.Primary.Line, Column: record.Primary.Column}
|
||||
references[record.Primary.SourceID] = true
|
||||
}
|
||||
for _, location := range record.Related {
|
||||
references[location.SourceID] = true
|
||||
}
|
||||
details.Findings = append(details.Findings, finding)
|
||||
}
|
||||
return record.Bytes(), nil
|
||||
if len(details.Findings) > 0 {
|
||||
details.State = "present"
|
||||
}
|
||||
if view.Sources != nil {
|
||||
for _, source := range view.Sources.Sources() {
|
||||
if references[source.ID] {
|
||||
details.Sources = append(details.Sources, validationSource{ID: source.ID, Label: source.Label, Path: source.Path})
|
||||
}
|
||||
}
|
||||
}
|
||||
return details
|
||||
}
|
||||
|
||||
@@ -7,11 +7,13 @@ Importing it does not install either command family.
|
||||
|
||||
## Module
|
||||
|
||||
The module path is `go.maximumdirect.net/ckprompt`. Version v0.2.0 uses
|
||||
`go.maximumdirect.net/commandkit v0.3.0`, `go.maximumdirect.net/ckconfig v0.2.0`,
|
||||
and PromptKit v0.16.0. See the
|
||||
[consumer guide](https://gitea.maximumdirect.net/eric/CommandKit/src/branch/main/docs/consumers/guide.md#promptkit-configuration-and-definitions)
|
||||
The module path is `go.maximumdirect.net/ckprompt`. This source uses Go 1.27.0,
|
||||
`go.maximumdirect.net/commandkit v0.3.0`, `go.maximumdirect.net/ckconfig v0.3.0`,
|
||||
`go.maximumdirect.net/configkit v1.1.0`, and `go.maximumdirect.net/promptkit v0.20.0`. See the
|
||||
[consumer guide](https://gitea.maximumdirect.net/eric/CommandKit/src/branch/main/docs/consumers/guide.md#promptkit-configuration-definitions-and-requirements)
|
||||
for callback, input, state, and acquisition contracts.
|
||||
The current source requires the aligned local workspace until new core and
|
||||
ckconfig releases supply its APIs.
|
||||
|
||||
## Example
|
||||
|
||||
@@ -19,11 +21,12 @@ Add `ckprompt.ConfigScope(loadEngine)` to the scopes passed to
|
||||
`ckconfig.Command` when the application wants PromptKit engine configuration
|
||||
and native comparison in the `config` family. Install
|
||||
`ckprompt.Command(ckprompt.FromEngine(loadEngine))` separately for catalogs,
|
||||
named inspections, and requirements discovery. `FromEngine` supplies eight
|
||||
PromptKit-backed callbacks: three inspections and five catalogs. Applications
|
||||
named inspections, and requirements discovery. `FromEngine` supplies nine
|
||||
PromptKit-backed callbacks: four inspections and five catalogs. Applications
|
||||
may narrow, wrap, or replace them before capture or provide custom callbacks
|
||||
with `ckprompt.Suite`. Add concrete request validation and smoke testing
|
||||
explicitly with `WithRequestValidation` and `WithSmokeTesting`. Inspection,
|
||||
with `ckprompt.Suite`. Add concrete request validation, prepared-request preview,
|
||||
and smoke testing explicitly with `WithRequestValidation`,
|
||||
`WithRequestPreparation`, and `WithSmokeTesting`. Inspection,
|
||||
requirements, and catalog operations do not execute prompts or contact model
|
||||
providers; application loaders and callbacks retain their own effects. Smoke
|
||||
testing invokes the selected native PromptKit operation; the
|
||||
|
||||
@@ -7,10 +7,10 @@ import (
|
||||
"io"
|
||||
"strconv"
|
||||
|
||||
configkit "gitea.maximumdirect.net/eric/ConfigKit"
|
||||
promptkit "gitea.maximumdirect.net/eric/promptkit"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
promptkit "go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
// PromptRequest selects one named prompt for inspection.
|
||||
@@ -19,6 +19,8 @@ type PromptRequest struct {
|
||||
Selection ckconfig.Selection
|
||||
// ID is the selected named prompt.
|
||||
ID string
|
||||
// Namespaces selects the native engine view; nil preserves the loader view.
|
||||
Namespaces *promptkit.Namespaces
|
||||
}
|
||||
|
||||
// ProfileRequest selects one named profile for inspection.
|
||||
@@ -27,6 +29,18 @@ type ProfileRequest struct {
|
||||
Selection ckconfig.Selection
|
||||
// ID is the selected named profile.
|
||||
ID string
|
||||
// Namespaces selects the native engine view; nil preserves the loader view.
|
||||
Namespaces *promptkit.Namespaces
|
||||
}
|
||||
|
||||
// BackendRequest selects one named backend for inspection.
|
||||
type BackendRequest struct {
|
||||
// Selection carries configuration and overlay values supplied to the command.
|
||||
Selection ckconfig.Selection
|
||||
// ID is the selected named backend.
|
||||
ID string
|
||||
// Namespaces selects the native engine view; nil preserves the loader view.
|
||||
Namespaces *promptkit.Namespaces
|
||||
}
|
||||
|
||||
// CatalogRequest selects the configuration and native namespace filter for a
|
||||
@@ -56,15 +70,17 @@ type NamespaceRequest struct {
|
||||
type RequirementsRequest struct {
|
||||
// Selection carries the configuration and overlay values supplied to the command.
|
||||
Selection ckconfig.Selection
|
||||
// Inspection forwards PromptKit's native prompt, version, profile, variable,
|
||||
// and session discovery context. Optional version, profile, and session
|
||||
// strings retain PromptKit's empty-value semantics.
|
||||
// Inspection forwards PromptKit's native prompt, profile, variable, and session
|
||||
// discovery context. Profile and session strings retain PromptKit's
|
||||
// empty-value semantics.
|
||||
Inspection promptkit.RequirementInspectionRequest
|
||||
// Namespaces selects the native engine view; nil preserves the loader view.
|
||||
Namespaces *promptkit.Namespaces
|
||||
}
|
||||
|
||||
// Suite describes application-owned input, shared state, and optional catalog,
|
||||
// named inspection, requirements discovery, concrete request validation, and
|
||||
// smoke testing capabilities. Its private issues retain adapter construction
|
||||
// named inspection, requirements discovery, request validation and preparation,
|
||||
// and smoke testing capabilities. Its private issues retain adapter construction
|
||||
// failures.
|
||||
// Factory results and callback effects remain caller-owned: Command does not
|
||||
// deep-copy arbitrary objects or repair aliases returned by factories.
|
||||
@@ -73,19 +89,19 @@ type RequirementsRequest struct {
|
||||
// Factories are not invoked during construction, installation, help, or version,
|
||||
// and need not run after failure.
|
||||
type Suite[I, S any] struct {
|
||||
// NewInput is called once when inspection, requirements, validation, smoke,
|
||||
// NewInput is called once when inspection, requirements, validation, preparation, smoke,
|
||||
// or catalog input preparation is reached, before applying selectors and
|
||||
// calling CheckInput.
|
||||
// If nil, input is the zero value of I, including nil for pointer types.
|
||||
NewInput func() I
|
||||
// NewState is called once when an inspection, validation, smoke, or catalog
|
||||
// NewState is called once when an inspection, validation, preparation, smoke, or catalog
|
||||
// callback is reached, after input checks pass. If nil, state is the zero
|
||||
// value of S, including nil for pointer types.
|
||||
NewState func() S
|
||||
// Selectors declares the original typed flags accepted by inspection,
|
||||
// requirements, validation, smoke, and catalog commands.
|
||||
// requirements, validation, preparation, smoke, and catalog commands.
|
||||
Selectors []commandkit.Flag[I]
|
||||
// CheckInput validates selected inspection, requirements, validation, smoke,
|
||||
// CheckInput validates selected inspection, requirements, validation, preparation, smoke,
|
||||
// or catalog input before state creation.
|
||||
CheckInput func(ckconfig.Selection, I) error
|
||||
// InspectPrompt inspects the selected prompt after input and state
|
||||
@@ -96,6 +112,8 @@ type Suite[I, S any] struct {
|
||||
// preparation. Its acquisition carries independent loader diagnostics and
|
||||
// terminal context alongside any native inspection result.
|
||||
InspectProfile func(context.Context, ProfileRequest, I, S) (commandkit.Acquired[*promptkit.ProfileInspection], error)
|
||||
// InspectBackend independently enables inspection of one named backend.
|
||||
InspectBackend func(context.Context, BackendRequest, I, S) (commandkit.Acquired[*promptkit.BackendInspection], error)
|
||||
// InspectRequirements inspects native PromptKit requirements after input and
|
||||
// state preparation. Its acquisition carries independent loader diagnostics
|
||||
// and terminal context alongside any native inspection result. It is
|
||||
@@ -109,6 +127,9 @@ type Suite[I, S any] struct {
|
||||
// context, and an empty value on success; PromptKit errors are returned
|
||||
// unchanged where supported.
|
||||
ValidateRequest func(context.Context, ValidationRequest, I, S) (commandkit.Acquired[struct{}], error)
|
||||
// PrepareRequest independently enables `promptkit show prepared`, returning
|
||||
// the native prepared request and any acquisition diagnostics.
|
||||
PrepareRequest func(context.Context, PreparationRequest, I, S) (commandkit.Acquired[*promptkit.PreparedRun], error)
|
||||
// SmokeTest runs one concrete native smoke-test operation after input and
|
||||
// state preparation. It is optional; nil omits only the smoke-test command.
|
||||
// The acquisition retains a native report, independent diagnostics, and
|
||||
@@ -137,7 +158,8 @@ type Suite[I, S any] struct {
|
||||
// omits only this catalog command.
|
||||
ListCollections func(context.Context, ckconfig.Selection, I, S) (commandkit.Acquired[[]promptkit.CollectionInfo], error)
|
||||
|
||||
issues []error
|
||||
namespaces *promptkit.Namespaces
|
||||
issues []error
|
||||
}
|
||||
|
||||
// WithRequestValidation attaches PromptKit-backed concrete request validation
|
||||
@@ -192,6 +214,12 @@ func WithRequestValidation[I, S any](
|
||||
return commandkit.Acquired[struct{}]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, fmt.Errorf("PromptKit request validation before native validation: %w", err)
|
||||
}
|
||||
|
||||
engine, err = namespacedEngine(engine, request.Namespaces)
|
||||
if err != nil {
|
||||
messages = messages.withOperationError(err)
|
||||
return commandkit.Acquired[struct{}]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
}
|
||||
|
||||
if err := engine.ValidateRequest(ctx, concreteRequest); err != nil {
|
||||
messages = messages.withOperationError(err)
|
||||
return commandkit.Acquired[struct{}]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
@@ -239,6 +267,7 @@ func ConfigScope[I, S any](load func(context.Context, ckconfig.Selection, I, S)
|
||||
Name: "promptkit",
|
||||
Summary: "PromptKit engine configuration.",
|
||||
Operations: []ckconfig.Operation{ckconfig.Validate, ckconfig.Show, ckconfig.Sources, ckconfig.Explain, ckconfig.Diff},
|
||||
Features: ckconfig.ScopeFeatures{PathDiscovery: true, PathShow: true},
|
||||
}
|
||||
if load == nil {
|
||||
return ckconfig.WithScopeError(scope, errors.New("PromptKit configuration loader is nil"))
|
||||
@@ -247,15 +276,25 @@ func ConfigScope[I, S any](load func(context.Context, ckconfig.Selection, I, S)
|
||||
scope.Acquire = func(ctx context.Context, request ckconfig.Request, input I, state S) (commandkit.Acquired[ckconfig.View], error) {
|
||||
_, inspection, messages, err := loadPromptKitEngine(ctx, request.Selection, input, state, "", load)
|
||||
if err != nil {
|
||||
return commandkit.Acquired[ckconfig.View]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
acquired := commandkit.Acquired[ckconfig.View]{Explanation: messages.explanation}
|
||||
var loadError *configkit.LoadError
|
||||
if errors.As(err, &loadError) && loadError != nil {
|
||||
acquired.Value.Sources = loadError
|
||||
acquired.Value.Findings = &ckconfig.Findings{Records: loadError.Diagnostics(), Messages: messages.diagnostics}
|
||||
} else {
|
||||
acquired.Diagnostics = messages.diagnostics
|
||||
}
|
||||
return acquired, err
|
||||
}
|
||||
metadata := inspection.Metadata()
|
||||
return commandkit.Acquired[ckconfig.View]{
|
||||
Value: ckconfig.View{
|
||||
Effective: inspection,
|
||||
Sources: inspection,
|
||||
Explanation: inspection,
|
||||
Metadata: &metadata,
|
||||
Findings: &ckconfig.Findings{Records: inspection.Diagnostics(), Messages: messages.diagnostics},
|
||||
},
|
||||
Diagnostics: messages.diagnostics,
|
||||
Explanation: messages.explanation,
|
||||
}, nil
|
||||
}
|
||||
@@ -300,9 +339,9 @@ func promptKitContextError(ctx context.Context) error {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
// FromEngine supplies eight PromptKit-backed callbacks: prompt, profile,
|
||||
// backend, namespace, and collection catalogs, plus named prompt and profile
|
||||
// inspection and requirements discovery.
|
||||
// FromEngine supplies nine PromptKit-backed callbacks: prompt, profile,
|
||||
// backend, namespace, and collection catalogs; named prompt, profile, and
|
||||
// backend inspection; and requirements discovery.
|
||||
// The requirements callback forwards RequirementsRequest.Inspection to
|
||||
// Engine.InspectRequirements. Concrete request validation is an independent
|
||||
// capability and can be composed explicitly with WithRequestValidation. Smoke
|
||||
@@ -371,6 +410,11 @@ func FromEngine[I, S any](load func(context.Context, ckconfig.Selection, I, S) (
|
||||
if err != nil {
|
||||
return commandkit.Acquired[*promptkit.PromptInspection]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
}
|
||||
engine, err = namespacedEngine(engine, request.Namespaces)
|
||||
if err != nil {
|
||||
messages = messages.withOperationError(err)
|
||||
return commandkit.Acquired[*promptkit.PromptInspection]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
}
|
||||
inspection, err := engine.InspectPrompt(ctx, request.ID)
|
||||
messages = messages.withOperationError(err)
|
||||
return commandkit.Acquired[*promptkit.PromptInspection]{Value: inspection, Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
@@ -380,15 +424,39 @@ func FromEngine[I, S any](load func(context.Context, ckconfig.Selection, I, S) (
|
||||
if err != nil {
|
||||
return commandkit.Acquired[*promptkit.ProfileInspection]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
}
|
||||
engine, err = namespacedEngine(engine, request.Namespaces)
|
||||
if err != nil {
|
||||
messages = messages.withOperationError(err)
|
||||
return commandkit.Acquired[*promptkit.ProfileInspection]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
}
|
||||
inspection, err := engine.InspectProfile(ctx, request.ID)
|
||||
messages = messages.withOperationError(err)
|
||||
return commandkit.Acquired[*promptkit.ProfileInspection]{Value: inspection, Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
},
|
||||
InspectBackend: func(ctx context.Context, request BackendRequest, input I, state S) (commandkit.Acquired[*promptkit.BackendInspection], error) {
|
||||
engine, _, messages, err := loadPromptKitEngine(ctx, request.Selection, input, state, "", load)
|
||||
if err != nil {
|
||||
return commandkit.Acquired[*promptkit.BackendInspection]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
}
|
||||
engine, err = namespacedEngine(engine, request.Namespaces)
|
||||
if err != nil {
|
||||
messages = messages.withOperationError(err)
|
||||
return commandkit.Acquired[*promptkit.BackendInspection]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
}
|
||||
inspection, err := engine.InspectBackend(ctx, request.ID)
|
||||
messages = messages.withOperationError(err)
|
||||
return commandkit.Acquired[*promptkit.BackendInspection]{Value: inspection, Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
},
|
||||
InspectRequirements: func(ctx context.Context, request RequirementsRequest, input I, state S) (commandkit.Acquired[*promptkit.RequirementInspection], error) {
|
||||
engine, _, messages, err := loadPromptKitEngine(ctx, request.Selection, input, state, "", load)
|
||||
if err != nil {
|
||||
return commandkit.Acquired[*promptkit.RequirementInspection]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
}
|
||||
engine, err = namespacedEngine(engine, request.Namespaces)
|
||||
if err != nil {
|
||||
messages = messages.withOperationError(err)
|
||||
return commandkit.Acquired[*promptkit.RequirementInspection]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
}
|
||||
inspection, err := engine.InspectRequirements(ctx, request.Inspection)
|
||||
messages = messages.withOperationError(err)
|
||||
return commandkit.Acquired[*promptkit.RequirementInspection]{Value: inspection, Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
|
||||
|
||||
@@ -11,15 +11,15 @@ import (
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
configkit "gitea.maximumdirect.net/eric/ConfigKit"
|
||||
promptkit "gitea.maximumdirect.net/eric/promptkit"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
promptkit "go.maximumdirect.net/promptkit"
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
const adapterPrompt = `prompts:
|
||||
briefing:
|
||||
version: "1"
|
||||
- id: briefing
|
||||
default_profile: default
|
||||
inputs:
|
||||
- name: topic
|
||||
@@ -36,8 +36,7 @@ const adapterPrompt = `prompts:
|
||||
output:
|
||||
format: text
|
||||
validation_mode: none
|
||||
empty:
|
||||
version: "1"
|
||||
- id: empty
|
||||
default_profile: default
|
||||
messages:
|
||||
- role: user
|
||||
@@ -46,10 +45,10 @@ const adapterPrompt = `prompts:
|
||||
format: text
|
||||
validation_mode: none
|
||||
backends:
|
||||
local:
|
||||
- id: local
|
||||
endpoint: "https://example.invalid/v1"
|
||||
profiles:
|
||||
default:
|
||||
- id: default
|
||||
backend: local
|
||||
model: example
|
||||
temperature: 0
|
||||
@@ -61,15 +60,14 @@ profiles:
|
||||
visible: true
|
||||
null_value: null
|
||||
sequence: [first, null, 3]
|
||||
requires-key:
|
||||
- id: requires-key
|
||||
backend: local
|
||||
model: example
|
||||
api_key_required: true
|
||||
`
|
||||
|
||||
const adapterRequirementsPrompt = `prompts:
|
||||
briefing:
|
||||
version: "1"
|
||||
- id: briefing
|
||||
default_profile: default
|
||||
session_id: '{{input "session-only"}} {{.session_variable}}'
|
||||
messages:
|
||||
@@ -79,10 +77,10 @@ const adapterRequirementsPrompt = `prompts:
|
||||
format: text
|
||||
validation_mode: none
|
||||
backends:
|
||||
local:
|
||||
- id: local
|
||||
endpoint: "https://example.invalid/v1"
|
||||
profiles:
|
||||
default:
|
||||
- id: default
|
||||
backend: local
|
||||
model: example
|
||||
`
|
||||
@@ -101,13 +99,22 @@ func adapterEngineFrom(t *testing.T, label, configuration string, options ...pro
|
||||
}
|
||||
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{
|
||||
Underlays: []configkit.Underlay{{Inputs: inputs}},
|
||||
}}, options...)
|
||||
}}, append([]promptkit.Option{promptkit.WithBundledOpenRouter(false)}, options...)...)
|
||||
if err != nil {
|
||||
t.Fatalf("construct PromptKit fixture: %v", err)
|
||||
}
|
||||
return engine
|
||||
}
|
||||
|
||||
func bundledEngine(t *testing.T) *promptkit.Engine {
|
||||
t.Helper()
|
||||
engine, err := promptkit.NewEngine(promptkit.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("construct bundled PromptKit fixture: %v", err)
|
||||
}
|
||||
return engine
|
||||
}
|
||||
|
||||
type recordingSmokeClient struct {
|
||||
request promptkit.GenerateRequest
|
||||
response *promptkit.GenerateResponse
|
||||
@@ -143,14 +150,14 @@ func TestWithSmokeTestingForwardsAuthoritativeNativeRequestAndRetainsReport(t *t
|
||||
suite := WithSmokeTesting(Suite[input, state]{},
|
||||
func(ctx context.Context, selection ckconfig.Selection, gotInput input, gotState state) (*promptkit.Engine, error) {
|
||||
loaderCalls++
|
||||
if ctx.Value(contextKey{}) != "smoke invocation" || selection != wantSelection || gotInput != wantInput || gotState != wantState {
|
||||
if ctx.Value(contextKey{}) != "smoke invocation" || !reflect.DeepEqual(selection, wantSelection) || gotInput != wantInput || gotState != wantState {
|
||||
t.Errorf("loader args = ctx=%v selection=%#v input=%#v state=%#v", ctx.Value(contextKey{}), selection, gotInput, gotState)
|
||||
}
|
||||
return engine, nil
|
||||
},
|
||||
func(ctx context.Context, request SmokeRequest, gotInput input, gotState state) (promptkit.SmokeTestRequest, error) {
|
||||
builderCalls++
|
||||
if ctx.Value(contextKey{}) != "smoke invocation" || request.Selection != wantSelection || request.Request.Kind != promptkit.SmokeTestAuthentication || gotInput != wantInput || gotState != wantState {
|
||||
if ctx.Value(contextKey{}) != "smoke invocation" || !reflect.DeepEqual(request.Selection, wantSelection) || request.Request.Kind != promptkit.SmokeTestAuthentication || gotInput != wantInput || gotState != wantState {
|
||||
t.Errorf("builder args = ctx=%v request=%#v input=%#v state=%#v", ctx.Value(contextKey{}), request, gotInput, gotState)
|
||||
}
|
||||
return built, nil
|
||||
@@ -281,8 +288,11 @@ func TestConfigScopeUsesNativeInspectionFacetsAndInvocationValues(t *testing.T)
|
||||
if err != nil || loaderCalls != 1 {
|
||||
t.Fatalf("scope acquisition = (%#v, %v), calls=%d", acquired, err, loaderCalls)
|
||||
}
|
||||
if acquired.Value.Metadata == nil || acquired.Value.Findings == nil || !scope.Features.PathDiscovery || !scope.Features.PathShow {
|
||||
t.Fatalf("missing native metadata or findings: %#v", acquired.Value)
|
||||
}
|
||||
var effective bytes.Buffer
|
||||
if err := acquired.Value.Effective.WriteEffective(&effective); err != nil || !strings.Contains(effective.String(), "briefing:") {
|
||||
if err := acquired.Value.Effective.WriteEffective(&effective); err != nil || !strings.Contains(effective.String(), "id: briefing") {
|
||||
t.Fatalf("native effective report = %q, %v", effective.String(), err)
|
||||
}
|
||||
if sources := acquired.Value.Sources.Sources(); len(sources) == 0 || sources[0].ID == "" {
|
||||
@@ -293,6 +303,59 @@ func TestConfigScopeUsesNativeInspectionFacetsAndInvocationValues(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBundledRecordsAndSourcesReachCommandOutput(t *testing.T) {
|
||||
engine := bundledEngine(t)
|
||||
ctx := context.Background()
|
||||
profiles, err := engine.ListProfiles(ctx)
|
||||
if err != nil || len(profiles) == 0 {
|
||||
t.Fatalf("native bundled profiles = %v, %v", profiles, err)
|
||||
}
|
||||
inspection, err := engine.InspectConfiguration()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sources := inspection.Sources()
|
||||
if len(sources) == 0 || sources[0].ID == "" {
|
||||
t.Fatalf("native bundled sources = %#v", sources)
|
||||
}
|
||||
load := func(context.Context, ckconfig.Selection, struct{}, struct{}) (*promptkit.Engine, error) {
|
||||
return engine, nil
|
||||
}
|
||||
app, err := commandkit.New(commandkit.Identity{Name: "bundle"}, Command(FromEngine(load)), ckconfig.Command(ckconfig.Suite[struct{}, struct{}]{Scopes: []ckconfig.Scope[struct{}, struct{}]{ConfigScope(load)}}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
result := app.Execute(ctx, []string{"promptkit", "list", "profiles", "--format", "yaml"}, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
var gotProfiles []string
|
||||
if result.Kind != commandkit.OutcomeSuccess {
|
||||
t.Fatalf("profile catalog = %#v: %s", result, out.String())
|
||||
}
|
||||
if err := yaml.Unmarshal(out.Bytes(), &gotProfiles); err != nil || !slices.Contains(gotProfiles, profiles[0]) {
|
||||
t.Fatalf("bundled profile %q missing from catalog %q: %v", profiles[0], out.String(), err)
|
||||
}
|
||||
out.Reset()
|
||||
result = app.Execute(ctx, []string{"config", "sources", "--scope", "promptkit", "--format", "yaml"}, commandkit.Streams{Out: &out, Err: io.Discard})
|
||||
var report struct {
|
||||
Sources []struct {
|
||||
ID string `yaml:"id"`
|
||||
Label string `yaml:"label"`
|
||||
} `yaml:"sources"`
|
||||
}
|
||||
if result.Kind != commandkit.OutcomeSuccess {
|
||||
t.Fatalf("source report = %#v: %s", result, out.String())
|
||||
}
|
||||
if err := yaml.Unmarshal(out.Bytes(), &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, source := range report.Sources {
|
||||
if source.ID == sources[0].ID && source.Label == sources[0].Label {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("bundled source %#v missing from report %q", sources[0], out.String())
|
||||
}
|
||||
|
||||
func TestConfigScopeRetainsNilLoaderIssueAfterCapabilitiesAreCleared(t *testing.T) {
|
||||
scope := ConfigScope[int, int](nil)
|
||||
if scope.Acquire != nil {
|
||||
@@ -368,7 +431,7 @@ func TestConfigScopeCompareUsesNativeDiffAndLoadsBothEqualSelections(t *testing.
|
||||
if !reflect.DeepEqual(got.Value, want) {
|
||||
t.Fatalf("adapter differences = %#v, want native PromptKit result %#v", got.Value, want)
|
||||
}
|
||||
if len(calls) != 2 || calls[0].selection != selection || calls[1].selection != selection || calls[0].input.label != "before" || calls[1].input.label != "after" || calls[0].state != state || calls[1].state != state {
|
||||
if len(calls) != 2 || !reflect.DeepEqual(calls[0].selection, selection) || !reflect.DeepEqual(calls[1].selection, selection) || calls[0].input.label != "before" || calls[1].input.label != "after" || calls[0].state != state || calls[1].state != state {
|
||||
t.Fatalf("loader calls = %#v", calls)
|
||||
}
|
||||
}
|
||||
@@ -467,7 +530,7 @@ func TestFromEnginePassesRequestsAndRetainsNilLoaderIssue(t *testing.T) {
|
||||
})
|
||||
selection := ckconfig.Selection{Overlay: commandkit.Supplied[string]{Value: "overlay.yml", Set: true}}
|
||||
prompt, err := suite.InspectPrompt(wantContext, PromptRequest{Selection: selection, ID: "briefing"}, wantInput, wantState)
|
||||
if err != nil || prompt.Value == nil || prompt.Value.PromptID != "briefing" || prompt.Value.PromptVersion == nil || *prompt.Value.PromptVersion != "1" || loaderCalls != 1 {
|
||||
if err != nil || prompt.Value == nil || prompt.Value.PromptID != "briefing" || loaderCalls != 1 {
|
||||
t.Fatalf("prompt inspection = (%#v, %v), calls=%d", prompt, err, loaderCalls)
|
||||
}
|
||||
secondPrompt, err := suite.InspectPrompt(wantContext, PromptRequest{Selection: selection, ID: "briefing"}, wantInput, wantState)
|
||||
@@ -529,7 +592,7 @@ func TestFromEngineInspectsRequirementsWithNativeRequest(t *testing.T) {
|
||||
if err != nil || acquired.Value == nil || !reflect.DeepEqual(acquired.Value, want) || loaderCalls != 1 {
|
||||
t.Fatalf("requirements inspection = (%#v, %v), calls=%d; want native result %#v", acquired, err, loaderCalls, want)
|
||||
}
|
||||
if acquired.Value.PromptID != "briefing" || acquired.Value.PromptVersion == nil || *acquired.Value.PromptVersion != "1" || acquired.Value.ProfileID != "default" {
|
||||
if acquired.Value.PromptID != "briefing" || acquired.Value.ProfileID != "default" {
|
||||
t.Fatalf("requirements selection = %#v", acquired.Value)
|
||||
}
|
||||
}
|
||||
@@ -596,7 +659,7 @@ func TestFromEngineListsNativeCatalogsWithInvocationValues(t *testing.T) {
|
||||
loaderCalls := 0
|
||||
suite := FromEngine(func(ctx context.Context, selection ckconfig.Selection, gotInput input, gotState state) (*promptkit.Engine, error) {
|
||||
loaderCalls++
|
||||
if ctx.Value(contextKey{}) != "catalog invocation" || selection != wantSelection || gotInput != wantInput || gotState != wantState {
|
||||
if ctx.Value(contextKey{}) != "catalog invocation" || !reflect.DeepEqual(selection, wantSelection) || gotInput != wantInput || gotState != wantState {
|
||||
t.Errorf("loader args = ctx=%v selection=%#v input=%#v state=%#v", ctx.Value(contextKey{}), selection, gotInput, gotState)
|
||||
}
|
||||
return engine, nil
|
||||
@@ -871,3 +934,25 @@ type failingDiagnosticWriter struct{ err error }
|
||||
func (writer failingDiagnosticWriter) Write([]byte) (int, error) { return 0, writer.err }
|
||||
|
||||
var _ io.Writer = failingDiagnosticWriter{}
|
||||
|
||||
func TestConfigScopeRetainsFailedLoadSnapshot(t *testing.T) {
|
||||
_, loadErr := configkit.Load[map[string]any](configkit.Bytes("broken", []byte("broken: [")))
|
||||
if loadErr == nil {
|
||||
t.Fatal("fixture unexpectedly loaded")
|
||||
}
|
||||
var snapshot *configkit.LoadError
|
||||
if !errors.As(loadErr, &snapshot) {
|
||||
t.Fatalf("unexpected load error: %v", loadErr)
|
||||
}
|
||||
wrapped := errors.Join(errors.New("loader context"), loadErr)
|
||||
scope := ConfigScope(func(context.Context, ckconfig.Selection, struct{}, struct{}) (*promptkit.Engine, error) {
|
||||
return nil, wrapped
|
||||
})
|
||||
got, err := scope.Acquire(context.Background(), ckconfig.Request{}, struct{}{}, struct{}{})
|
||||
if !errors.Is(err, loadErr) || got.Value.Sources == nil || got.Value.Findings == nil || got.Value.Effective != nil || got.Value.Metadata != nil || got.Value.Explanation != nil || len(got.Diagnostics) != 0 {
|
||||
t.Fatalf("failed acquisition = %#v, %v", got, err)
|
||||
}
|
||||
if !reflect.DeepEqual(got.Value.Sources.Sources(), snapshot.Sources()) || !reflect.DeepEqual(got.Value.Findings.Records, snapshot.Diagnostics()) {
|
||||
t.Fatalf("failed snapshot = %#v", got.Value)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,26 +1,22 @@
|
||||
package ckprompt
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
promptkit "gitea.maximumdirect.net/eric/promptkit"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
"go.yaml.in/yaml/v4"
|
||||
promptkit "go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
type definitionInput[I any] struct {
|
||||
selection ckconfig.Selection
|
||||
id string
|
||||
format string
|
||||
captured commandkit.FlagValues[I]
|
||||
selected I
|
||||
namespaces namespaceInput
|
||||
selection ckconfig.Selection
|
||||
id string
|
||||
captured commandkit.FlagValues[I]
|
||||
selected I
|
||||
}
|
||||
|
||||
type catalogInput[I any] struct {
|
||||
@@ -29,15 +25,16 @@ type catalogInput[I any] struct {
|
||||
allNamespaces commandkit.Supplied[bool]
|
||||
kinds []promptkit.ResourceKind
|
||||
filter promptkit.NamespaceFilter
|
||||
format string
|
||||
captured commandkit.FlagValues[I]
|
||||
selected I
|
||||
}
|
||||
|
||||
type requirementsInput[I any] struct {
|
||||
namespaces namespaceInput
|
||||
selection ckconfig.Selection
|
||||
inspection promptkit.RequirementInspectionRequest
|
||||
format string
|
||||
resources ResourceInput
|
||||
inputs PromptInputs
|
||||
captured commandkit.FlagValues[I]
|
||||
selected I
|
||||
}
|
||||
@@ -48,12 +45,12 @@ type variableAssignment struct {
|
||||
}
|
||||
|
||||
type inputAssignment struct {
|
||||
name string
|
||||
path string
|
||||
name string
|
||||
value string
|
||||
}
|
||||
|
||||
// Command captures the optional PromptKit catalogs, named inspection,
|
||||
// requirements discovery, concrete request validation, and smoke-test
|
||||
// requirements discovery, concrete request validation and preparation, and smoke-test
|
||||
// callbacks and adds only supplied operations. Discovery and validation share the
|
||||
// `requirements` group and remain independently optional. An absent suite
|
||||
// claims no namespace; attached construction issues remain reportable. It adds
|
||||
@@ -63,11 +60,14 @@ type inputAssignment struct {
|
||||
// callback-referenced objects and effects remain caller-owned. Suite documents
|
||||
// invocation input and state initialization, zero values, and caller ownership
|
||||
// of returned objects.
|
||||
// Catalog commands accept config/overlay selection and suite selectors, and
|
||||
// render YAML with `yaml` as the only format and default. Named-show formats are
|
||||
// unchanged.
|
||||
// Named resource inspections return native reports through shared formatting.
|
||||
// Catalog commands accept config/overlay selection and suite selectors.
|
||||
func Command[I, S any](suite Suite[I, S]) commandkit.Command {
|
||||
if suite.InspectPrompt == nil && suite.InspectProfile == nil && suite.InspectRequirements == nil && suite.ValidateRequest == nil && suite.SmokeTest == nil && suite.ListPrompts == nil && suite.ListProfiles == nil && suite.ListBackends == nil && suite.ListNamespaces == nil && suite.ListCollections == nil {
|
||||
return buildCommand(suite, nil)
|
||||
}
|
||||
|
||||
func buildCommand[I, S any](suite Suite[I, S], aliases *[]commandkit.Declaration) commandkit.Command {
|
||||
if suite.InspectPrompt == nil && suite.InspectProfile == nil && suite.InspectBackend == nil && suite.InspectRequirements == nil && suite.ValidateRequest == nil && suite.PrepareRequest == nil && suite.SmokeTest == nil && suite.ListPrompts == nil && suite.ListProfiles == nil && suite.ListBackends == nil && suite.ListNamespaces == nil && suite.ListCollections == nil {
|
||||
command := commandkit.NoCommand()
|
||||
for _, issue := range suite.issues {
|
||||
command = commandkit.WithError(command, issue)
|
||||
@@ -79,10 +79,16 @@ func Command[I, S any](suite Suite[I, S]) commandkit.Command {
|
||||
rootCommands := make([]commandkit.Command, 0, 3)
|
||||
showCommands := make([]commandkit.Command, 0, 2)
|
||||
if suite.InspectPrompt != nil {
|
||||
showCommands = append(showCommands, newDefinitionCommand(suite, "prompt", true))
|
||||
showCommands = append(showCommands, newDefinitionCommand(suite, "prompt", aliases))
|
||||
}
|
||||
if suite.InspectProfile != nil {
|
||||
showCommands = append(showCommands, newDefinitionCommand(suite, "profile", false))
|
||||
showCommands = append(showCommands, newDefinitionCommand(suite, "profile", aliases))
|
||||
}
|
||||
if suite.InspectBackend != nil {
|
||||
showCommands = append(showCommands, newDefinitionCommand(suite, "backend", aliases))
|
||||
}
|
||||
if suite.PrepareRequest != nil {
|
||||
showCommands = append(showCommands, newPreparationCommand(suite, aliases))
|
||||
}
|
||||
if len(showCommands) != 0 {
|
||||
rootCommands = append(rootCommands, commandkit.Group("show", "Show a named PromptKit definition.", showCommands...))
|
||||
@@ -108,16 +114,16 @@ func Command[I, S any](suite Suite[I, S]) commandkit.Command {
|
||||
}
|
||||
requirementsCommands := make([]commandkit.Command, 0, 2)
|
||||
if suite.InspectRequirements != nil {
|
||||
requirementsCommands = append(requirementsCommands, newRequirementsCommand(suite))
|
||||
requirementsCommands = append(requirementsCommands, newRequirementsCommand(suite, aliases))
|
||||
}
|
||||
if suite.ValidateRequest != nil {
|
||||
requirementsCommands = append(requirementsCommands, newValidationCommand(suite))
|
||||
requirementsCommands = append(requirementsCommands, newValidationCommand(suite, aliases))
|
||||
}
|
||||
if len(requirementsCommands) != 0 {
|
||||
rootCommands = append(rootCommands, commandkit.Group("requirements", "Inspect and validate prompt requirements.", requirementsCommands...))
|
||||
}
|
||||
if suite.SmokeTest != nil {
|
||||
rootCommands = append(rootCommands, newSmokeTestCommand(suite))
|
||||
rootCommands = append(rootCommands, newSmokeTestCommand(suite, aliases))
|
||||
}
|
||||
command := commandkit.RootGroup("promptkit", "Inspect, list, validate requests, and run PromptKit smoke tests.", rootCommands...)
|
||||
for _, issue := range suite.issues {
|
||||
@@ -138,8 +144,6 @@ func newCatalogListCommand[I, S any](suite Suite[I, S], name string) commandkit.
|
||||
func(input **catalogInput[I], value commandkit.Supplied[string]) { (*input).selection.Config = value }),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "overlay", Usage: "Configuration overlay path.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseDefinitionString,
|
||||
func(input **catalogInput[I], value commandkit.Supplied[string]) { (*input).selection.Overlay = value }),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "format", Usage: "Catalog format: yaml.", Completion: completionChoices("yaml")}, stringDefault("yaml"), parseDefinitionString,
|
||||
func(input **catalogInput[I], value commandkit.Supplied[string]) { (*input).format = value.Value }),
|
||||
)
|
||||
if name == "prompts" || name == "profiles" || name == "backends" {
|
||||
flags = append(flags,
|
||||
@@ -169,9 +173,6 @@ func newCatalogListCommand[I, S any](suite Suite[I, S], name string) commandkit.
|
||||
if input == nil {
|
||||
return errors.New("PromptKit catalog input must not be nil")
|
||||
}
|
||||
if err := checkCatalogFormat(input.format); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := prepareCatalogFilter(input, name); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -185,21 +186,21 @@ func newCatalogListCommand[I, S any](suite Suite[I, S], name string) commandkit.
|
||||
Run: func(invocation commandkit.Invocation, input *catalogInput[I]) commandkit.Outcome {
|
||||
switch name {
|
||||
case "prompts":
|
||||
return runCatalogList(invocation, suite, input, name, suite.ListPrompts, encodePromptCatalog)
|
||||
return runCatalogList(invocation, suite, input, name, suite.ListPrompts, promptCatalogReport)
|
||||
case "profiles":
|
||||
return runCatalogList(invocation, suite, input, name, suite.ListProfiles, encodeProfileCatalog)
|
||||
return runCatalogList(invocation, suite, input, name, suite.ListProfiles, stringCatalogReport)
|
||||
case "backends":
|
||||
return runCatalogList(invocation, suite, input, name, suite.ListBackends, encodeProfileCatalog)
|
||||
return runCatalogList(invocation, suite, input, name, suite.ListBackends, stringCatalogReport)
|
||||
case "namespaces":
|
||||
list := func(ctx context.Context, request CatalogRequest, value I, state S) (commandkit.Acquired[[]string], error) {
|
||||
return suite.ListNamespaces(ctx, NamespaceRequest{Selection: request.Selection, Kinds: input.kinds}, value, state)
|
||||
}
|
||||
return runCatalogList(invocation, suite, input, name, list, encodeProfileCatalog)
|
||||
return runCatalogList(invocation, suite, input, name, list, stringCatalogReport)
|
||||
case "collections":
|
||||
list := func(ctx context.Context, request CatalogRequest, value I, state S) (commandkit.Acquired[[]promptkit.CollectionInfo], error) {
|
||||
return suite.ListCollections(ctx, request.Selection, value, state)
|
||||
}
|
||||
return runCatalogList(invocation, suite, input, name, list, encodeCollectionCatalog)
|
||||
return runCatalogList(invocation, suite, input, name, list, collectionCatalogReport)
|
||||
default:
|
||||
return definitionFailure("Unable to list the selected PromptKit catalog.", commandkit.Explanation{}, fmt.Errorf("unknown PromptKit catalog %q", name))
|
||||
}
|
||||
@@ -230,25 +231,11 @@ func prepareCatalogFilter[I any](input *catalogInput[I], name string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkCatalogFormat(format string) error {
|
||||
if format != "yaml" {
|
||||
return fmt.Errorf("unsupported catalog format %q", format)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkRequirementsFormat(format string) error {
|
||||
if format != "yaml" {
|
||||
return fmt.Errorf("unsupported requirements format %q; expected yaml", format)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func prepareCatalogInput[I, S any](suite Suite[I, S], input *catalogInput[I]) (I, error) {
|
||||
return prepareSuiteInput(suite, input.selection, input.captured)
|
||||
}
|
||||
|
||||
func newDefinitionCommand[I, S any](suite Suite[I, S], name string, prompt bool) commandkit.Command {
|
||||
func newDefinitionCommand[I, S any](suite Suite[I, S], name string, aliases *[]commandkit.Declaration) commandkit.Command {
|
||||
flags := commandkit.CaptureFlags(suite.Selectors, func(input **definitionInput[I]) *commandkit.FlagValues[I] {
|
||||
if input == nil || *input == nil {
|
||||
return nil
|
||||
@@ -262,9 +249,11 @@ func newDefinitionCommand[I, S any](suite Suite[I, S], name string, prompt bool)
|
||||
func(input **definitionInput[I], value commandkit.Supplied[string]) {
|
||||
(*input).selection.Overlay = value
|
||||
}),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "format", Usage: "Report format: text or yaml.", Completion: completionChoices("text", "yaml")}, stringDefault("text"), parseDefinitionString,
|
||||
func(input **definitionInput[I], value commandkit.Supplied[string]) { (*input).format = value.Value }),
|
||||
)
|
||||
if suite.namespaces != nil {
|
||||
flags = appendRequestBindings(flags, "promptkit show "+name, aliases, namespaceFlags(func(input **definitionInput[I]) *namespaceInput { return &(*input).namespaces }, name)...)
|
||||
}
|
||||
|
||||
spec := commandkit.CommandSpec[*definitionInput[I]]{
|
||||
Name: name,
|
||||
Summary: "Inspect a named PromptKit " + name + ".",
|
||||
@@ -273,13 +262,10 @@ func newDefinitionCommand[I, S any](suite Suite[I, S], name string, prompt bool)
|
||||
},
|
||||
Flags: flags,
|
||||
Arguments: []commandkit.Argument[*definitionInput[I]]{
|
||||
commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "id", Usage: "Prompt or profile ID."}, true, parseDefinitionString,
|
||||
commandkit.ValueArgument(commandkit.ArgumentMeta{Name: strings.ToUpper(name) + "_ID", Usage: "Resource ID."}, true, parseDefinitionString,
|
||||
func(input **definitionInput[I], value commandkit.Supplied[string]) { (*input).id = value.Value }),
|
||||
},
|
||||
CheckInput: func(input *definitionInput[I]) error {
|
||||
if err := checkDefinitionFormat(input.format); err != nil {
|
||||
return err
|
||||
}
|
||||
selected, err := prepareDefinitionInput(suite, input)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -288,13 +274,13 @@ func newDefinitionCommand[I, S any](suite Suite[I, S], name string, prompt bool)
|
||||
return nil
|
||||
},
|
||||
Run: func(invocation commandkit.Invocation, input *definitionInput[I]) commandkit.Outcome {
|
||||
return runDefinitionInspection(invocation, suite, input, prompt)
|
||||
return runDefinitionInspection(invocation, suite, input, name)
|
||||
},
|
||||
}
|
||||
return commandkit.NewCommand(spec)
|
||||
}
|
||||
|
||||
func newRequirementsCommand[I, S any](suite Suite[I, S]) commandkit.Command {
|
||||
func newRequirementsCommand[I, S any](suite Suite[I, S], aliases *[]commandkit.Declaration) commandkit.Command {
|
||||
flags := commandkit.CaptureFlags(suite.Selectors, func(input **requirementsInput[I]) *commandkit.FlagValues[I] {
|
||||
if input == nil || *input == nil {
|
||||
return nil
|
||||
@@ -310,29 +296,20 @@ func newRequirementsCommand[I, S any](suite Suite[I, S]) commandkit.Command {
|
||||
func(input **requirementsInput[I], value commandkit.Supplied[string]) {
|
||||
(*input).selection.Overlay = value
|
||||
}),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "profile", Usage: "Profile identity for discovery."}, stringDefault(""), parseDefinitionString,
|
||||
func(input **requirementsInput[I], value commandkit.Supplied[string]) {
|
||||
(*input).inspection.ProfileID = value.Value
|
||||
}),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "session-id", Usage: "Session context for discovery."}, stringDefault(""), parseDefinitionString,
|
||||
func(input **requirementsInput[I], value commandkit.Supplied[string]) {
|
||||
(*input).inspection.SessionID = value.Value
|
||||
}),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "format", Usage: "Report format: yaml.", Completion: completionChoices("yaml")}, stringDefault("yaml"), parseDefinitionString,
|
||||
func(input **requirementsInput[I], value commandkit.Supplied[string]) { (*input).format = value.Value }),
|
||||
commandkit.RepeatFlag(commandkit.FlagMeta{Name: "var", Usage: "Caller variable assignment KEY=VALUE."}, []variableAssignment(nil), parseVariableAssignment,
|
||||
func(input **requirementsInput[I], value commandkit.Supplied[[]variableAssignment]) {
|
||||
variables := make(map[string]string, len(value.Value))
|
||||
for _, assignment := range value.Value {
|
||||
variables[assignment.key] = assignment.value
|
||||
}
|
||||
(*input).inspection.Vars = variables
|
||||
}),
|
||||
)
|
||||
|
||||
resources := NewResourceFlags(func(input **requirementsInput[I]) *ResourceInput { return &(*input).resources })
|
||||
inputs := NewPromptInputFlags(func(input **requirementsInput[I]) *PromptInputs { return &(*input).inputs })
|
||||
flags = appendRequestBindings(flags, "promptkit requirements show", aliases, requestBinding[*requirementsInput[I]]{resources.Profile, requestFlags.Profile}, requestBinding[*requirementsInput[I]]{resources.SessionID, requestFlags.SessionID}, requestBinding[*requirementsInput[I]]{inputs.Variable, requestFlags.Var})
|
||||
|
||||
if suite.namespaces != nil {
|
||||
flags = appendRequestBindings(flags, "promptkit requirements show", aliases, namespaceFlags(func(input **requirementsInput[I]) *namespaceInput { return &(*input).namespaces }, "prompt", "profile")...)
|
||||
}
|
||||
|
||||
spec := commandkit.CommandSpec[*requirementsInput[I]]{
|
||||
Name: "show",
|
||||
Summary: "Inspect requirements for a named PromptKit prompt.",
|
||||
Name: "show",
|
||||
Summary: "Inspect requirements for a named PromptKit prompt.",
|
||||
Description: "Profile selection establishes the reported profile identity, not a different set of requirements. A profile namespace qualifies an explicitly supplied short profile ID, not the prompt’s stored default reference.",
|
||||
NewInput: func() *requirementsInput[I] {
|
||||
return &requirementsInput[I]{}
|
||||
},
|
||||
@@ -344,9 +321,9 @@ func newRequirementsCommand[I, S any](suite Suite[I, S]) commandkit.Command {
|
||||
}),
|
||||
},
|
||||
CheckInput: func(input *requirementsInput[I]) error {
|
||||
if err := checkRequirementsFormat(input.format); err != nil {
|
||||
return err
|
||||
}
|
||||
input.inspection.ProfileID = input.resources.Profile.Value
|
||||
input.inspection.SessionID = input.resources.SessionID.Value
|
||||
input.inspection.Vars = input.inputs.Vars
|
||||
selected, err := prepareSuiteInput(suite, input.selection, input.captured)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -387,7 +364,7 @@ func runCatalogList[T any, I, S any](
|
||||
input *catalogInput[I],
|
||||
catalog string,
|
||||
list func(context.Context, CatalogRequest, I, S) (commandkit.Acquired[T], error),
|
||||
encode func(T) ([]byte, error),
|
||||
project func(T) any,
|
||||
) commandkit.Outcome {
|
||||
if invocation.Context != nil {
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
@@ -414,167 +391,102 @@ func runCatalogList[T any, I, S any](
|
||||
return definitionFailure("PromptKit catalog listing was canceled.", acquired.Explanation, err)
|
||||
}
|
||||
}
|
||||
return renderPreparedPromptReport(invocation, acquired.Explanation, func() ([]byte, error) {
|
||||
return encode(acquired.Value)
|
||||
})
|
||||
_ = invocation.Reporter().Report(commandkit.Report{Value: project(acquired.Value)})
|
||||
return commandkit.Success()
|
||||
}
|
||||
|
||||
func runDefinitionInspection[I, S any](invocation commandkit.Invocation, suite Suite[I, S], input *definitionInput[I], prompt bool) commandkit.Outcome {
|
||||
if invocation.Context != nil {
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return definitionFailure("PromptKit inspection was canceled.", commandkit.Explanation{}, err)
|
||||
}
|
||||
func runDefinitionInspection[I, S any](invocation commandkit.Invocation, suite Suite[I, S], input *definitionInput[I], kind string) commandkit.Outcome {
|
||||
if err := promptKitContextError(invocation.Context); err != nil {
|
||||
return definitionFailure("PromptKit inspection was canceled.", commandkit.Explanation{}, err)
|
||||
}
|
||||
var state S
|
||||
if suite.NewState != nil {
|
||||
state = suite.NewState()
|
||||
}
|
||||
if invocation.Context != nil {
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return definitionFailure("PromptKit inspection was canceled.", commandkit.Explanation{}, err)
|
||||
}
|
||||
if err := promptKitContextError(invocation.Context); err != nil {
|
||||
return definitionFailure("PromptKit inspection was canceled.", commandkit.Explanation{}, err)
|
||||
}
|
||||
|
||||
if prompt {
|
||||
request := PromptRequest{Selection: input.selection, ID: input.id}
|
||||
acquired, err := suite.InspectPrompt(invocation.Context, request, input.selected, state)
|
||||
queuePromptDiagnostics(invocation.Reporter(), acquired.Diagnostics)
|
||||
if err != nil {
|
||||
return definitionFailure(fmt.Sprintf("Unable to inspect PromptKit prompt %q.", input.id), acquired.Explanation, err)
|
||||
var value any
|
||||
var diagnostics []commandkit.Diagnostic
|
||||
var explanation commandkit.Explanation
|
||||
var err error
|
||||
switch kind {
|
||||
case "prompt":
|
||||
var result commandkit.Acquired[*promptkit.PromptInspection]
|
||||
result, err = suite.InspectPrompt(invocation.Context, PromptRequest{Selection: input.selection, ID: input.id, Namespaces: selectedNamespaces(suite.namespaces, input.namespaces)}, input.selected, state)
|
||||
if result.Value != nil {
|
||||
value = result.Value
|
||||
}
|
||||
if acquired.Value == nil {
|
||||
return definitionFailure("PromptKit prompt inspection returned no result.", acquired.Explanation, nil)
|
||||
diagnostics, explanation = result.Diagnostics, result.Explanation
|
||||
case "profile":
|
||||
var result commandkit.Acquired[*promptkit.ProfileInspection]
|
||||
result, err = suite.InspectProfile(invocation.Context, ProfileRequest{Selection: input.selection, ID: input.id, Namespaces: selectedNamespaces(suite.namespaces, input.namespaces)}, input.selected, state)
|
||||
if result.Value != nil {
|
||||
value = result.Value
|
||||
}
|
||||
if invocation.Context != nil {
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return definitionFailure(fmt.Sprintf("Inspection of PromptKit prompt %q was canceled.", input.id), acquired.Explanation, err)
|
||||
}
|
||||
diagnostics, explanation = result.Diagnostics, result.Explanation
|
||||
case "backend":
|
||||
var result commandkit.Acquired[*promptkit.BackendInspection]
|
||||
result, err = suite.InspectBackend(invocation.Context, BackendRequest{Selection: input.selection, ID: input.id, Namespaces: selectedNamespaces(suite.namespaces, input.namespaces)}, input.selected, state)
|
||||
if result.Value != nil {
|
||||
value = result.Value
|
||||
}
|
||||
return renderPromptReport(invocation, acquired.Value, input.format, acquired.Explanation)
|
||||
diagnostics, explanation = result.Diagnostics, result.Explanation
|
||||
}
|
||||
|
||||
request := ProfileRequest{Selection: input.selection, ID: input.id}
|
||||
acquired, err := suite.InspectProfile(invocation.Context, request, input.selected, state)
|
||||
queuePromptDiagnostics(invocation.Reporter(), acquired.Diagnostics)
|
||||
queuePromptDiagnostics(invocation.Reporter(), diagnostics)
|
||||
if err != nil {
|
||||
return definitionFailure(fmt.Sprintf("Unable to inspect PromptKit profile %q.", input.id), acquired.Explanation, err)
|
||||
return definitionFailure(fmt.Sprintf("Unable to inspect PromptKit %s %q.", kind, input.id), explanation, err)
|
||||
}
|
||||
if acquired.Value == nil {
|
||||
return definitionFailure("PromptKit profile inspection returned no result.", acquired.Explanation, nil)
|
||||
if value == nil {
|
||||
return definitionFailure(fmt.Sprintf("PromptKit %s inspection returned no result.", kind), explanation, nil)
|
||||
}
|
||||
if invocation.Context != nil {
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
return definitionFailure(fmt.Sprintf("Inspection of PromptKit profile %q was canceled.", input.id), acquired.Explanation, err)
|
||||
}
|
||||
if err := promptKitContextError(invocation.Context); err != nil {
|
||||
return definitionFailure(fmt.Sprintf("Inspection of PromptKit %s %q was canceled.", kind, input.id), explanation, err)
|
||||
}
|
||||
return renderProfileReport(invocation, acquired.Value, input.format, acquired.Explanation)
|
||||
}
|
||||
|
||||
type promptInputReport struct {
|
||||
Name string `yaml:"name"`
|
||||
Required bool `yaml:"required"`
|
||||
ContentType string `yaml:"content_type"`
|
||||
Description string `yaml:"description"`
|
||||
}
|
||||
|
||||
type promptOutputContractReport struct {
|
||||
Format string `yaml:"format"`
|
||||
ValidationMode string `yaml:"validation_mode"`
|
||||
SchemaPath string `yaml:"schema_path"`
|
||||
RepairAttempts int `yaml:"repair_attempts"`
|
||||
}
|
||||
|
||||
type promptInspectionReport struct {
|
||||
PromptID string `yaml:"prompt_id"`
|
||||
PromptVersion *string `yaml:"version,omitempty"`
|
||||
PromptHash string `yaml:"prompt_hash"`
|
||||
DefaultProfileID string `yaml:"default_profile_id"`
|
||||
Inputs []promptInputReport `yaml:"inputs"`
|
||||
OutputContract promptOutputContractReport `yaml:"output_contract"`
|
||||
_ = invocation.Reporter().Report(commandkit.Report{Value: value})
|
||||
return commandkit.Success()
|
||||
}
|
||||
|
||||
type requirementsInspectionReport struct {
|
||||
PromptID string `yaml:"prompt_id"`
|
||||
PromptVersion *string `yaml:"version,omitempty"`
|
||||
ProfileID string `yaml:"profile_id"`
|
||||
Complete bool `yaml:"complete"`
|
||||
Inputs []requirementInputReport `yaml:"inputs"`
|
||||
Variables []requirementVariableReport `yaml:"variables"`
|
||||
Issues []requirementIssueReport `yaml:"issues"`
|
||||
PromptID string `json:"prompt_id"`
|
||||
ProfileID string `json:"profile_id"`
|
||||
Complete bool `json:"complete"`
|
||||
Inputs []requirementInputReport `json:"inputs"`
|
||||
Variables []requirementVariableReport `json:"variables"`
|
||||
Issues []requirementIssueReport `json:"issues"`
|
||||
}
|
||||
|
||||
type requirementInputReport struct {
|
||||
Name string `yaml:"name"`
|
||||
Kind string `yaml:"kind"`
|
||||
Declared bool `yaml:"declared"`
|
||||
ContentType *string `yaml:"content_type"`
|
||||
Description *string `yaml:"description"`
|
||||
Explanation string `yaml:"explanation"`
|
||||
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 requirementVariableReport struct {
|
||||
Name string `yaml:"name"`
|
||||
Kind string `yaml:"kind"`
|
||||
Supplied bool `yaml:"supplied"`
|
||||
Explanation string `yaml:"explanation"`
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
Supplied bool `json:"supplied"`
|
||||
Explanation string `json:"explanation"`
|
||||
}
|
||||
|
||||
type requirementIssueReport struct {
|
||||
Code string `yaml:"code"`
|
||||
InputName string `yaml:"input_name"`
|
||||
VariableName string `yaml:"variable_name"`
|
||||
Description string `yaml:"description"`
|
||||
}
|
||||
|
||||
type modelParamsReport struct {
|
||||
BackendID string `yaml:"backend_id"`
|
||||
Endpoint string `yaml:"endpoint"`
|
||||
Model string `yaml:"model"`
|
||||
Temperature float64 `yaml:"temperature"`
|
||||
MaxTokens int `yaml:"max_tokens"`
|
||||
TopP float64 `yaml:"top_p"`
|
||||
TimeoutSeconds int `yaml:"timeout_seconds"`
|
||||
ServiceTier string `yaml:"service_tier"`
|
||||
ReasoningEffort string `yaml:"reasoning_effort"`
|
||||
APIKeyEnv string `yaml:"api_key_env"`
|
||||
ExtraParams map[string]any `yaml:"extra_params"`
|
||||
}
|
||||
|
||||
type profileInspectionReport struct {
|
||||
ProfileID string `yaml:"profile_id"`
|
||||
EffectiveModelParams modelParamsReport `yaml:"effective_model_params"`
|
||||
APIKeyRequired bool `yaml:"api_key_required"`
|
||||
}
|
||||
|
||||
func promptReportFromInspection(inspection *promptkit.PromptInspection) promptInspectionReport {
|
||||
report := promptInspectionReport{
|
||||
PromptID: inspection.PromptID,
|
||||
PromptVersion: inspection.PromptVersion,
|
||||
PromptHash: inspection.PromptHash,
|
||||
DefaultProfileID: inspection.DefaultProfileID,
|
||||
Inputs: make([]promptInputReport, 0, len(inspection.Inputs)),
|
||||
OutputContract: promptOutputContractReport{
|
||||
Format: string(inspection.OutputContract.Format),
|
||||
ValidationMode: string(inspection.OutputContract.ValidationMode),
|
||||
SchemaPath: inspection.OutputContract.SchemaPath,
|
||||
RepairAttempts: inspection.OutputContract.RepairAttempts,
|
||||
},
|
||||
}
|
||||
for _, input := range inspection.Inputs {
|
||||
report.Inputs = append(report.Inputs, promptInputReport{Name: input.Name, Required: input.Required, ContentType: input.ContentType, Description: input.Description})
|
||||
}
|
||||
return report
|
||||
Code string `json:"code"`
|
||||
InputName string `json:"input_name"`
|
||||
VariableName string `json:"variable_name"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
func requirementsReportFromInspection(inspection *promptkit.RequirementInspection) requirementsInspectionReport {
|
||||
report := requirementsInspectionReport{
|
||||
PromptID: inspection.PromptID,
|
||||
PromptVersion: inspection.PromptVersion,
|
||||
ProfileID: inspection.ProfileID,
|
||||
Complete: inspection.Complete,
|
||||
Inputs: make([]requirementInputReport, 0, len(inspection.Inputs)),
|
||||
Variables: make([]requirementVariableReport, 0, len(inspection.Variables)),
|
||||
Issues: make([]requirementIssueReport, 0, len(inspection.Issues)),
|
||||
PromptID: inspection.PromptID,
|
||||
ProfileID: inspection.ProfileID,
|
||||
Complete: inspection.Complete,
|
||||
Inputs: make([]requirementInputReport, 0, len(inspection.Inputs)),
|
||||
Variables: make([]requirementVariableReport, 0, len(inspection.Variables)),
|
||||
Issues: make([]requirementIssueReport, 0, len(inspection.Issues)),
|
||||
}
|
||||
for _, input := range inspection.Inputs {
|
||||
report.Inputs = append(report.Inputs, requirementInputReport{
|
||||
@@ -605,24 +517,6 @@ func requirementsReportFromInspection(inspection *promptkit.RequirementInspectio
|
||||
return report
|
||||
}
|
||||
|
||||
func profileReportFromInspection(inspection *promptkit.ProfileInspection) profileInspectionReport {
|
||||
params := inspection.EffectiveModelParams
|
||||
extra := params.ExtraParams
|
||||
if extra == nil {
|
||||
extra = map[string]any{}
|
||||
}
|
||||
return profileInspectionReport{
|
||||
ProfileID: inspection.ProfileID,
|
||||
EffectiveModelParams: modelParamsReport{
|
||||
BackendID: params.BackendID, Endpoint: params.Endpoint, Model: params.Model,
|
||||
Temperature: params.Temperature, MaxTokens: params.MaxTokens, TopP: params.TopP,
|
||||
TimeoutSeconds: params.TimeoutSeconds, ServiceTier: params.ServiceTier,
|
||||
ReasoningEffort: params.ReasoningEffort, APIKeyEnv: params.APIKeyEnv, ExtraParams: extra,
|
||||
},
|
||||
APIKeyRequired: inspection.APIKeyRequired,
|
||||
}
|
||||
}
|
||||
|
||||
func runRequirementsInspection[I, S any](invocation commandkit.Invocation, suite Suite[I, S], input *requirementsInput[I]) commandkit.Outcome {
|
||||
if invocation.Context != nil {
|
||||
if err := invocation.Context.Err(); err != nil {
|
||||
@@ -639,7 +533,7 @@ func runRequirementsInspection[I, S any](invocation commandkit.Invocation, suite
|
||||
}
|
||||
}
|
||||
|
||||
request := RequirementsRequest{Selection: input.selection, Inspection: input.inspection}
|
||||
request := RequirementsRequest{Selection: input.selection, Inspection: input.inspection, Namespaces: selectedNamespaces(suite.namespaces, input.namespaces)}
|
||||
acquired, err := suite.InspectRequirements(invocation.Context, request, input.selected, state)
|
||||
queuePromptDiagnostics(invocation.Reporter(), acquired.Diagnostics)
|
||||
if err != nil {
|
||||
@@ -653,137 +547,40 @@ func runRequirementsInspection[I, S any](invocation commandkit.Invocation, suite
|
||||
return definitionFailure(fmt.Sprintf("Requirements inspection for PromptKit prompt %q was canceled.", input.inspection.PromptID), acquired.Explanation, err)
|
||||
}
|
||||
}
|
||||
return renderPreparedPromptReport(invocation, acquired.Explanation, func() ([]byte, error) {
|
||||
return encodePromptYAMLBytes(requirementsReportFromInspection(acquired.Value))
|
||||
})
|
||||
}
|
||||
|
||||
func renderPromptReport(invocation commandkit.Invocation, inspection *promptkit.PromptInspection, format string, explanation commandkit.Explanation) commandkit.Outcome {
|
||||
return renderPreparedPromptReport(invocation, explanation, func() ([]byte, error) {
|
||||
report := promptReportFromInspection(inspection)
|
||||
if format == "yaml" {
|
||||
return encodePromptYAMLBytes(report)
|
||||
}
|
||||
return []byte(formatPromptText(report)), nil
|
||||
})
|
||||
}
|
||||
|
||||
func renderProfileReport(invocation commandkit.Invocation, inspection *promptkit.ProfileInspection, format string, explanation commandkit.Explanation) commandkit.Outcome {
|
||||
return renderPreparedPromptReport(invocation, explanation, func() ([]byte, error) {
|
||||
report := profileReportFromInspection(inspection)
|
||||
if format == "yaml" {
|
||||
return encodePromptYAMLBytes(report)
|
||||
}
|
||||
text, err := formatProfileText(report)
|
||||
return []byte(text), err
|
||||
})
|
||||
}
|
||||
|
||||
// These reports were already prepared before delivery. Keep that boundary
|
||||
// inside managed rendering, with cancellation owned by the command outcome.
|
||||
func renderPreparedPromptReport(invocation commandkit.Invocation, explanation commandkit.Explanation, prepare func() ([]byte, error)) commandkit.Outcome {
|
||||
var canceled error
|
||||
_ = invocation.Reporter().RenderOutput(func(writer io.Writer) error {
|
||||
output, err := prepare()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if canceled = promptKitContextError(invocation.Context); canceled != nil {
|
||||
return nil
|
||||
}
|
||||
_, err = writer.Write(output)
|
||||
return err
|
||||
})
|
||||
if canceled != nil {
|
||||
return definitionFailure("PromptKit report preparation was canceled.", explanation, canceled)
|
||||
}
|
||||
_ = invocation.Reporter().Report(commandkit.Report{Value: requirementsReportFromInspection(acquired.Value)})
|
||||
return commandkit.Success()
|
||||
}
|
||||
|
||||
func formatPromptText(report promptInspectionReport) string {
|
||||
var output strings.Builder
|
||||
fmt.Fprintf(&output, "Prompt ID: %s\n", strconv.Quote(report.PromptID))
|
||||
if report.PromptVersion != nil {
|
||||
fmt.Fprintf(&output, "Prompt version: %s\n", strconv.Quote(*report.PromptVersion))
|
||||
}
|
||||
fmt.Fprintf(&output, "Prompt hash: %s\n", strconv.Quote(report.PromptHash))
|
||||
fmt.Fprintf(&output, "Default profile ID: %s\n", strconv.Quote(report.DefaultProfileID))
|
||||
output.WriteString("Inputs:\n")
|
||||
for _, input := range report.Inputs {
|
||||
fmt.Fprintf(&output, " - name: %s\n required: %t\n content_type: %s\n description: %s\n", strconv.Quote(input.Name), input.Required, strconv.Quote(input.ContentType), strconv.Quote(input.Description))
|
||||
}
|
||||
if len(report.Inputs) == 0 {
|
||||
output.WriteString(" []\n")
|
||||
}
|
||||
fmt.Fprintf(&output, "Output contract:\n format: %s\n validation_mode: %s\n schema_path: %s\n repair_attempts: %d\n", strconv.Quote(report.OutputContract.Format), strconv.Quote(report.OutputContract.ValidationMode), strconv.Quote(report.OutputContract.SchemaPath), report.OutputContract.RepairAttempts)
|
||||
return output.String()
|
||||
}
|
||||
|
||||
func formatProfileText(report profileInspectionReport) (string, error) {
|
||||
params := report.EffectiveModelParams
|
||||
var output strings.Builder
|
||||
fmt.Fprintf(&output, "Profile ID: %s\n", strconv.Quote(report.ProfileID))
|
||||
output.WriteString("Effective model params:\n")
|
||||
fmt.Fprintf(&output, " backend_id: %s\n endpoint: %s\n model: %s\n temperature: %s\n max_tokens: %d\n top_p: %s\n timeout_seconds: %d\n service_tier: %s\n reasoning_effort: %s\n api_key_env: %s\n", strconv.Quote(params.BackendID), strconv.Quote(params.Endpoint), strconv.Quote(params.Model), strconv.FormatFloat(params.Temperature, 'g', -1, 64), params.MaxTokens, strconv.FormatFloat(params.TopP, 'g', -1, 64), params.TimeoutSeconds, strconv.Quote(params.ServiceTier), strconv.Quote(params.ReasoningEffort), strconv.Quote(params.APIKeyEnv))
|
||||
output.WriteString(" extra_params:\n")
|
||||
var nested strings.Builder
|
||||
if err := encodePromptYAML(&nested, params.ExtraParams); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, line := range strings.Split(strings.TrimSuffix(nested.String(), "\n"), "\n") {
|
||||
output.WriteString(" ")
|
||||
output.WriteString(line)
|
||||
output.WriteByte('\n')
|
||||
}
|
||||
fmt.Fprintf(&output, "API key required: %t\n", report.APIKeyRequired)
|
||||
return output.String(), nil
|
||||
}
|
||||
|
||||
func encodePromptYAML(writer io.Writer, value any) error {
|
||||
encoder := yaml.NewEncoder(writer)
|
||||
encoder.SetIndent(2)
|
||||
return encoder.Encode(value)
|
||||
}
|
||||
|
||||
type promptCatalogEntry struct {
|
||||
ID string `yaml:"id"`
|
||||
Version *string `yaml:"version,omitempty"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
func encodePromptCatalog(prompts []promptkit.PromptIdentity) ([]byte, error) {
|
||||
func promptCatalogReport(prompts []promptkit.PromptIdentity) any {
|
||||
entries := make([]promptCatalogEntry, len(prompts))
|
||||
for index, prompt := range prompts {
|
||||
entries[index] = promptCatalogEntry{ID: prompt.ID, Version: prompt.Version}
|
||||
entries[index] = promptCatalogEntry{ID: prompt.ID}
|
||||
}
|
||||
return encodePromptYAMLBytes(entries)
|
||||
return entries
|
||||
}
|
||||
|
||||
func encodeProfileCatalog(profiles []string) ([]byte, error) {
|
||||
if profiles == nil {
|
||||
profiles = []string{}
|
||||
func stringCatalogReport(values []string) any {
|
||||
if values == nil {
|
||||
return []string{}
|
||||
}
|
||||
return encodePromptYAMLBytes(profiles)
|
||||
return values
|
||||
}
|
||||
|
||||
type collectionCatalogEntry struct {
|
||||
Namespace string `yaml:"namespace"`
|
||||
Version *string `yaml:"version,omitempty"`
|
||||
Namespace string `json:"namespace"`
|
||||
Version *string `json:"version,omitempty"`
|
||||
}
|
||||
|
||||
func encodeCollectionCatalog(collections []promptkit.CollectionInfo) ([]byte, error) {
|
||||
func collectionCatalogReport(collections []promptkit.CollectionInfo) any {
|
||||
entries := make([]collectionCatalogEntry, len(collections))
|
||||
for index, collection := range collections {
|
||||
entries[index] = collectionCatalogEntry{Namespace: collection.Namespace, Version: collection.ReleaseVersion}
|
||||
}
|
||||
return encodePromptYAMLBytes(entries)
|
||||
}
|
||||
|
||||
func encodePromptYAMLBytes(value any) ([]byte, error) {
|
||||
var output bytes.Buffer
|
||||
if err := encodePromptYAML(&output, value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return output.Bytes(), nil
|
||||
return entries
|
||||
}
|
||||
|
||||
func queuePromptDiagnostics(reporter *commandkit.Reporter, diagnostics []commandkit.Diagnostic) {
|
||||
@@ -816,13 +613,6 @@ func definitionFailure(message string, explanation commandkit.Explanation, cause
|
||||
return outcome
|
||||
}
|
||||
|
||||
func checkDefinitionFormat(format string) error {
|
||||
if format != "text" && format != "yaml" {
|
||||
return fmt.Errorf("unsupported format %q; expected text or yaml", format)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseDefinitionString(value string) (string, error) { return value, nil }
|
||||
|
||||
func parseVariableAssignment(raw string) (variableAssignment, error) {
|
||||
@@ -834,11 +624,9 @@ func parseVariableAssignment(raw string) (variableAssignment, error) {
|
||||
}
|
||||
|
||||
func parseInputAssignment(raw string) (inputAssignment, error) {
|
||||
name, path, found := strings.Cut(raw, "=")
|
||||
name, value, found := strings.Cut(raw, "=")
|
||||
if !found {
|
||||
return inputAssignment{}, fmt.Errorf("input assignment %q must contain =", raw)
|
||||
}
|
||||
return inputAssignment{name: name, path: path}, nil
|
||||
return inputAssignment{name: name, value: value}, nil
|
||||
}
|
||||
|
||||
func stringDefault(value string) *string { return &value }
|
||||
|
||||
@@ -6,13 +6,12 @@ import (
|
||||
"errors"
|
||||
"io"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
promptkit "gitea.maximumdirect.net/eric/promptkit"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
promptkit "go.maximumdirect.net/promptkit"
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
@@ -142,7 +141,7 @@ func TestRequirementsCommandCapturesContextAndVariableAssignments(t *testing.T)
|
||||
if familyOutcome.Kind != commandkit.OutcomeSuccess || !strings.Contains(familyHelp.String(), "requirements") || strings.Contains(familyHelp.String(), "\n show ") || strings.Contains(familyHelp.String(), "\n list ") {
|
||||
t.Fatalf("requirements-only family help = (%#v, %q)", familyOutcome, familyHelp.String())
|
||||
}
|
||||
for _, flag := range []string{"--config", "--overlay", "--profile", "--session-id", "--var", "--format", "--campaign"} {
|
||||
for _, flag := range []string{"--config", "--overlay", "--llm-profile", "--llm-session-id", "--llm-var", "--format", "--campaign"} {
|
||||
if !strings.Contains(help.String(), flag) {
|
||||
t.Errorf("requirements help omits %s: %q", flag, help.String())
|
||||
}
|
||||
@@ -155,10 +154,10 @@ func TestRequirementsCommandCapturesContextAndVariableAssignments(t *testing.T)
|
||||
args := []string{
|
||||
"promptkit", "requirements", "show", "briefing", "--campaign", "spring",
|
||||
"--config", "before.yml", "--config=", "--overlay", "base.yml", "--overlay=",
|
||||
"--profile", "first", "--profile", "editorial",
|
||||
"--session-id", "old-session", "--session-id", "session-42", "--format", "text", "--format", "yaml",
|
||||
"--var", "note=hello, world", "--var", "empty=", "--var", "token=a=b", "--var", "=value",
|
||||
"--var", "mode=brief", "--var", "mode=full",
|
||||
"--llm-profile", "first", "--llm-profile", "editorial",
|
||||
"--llm-session-id", "old-session", "--llm-session-id", "session-42", "--format", "text", "--format", "yaml",
|
||||
"--llm-var", "note=hello, world", "--llm-var", "empty=", "--llm-var", "token=a=b", "--llm-var", "=value",
|
||||
"--llm-var", "mode=brief", "--llm-var", "mode=full",
|
||||
}
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || outcome.Status != 0 {
|
||||
@@ -203,10 +202,10 @@ func TestRequirementsCommandUsageFailuresPrecedeApplicationPreparation(t *testin
|
||||
}{
|
||||
{name: "missing operand", args: []string{"promptkit", "requirements", "show"}},
|
||||
{name: "extra operand", args: []string{"promptkit", "requirements", "show", "briefing", "extra"}},
|
||||
{name: "unsupported format", args: []string{"promptkit", "requirements", "show", "briefing", "--format", "text"}},
|
||||
{name: "malformed variable followed by valid assignment", args: []string{"promptkit", "requirements", "show", "briefing", "--var", "broken", "--var", "mode=full"}},
|
||||
{name: "unsupported format", args: []string{"promptkit", "requirements", "show", "briefing", "--format", "invalid"}},
|
||||
{name: "malformed variable followed by valid assignment", args: []string{"promptkit", "requirements", "show", "briefing", "--llm-var", "broken", "--llm-var", "mode=full"}},
|
||||
{name: "no built-in scope", args: []string{"promptkit", "requirements", "show", "briefing", "--scope", "all"}},
|
||||
{name: "malformed variable on help", args: []string{"help", "promptkit", "requirements", "show", "--var", "broken"}},
|
||||
{name: "malformed variable on help", args: []string{"help", "promptkit", "requirements", "show", "--llm-var", "broken"}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
newInputCalls, checkInputCalls, newStateCalls, providerCalls := 0, 0, 0, 0
|
||||
@@ -347,7 +346,7 @@ func TestDiscoveryCommandsForwardFiltersAndRenderCollections(t *testing.T) {
|
||||
ListPrompts: func(_ context.Context, request CatalogRequest, _, _ struct{}) (commandkit.Acquired[[]promptkit.PromptIdentity], error) {
|
||||
providers++
|
||||
promptRequest = request
|
||||
return commandkit.Acquired[[]promptkit.PromptIdentity]{Value: []promptkit.PromptIdentity{{ID: "team/briefing", Version: testStringPointer("")}}}, nil
|
||||
return commandkit.Acquired[[]promptkit.PromptIdentity]{Value: []promptkit.PromptIdentity{{ID: "team/briefing"}}}, nil
|
||||
},
|
||||
ListProfiles: func(_ context.Context, request CatalogRequest, _, _ struct{}) (commandkit.Acquired[[]string], error) {
|
||||
providers++
|
||||
@@ -387,7 +386,7 @@ func TestDiscoveryCommandsForwardFiltersAndRenderCollections(t *testing.T) {
|
||||
t.Fatalf("prompt list outcome/request = (%#v, %#v), output=%q", outcome, promptRequest, output)
|
||||
}
|
||||
var promptRows []map[string]any
|
||||
if err := yaml.Unmarshal([]byte(output), &promptRows); err != nil || len(promptRows) != 1 || promptRows[0]["id"] != "team/briefing" || promptRows[0]["version"] != "" {
|
||||
if err := yaml.Unmarshal([]byte(output), &promptRows); err != nil || len(promptRows) != 1 || promptRows[0]["id"] != "team/briefing" || len(promptRows[0]) != 1 {
|
||||
t.Fatalf("prompt catalog YAML = %#v, error=%v, output=%q", promptRows, err, output)
|
||||
}
|
||||
|
||||
@@ -403,7 +402,7 @@ func TestDiscoveryCommandsForwardFiltersAndRenderCollections(t *testing.T) {
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || backendRequest.Filter.Mode != promptkit.NamespaceAll {
|
||||
t.Fatalf("backend list outcome/filter = (%#v, %#v)", outcome, backendRequest.Filter)
|
||||
}
|
||||
outcome, output = run("promptkit", "list", "namespaces", "--kind", "prompt", "--kind", "backend")
|
||||
outcome, output = run("promptkit", "list", "namespaces", "--kind", "prompt", "--kind", "backend", "--format=yaml")
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || !reflect.DeepEqual(namespaceRequest.Kinds, []promptkit.ResourceKind{promptkit.ResourcePrompt, promptkit.ResourceBackend}) {
|
||||
t.Fatalf("namespace list outcome/kinds = (%#v, %#v)", outcome, namespaceRequest.Kinds)
|
||||
}
|
||||
@@ -456,12 +455,12 @@ func TestCatalogListUsesPreparedInputAndPreflightsFormat(t *testing.T) {
|
||||
ListPrompts: func(_ context.Context, request CatalogRequest, value input, gotState state) (commandkit.Acquired[[]promptkit.PromptIdentity], error) {
|
||||
providerCalls++
|
||||
received, receivedSelection, receivedState = value, request.Selection, gotState
|
||||
return commandkit.Acquired[[]promptkit.PromptIdentity]{Value: []promptkit.PromptIdentity{{ID: "briefing", Version: testStringPointer("1")}}}, nil
|
||||
return commandkit.Acquired[[]promptkit.PromptIdentity]{Value: []promptkit.PromptIdentity{{ID: "briefing"}}}, nil
|
||||
},
|
||||
}
|
||||
app := newPromptTestApp(t, Command(suite))
|
||||
var output bytes.Buffer
|
||||
invalid := app.Execute(context.Background(), []string{"promptkit", "list", "prompts", "--format", "text"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
invalid := app.Execute(context.Background(), []string{"promptkit", "list", "prompts", "--format", "invalid"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
if invalid.Kind != commandkit.OutcomeUsage || newInputCalls != 0 || newStateCalls != 0 || providerCalls != 0 || output.Len() != 0 {
|
||||
t.Fatalf("invalid format preflight = %#v, factories/providers=%d/%d/%d output=%q", invalid, newInputCalls, newStateCalls, providerCalls, output.String())
|
||||
}
|
||||
@@ -594,9 +593,9 @@ func TestCatalogNilFactoriesSupplyZeroValues(t *testing.T) {
|
||||
|
||||
func TestCatalogCommandsRenderNativeValuesAndEmptySequences(t *testing.T) {
|
||||
prompts := []promptkit.PromptIdentity{
|
||||
{ID: "later", Version: testStringPointer("1.10")},
|
||||
{ID: "001", Version: testStringPointer(" 03 ")},
|
||||
{ID: "a: true", Version: testStringPointer("yes")},
|
||||
{ID: "later"},
|
||||
{ID: "001"},
|
||||
{ID: "a: true"},
|
||||
{ID: "without-version"},
|
||||
}
|
||||
profiles := []string{"later", "001", "a: true", "later"}
|
||||
@@ -626,13 +625,8 @@ func TestCatalogCommandsRenderNativeValuesAndEmptySequences(t *testing.T) {
|
||||
if !idOK || id != prompts[index].ID {
|
||||
t.Errorf("prompt entry %d = %#v, want ID %q", index, entry, prompts[index].ID)
|
||||
}
|
||||
version, versionExists := entry["version"]
|
||||
if prompts[index].Version == nil {
|
||||
if versionExists || len(entry) != 1 {
|
||||
t.Errorf("prompt entry %d emitted absent version: %#v", index, entry)
|
||||
}
|
||||
} else if !versionExists || version != *prompts[index].Version || len(entry) != 2 {
|
||||
t.Errorf("prompt entry %d version = %#v, want %q", index, version, *prompts[index].Version)
|
||||
if _, exists := entry["version"]; exists || len(entry) != 1 {
|
||||
t.Errorf("prompt entry %d contains unexpected fields: %#v", index, entry)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -727,7 +721,7 @@ func TestCatalogFailureReportsWarningAndNativeExplanationSeparately(t *testing.T
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
canceled := newPromptTestApp(t, Command(Suite[struct{}, struct{}]{ListPrompts: func(context.Context, CatalogRequest, struct{}, struct{}) (commandkit.Acquired[[]promptkit.PromptIdentity], error) {
|
||||
cancel()
|
||||
return commandkit.Acquired[[]promptkit.PromptIdentity]{Value: []promptkit.PromptIdentity{{ID: "briefing", Version: testStringPointer("1")}}, Diagnostics: []commandkit.Diagnostic{diagnostic}}, nil
|
||||
return commandkit.Acquired[[]promptkit.PromptIdentity]{Value: []promptkit.PromptIdentity{{ID: "briefing"}}, Diagnostics: []commandkit.Diagnostic{diagnostic}}, nil
|
||||
}}))
|
||||
output.Reset()
|
||||
diagnosticOutput.Reset()
|
||||
@@ -747,7 +741,7 @@ func TestCatalogFailureReportsWarningAndNativeExplanationSeparately(t *testing.T
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
writerApp := newPromptTestApp(t, Command(Suite[struct{}, struct{}]{ListPrompts: func(context.Context, CatalogRequest, struct{}, struct{}) (commandkit.Acquired[[]promptkit.PromptIdentity], error) {
|
||||
return commandkit.Acquired[[]promptkit.PromptIdentity]{Value: []promptkit.PromptIdentity{{ID: "briefing", Version: testStringPointer("1")}}, Diagnostics: []commandkit.Diagnostic{diagnostic}}, nil
|
||||
return commandkit.Acquired[[]promptkit.PromptIdentity]{Value: []promptkit.PromptIdentity{{ID: "briefing"}}, Diagnostics: []commandkit.Diagnostic{diagnostic}}, nil
|
||||
}}))
|
||||
outcome := writerApp.Execute(context.Background(), []string{"promptkit", "list", "prompts"}, commandkit.Streams{Out: test.writer, Err: io.Discard})
|
||||
if outcome.Kind != commandkit.OutcomeOperational || !errors.Is(outcome.Presentation.Output.WriteError, test.want) || outcome.Presentation.Output.State != commandkit.DeliveryIncomplete {
|
||||
@@ -806,7 +800,7 @@ func TestCatalogAndInspectionRespectSuccessfulReportingModes(t *testing.T) {
|
||||
if output.Len() != 0 {
|
||||
t.Fatalf("quiet inspection wrote result output %q", output.String())
|
||||
}
|
||||
} else if !strings.Contains(output.String(), "Prompt ID: \"briefing\"") {
|
||||
} else if !strings.Contains(output.String(), "id: briefing") {
|
||||
t.Fatalf("%s inspection omitted result: %q", mode, output.String())
|
||||
}
|
||||
})
|
||||
@@ -815,11 +809,11 @@ func TestCatalogAndInspectionRespectSuccessfulReportingModes(t *testing.T) {
|
||||
|
||||
func TestQuietInspectionStillFindsReportEncodingFailure(t *testing.T) {
|
||||
called := false
|
||||
extra := map[string]any{"unsupported": func() {}}
|
||||
app := newPromptTestApp(t, Command(Suite[struct{}, struct{}]{InspectProfile: func(context.Context, ProfileRequest, struct{}, struct{}) (commandkit.Acquired[*promptkit.ProfileInspection], error) {
|
||||
called = true
|
||||
return commandkit.Acquired[*promptkit.ProfileInspection]{Value: &promptkit.ProfileInspection{
|
||||
ProfileID: "broken",
|
||||
EffectiveModelParams: promptkit.ExecutionTarget{ExtraParams: map[string]any{"unsupported": func() {}}},
|
||||
ProfileID: "broken", ExtraParams: &extra,
|
||||
}}, nil
|
||||
}}))
|
||||
result := &countingWriter{}
|
||||
@@ -930,147 +924,6 @@ func TestDefinitionInputAndStateLifetimesFollowChecks(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefinitionReportsRetainNativeFieldsAndSafeCredentialReferences(t *testing.T) {
|
||||
t.Setenv("PROMPTKIT_ADAPTER_TEST_KEY", "credential-value-must-not-appear")
|
||||
engine := adapterEngine(t)
|
||||
loadCalls := 0
|
||||
suite := FromEngine(func(context.Context, ckconfig.Selection, struct{}, struct{}) (*promptkit.Engine, error) {
|
||||
loadCalls++
|
||||
return engine, nil
|
||||
})
|
||||
app := newPromptTestApp(t, Command(suite))
|
||||
var output bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"promptkit", "show", "prompt", "briefing", "--format", "yaml"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || loadCalls != 1 {
|
||||
t.Fatalf("prompt report outcome=%#v load calls=%d report=%s", outcome, loadCalls, output.String())
|
||||
}
|
||||
var prompt map[string]any
|
||||
if err := yaml.Unmarshal(output.Bytes(), &prompt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inputs := prompt["inputs"].([]any)
|
||||
if len(inputs) != 2 || inputs[0].(map[string]any)["name"] != "topic" || inputs[1].(map[string]any)["name"] != "audience" || prompt["prompt_hash"] == "" {
|
||||
t.Fatalf("prompt fields/order = %#v", prompt)
|
||||
}
|
||||
contract := prompt["output_contract"].(map[string]any)
|
||||
if contract["repair_attempts"] != 0 {
|
||||
t.Fatalf("zero-valued contract field was lost: %#v", contract)
|
||||
}
|
||||
|
||||
output.Reset()
|
||||
outcome = app.Execute(context.Background(), []string{"promptkit", "show", "prompt", "briefing"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || loadCalls != 2 || !strings.Contains(output.String(), "Prompt version: \"1\"") || !strings.Contains(output.String(), `- name: "topic"`) {
|
||||
t.Fatalf("default text prompt report = (%#v, calls=%d, %s)", outcome, loadCalls, output.String())
|
||||
}
|
||||
|
||||
output.Reset()
|
||||
outcome = app.Execute(context.Background(), []string{"promptkit", "show", "profile", "default", "--format", "yaml"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || loadCalls != 3 {
|
||||
t.Fatalf("profile report outcome=%#v calls=%d report=%s", outcome, loadCalls, output.String())
|
||||
}
|
||||
var profile map[string]any
|
||||
if err := yaml.Unmarshal(output.Bytes(), &profile); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
params := profile["effective_model_params"].(map[string]any)
|
||||
if params["api_key_env"] != "PROMPTKIT_ADAPTER_TEST_KEY" || params["temperature"] != 0 || params["max_tokens"] != 0 || strings.Contains(output.String(), "credential-value-must-not-appear") {
|
||||
t.Fatalf("credential or zero model fields = %#v / %s", params, output.String())
|
||||
}
|
||||
extra := params["extra_params"].(map[string]any)
|
||||
nested := extra["nested"].(map[string]any)
|
||||
sequence := extra["sequence"].([]any)
|
||||
if extra["token"] != "caller-owned-value" || nested["null_value"] != nil || nested["visible"] != true || len(sequence) != 3 || sequence[1] != nil || sequence[2] != 3 {
|
||||
t.Fatalf("nested ExtraParams changed: %#v", extra)
|
||||
}
|
||||
|
||||
output.Reset()
|
||||
outcome = app.Execute(context.Background(), []string{"promptkit", "show", "profile", "default"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || loadCalls != 4 || !strings.Contains(output.String(), "API key required: false") || !strings.Contains(output.String(), `api_key_env: "PROMPTKIT_ADAPTER_TEST_KEY"`) {
|
||||
t.Fatalf("default text profile report = (%#v, calls=%d, %s)", outcome, loadCalls, output.String())
|
||||
}
|
||||
|
||||
output.Reset()
|
||||
outcome = app.Execute(context.Background(), []string{"promptkit", "show", "profile", "requires-key", "--format", "yaml"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || !strings.Contains(output.String(), "api_key_required: true") {
|
||||
t.Fatalf("credential requirement report = (%#v, %s)", outcome, output.String())
|
||||
}
|
||||
|
||||
output.Reset()
|
||||
outcome = app.Execute(context.Background(), []string{"promptkit", "show", "prompt", "empty", "--format", "yaml"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || !strings.Contains(output.String(), "inputs: []") {
|
||||
t.Fatalf("empty prompt input list = (%#v, %s)", outcome, output.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionalPromptVersionsPreserveAbsenceAndEmptyValues(t *testing.T) {
|
||||
empty := ""
|
||||
label := "release-1"
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
version *string
|
||||
present bool
|
||||
want string
|
||||
}{
|
||||
{name: "absent"},
|
||||
{name: "present empty", version: &empty, present: true, want: ""},
|
||||
{name: "nonempty", version: &label, present: true, want: "release-1"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
prompt := promptReportFromInspection(&promptkit.PromptInspection{PromptID: "briefing", PromptVersion: test.version})
|
||||
promptBytes, err := encodePromptYAMLBytes(prompt)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var promptReport map[string]any
|
||||
if err := yaml.Unmarshal(promptBytes, &promptReport); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertOptionalVersion(t, promptReport, test.present, test.want)
|
||||
text := formatPromptText(prompt)
|
||||
if test.present && !strings.Contains(text, "Prompt version: "+strconv.Quote(test.want)+"\n") {
|
||||
t.Errorf("text omitted present version %q: %q", test.want, text)
|
||||
}
|
||||
if !test.present && strings.Contains(text, "Prompt version:") {
|
||||
t.Errorf("text emitted absent version: %q", text)
|
||||
}
|
||||
|
||||
requirementsBytes, err := encodePromptYAMLBytes(requirementsReportFromInspection(&promptkit.RequirementInspection{PromptID: "briefing", PromptVersion: test.version}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var requirementsReport map[string]any
|
||||
if err := yaml.Unmarshal(requirementsBytes, &requirementsReport); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertOptionalVersion(t, requirementsReport, test.present, test.want)
|
||||
|
||||
catalogBytes, err := encodePromptCatalog([]promptkit.PromptIdentity{{ID: "briefing", Version: test.version}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var catalog []map[string]any
|
||||
if err := yaml.Unmarshal(catalogBytes, &catalog); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(catalog) != 1 || catalog[0]["id"] != "briefing" {
|
||||
t.Fatalf("catalog = %#v", catalog)
|
||||
}
|
||||
assertOptionalVersion(t, catalog[0], test.present, test.want)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func assertOptionalVersion(t *testing.T, report map[string]any, present bool, want string) {
|
||||
t.Helper()
|
||||
version, found := report["version"]
|
||||
if found != present {
|
||||
t.Fatalf("version presence = %t in %#v, want %t", found, report, present)
|
||||
}
|
||||
if present && version != want {
|
||||
t.Errorf("version = %#v, want %q", version, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeLookupErrorsAndBlankIDsReachCallbacks(t *testing.T) {
|
||||
nativeErr := errors.New("native lookup failure")
|
||||
calls := 0
|
||||
@@ -1129,7 +982,7 @@ func TestDefinitionFormatPreflightAndReportDeliveryFailure(t *testing.T) {
|
||||
return commandkit.Acquired[*promptkit.ProfileInspection]{Value: &promptkit.ProfileInspection{ProfileID: "default"}}, nil
|
||||
}}))
|
||||
var output bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"promptkit", "show", "profile", "default", "--format", "json"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
outcome := app.Execute(context.Background(), []string{"promptkit", "show", "profile", "default", "--format", "invalid"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
if outcome.Kind != commandkit.OutcomeUsage || calls != 0 || output.Len() != 0 {
|
||||
t.Fatalf("bad format was not rejected before callback: outcome=%#v calls=%d output=%q", outcome, calls, output.String())
|
||||
}
|
||||
@@ -1152,24 +1005,13 @@ func (writer partialReportWriter) Write(content []byte) (int, error) {
|
||||
|
||||
var _ io.Writer = partialReportWriter{}
|
||||
|
||||
func TestProfileTextUsesCredentialNamesAndExplicitEmptyExtraParams(t *testing.T) {
|
||||
report := profileReportFromInspection(&promptkit.ProfileInspection{ProfileID: "default", EffectiveModelParams: promptkit.ExecutionTarget{APIKeyEnv: "APP_KEY", ExtraParams: nil}})
|
||||
text, err := formatProfileText(report)
|
||||
if err != nil || !strings.Contains(text, "api_key_env: \"APP_KEY\"") || !strings.Contains(text, "extra_params:\n {}\n") || !strings.Contains(text, "API key required: false") {
|
||||
t.Fatalf("profile text = (%q, %v)", text, err)
|
||||
}
|
||||
if strings.Contains(text, "APP_KEY_VALUE") {
|
||||
t.Fatalf("report contains a credential value: %q", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPromptCatalogYAMLPreservesSchemaStringsAndOrder(t *testing.T) {
|
||||
want := []promptkit.PromptIdentity{
|
||||
{ID: " briefing ", Version: testStringPointer(" 03 ")},
|
||||
{ID: "001", Version: testStringPointer("1.10")},
|
||||
{ID: " briefing ", Version: testStringPointer(" 03 ")},
|
||||
{ID: " briefing "},
|
||||
{ID: "001"},
|
||||
{ID: " briefing "},
|
||||
}
|
||||
output, err := encodePromptCatalog(want)
|
||||
output, err := renderTestYAML(promptCatalogReport(want))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -1181,13 +1023,12 @@ func TestPromptCatalogYAMLPreservesSchemaStringsAndOrder(t *testing.T) {
|
||||
t.Fatalf("catalog entry count = %d, want %d: %q", len(decoded), len(want), output)
|
||||
}
|
||||
for index, entry := range decoded {
|
||||
if len(entry) != 2 {
|
||||
t.Errorf("entry %d fields = %#v, want only id and version", index, entry)
|
||||
if len(entry) != 1 {
|
||||
t.Errorf("entry %d fields = %#v, want only id", index, entry)
|
||||
}
|
||||
id, idOK := entry["id"].(string)
|
||||
version, versionOK := entry["version"].(string)
|
||||
if !idOK || !versionOK || id != want[index].ID || want[index].Version == nil || version != *want[index].Version {
|
||||
t.Errorf("entry %d = %#v, want id/version %q/%#v", index, entry, want[index].ID, want[index].Version)
|
||||
if !idOK || id != want[index].ID {
|
||||
t.Errorf("entry %d = %#v, want id %q", index, entry, want[index].ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1197,10 +1038,12 @@ func TestCatalogYAMLEncodersRenderNilAndEmptyInventoriesAsSequences(t *testing.T
|
||||
name string
|
||||
data func() ([]byte, error)
|
||||
}{
|
||||
{name: "nil prompts", data: func() ([]byte, error) { return encodePromptCatalog(nil) }},
|
||||
{name: "empty prompts", data: func() ([]byte, error) { return encodePromptCatalog(make([]promptkit.PromptIdentity, 0)) }},
|
||||
{name: "nil profiles", data: func() ([]byte, error) { return encodeProfileCatalog(nil) }},
|
||||
{name: "empty profiles", data: func() ([]byte, error) { return encodeProfileCatalog(make([]string, 0)) }},
|
||||
{name: "nil prompts", data: func() ([]byte, error) { return renderTestYAML(promptCatalogReport(nil)) }},
|
||||
{name: "empty prompts", data: func() ([]byte, error) {
|
||||
return renderTestYAML(promptCatalogReport(make([]promptkit.PromptIdentity, 0)))
|
||||
}},
|
||||
{name: "nil profiles", data: func() ([]byte, error) { return renderTestYAML(stringCatalogReport(nil)) }},
|
||||
{name: "empty profiles", data: func() ([]byte, error) { return renderTestYAML(stringCatalogReport(make([]string, 0))) }},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
output, err := test.data()
|
||||
@@ -1216,7 +1059,7 @@ func TestCatalogYAMLEncodersRenderNilAndEmptyInventoriesAsSequences(t *testing.T
|
||||
|
||||
func TestProfileCatalogYAMLPreservesStringValuesAndOrder(t *testing.T) {
|
||||
want := []string{" default ", "001", "same", "same"}
|
||||
output, err := encodeProfileCatalog(want)
|
||||
output, err := renderTestYAML(stringCatalogReport(want))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -1236,7 +1079,7 @@ func TestProfileCatalogYAMLPreservesStringValuesAndOrder(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRequirementsReportRendersEmptyInventoriesAndFalseValues(t *testing.T) {
|
||||
output, err := encodePromptYAMLBytes(requirementsReportFromInspection(&promptkit.RequirementInspection{}))
|
||||
output, err := renderTestYAML(requirementsReportFromInspection(&promptkit.RequirementInspection{}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -1272,10 +1115,9 @@ func TestRequirementsReportPreservesNativeFieldsAndMetadata(t *testing.T) {
|
||||
empty := ""
|
||||
contentType := "true"
|
||||
inspection := &promptkit.RequirementInspection{
|
||||
PromptID: "true",
|
||||
PromptVersion: testStringPointer("001"),
|
||||
ProfileID: "null",
|
||||
Complete: true,
|
||||
PromptID: "true",
|
||||
ProfileID: "null",
|
||||
Complete: true,
|
||||
Inputs: []promptkit.InputRequirement{
|
||||
{Name: "true", Kind: promptkit.RequirementKind("123"), Declared: false, Description: &empty},
|
||||
{Name: "001", Kind: promptkit.RequirementKind("future_kind"), Declared: true, ContentType: &contentType, Explanation: "false"},
|
||||
@@ -1295,7 +1137,7 @@ func TestRequirementsReportPreservesNativeFieldsAndMetadata(t *testing.T) {
|
||||
for _, complete := range []bool{true, false} {
|
||||
t.Run(map[bool]string{true: "complete", false: "partial"}[complete], func(t *testing.T) {
|
||||
inspection.Complete = complete
|
||||
output, err := encodePromptYAMLBytes(requirementsReportFromInspection(inspection))
|
||||
output, err := renderTestYAML(requirementsReportFromInspection(inspection))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -1303,10 +1145,13 @@ func TestRequirementsReportPreservesNativeFieldsAndMetadata(t *testing.T) {
|
||||
if err := yaml.Unmarshal(output, &report); err != nil {
|
||||
t.Fatalf("decode requirements report %q: %v", output, err)
|
||||
}
|
||||
if report["complete"] != complete || report["prompt_id"] != "true" || report["version"] != "001" || report["profile_id"] != "null" {
|
||||
if report["complete"] != complete || report["prompt_id"] != "true" || report["profile_id"] != "null" {
|
||||
t.Fatalf("selected context or completeness = %#v", report)
|
||||
}
|
||||
|
||||
if _, exists := report["version"]; exists {
|
||||
t.Fatalf("requirements version emitted: %#v", report)
|
||||
}
|
||||
inputs, ok := report["inputs"].([]any)
|
||||
if !ok || len(inputs) != 2 {
|
||||
t.Fatalf("inputs = %#v", report["inputs"])
|
||||
|
||||
@@ -9,11 +9,11 @@ import (
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
configkit "gitea.maximumdirect.net/eric/ConfigKit"
|
||||
promptkit "gitea.maximumdirect.net/eric/promptkit"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
"go.maximumdirect.net/ckprompt"
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
promptkit "go.maximumdirect.net/promptkit"
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
@@ -64,7 +64,7 @@ func TestPublicConfigDiffUsesPromptKitPairAndPreparedInputs(t *testing.T) {
|
||||
events = append(events, "state")
|
||||
return &compositionState{token: len(events)}
|
||||
},
|
||||
Selectors: []ckconfig.Selector[*compositionInput]{{Binding: flag, Scopes: []string{"app", "promptkit"}}},
|
||||
Selectors: []ckconfig.Selector[*compositionInput]{{Binding: flag, AgainstName: "against-campaign", Scopes: []string{"app", "promptkit"}}},
|
||||
CheckInput: func(scope string, selection ckconfig.Selection, input *compositionInput) error {
|
||||
if scope == "promptkit" {
|
||||
events = append(events, "check")
|
||||
@@ -90,7 +90,7 @@ func TestPublicConfigDiffUsesPromptKitPairAndPreparedInputs(t *testing.T) {
|
||||
rightSet bool
|
||||
}{
|
||||
{name: "right selection is explicit", rightArgs: []string{"--against-config", "after.yml"}, rightValue: "after.yml", rightSet: true},
|
||||
{name: "right selection inherits", rightValue: "before.yml", rightSet: true},
|
||||
{name: "right selection remains omitted"},
|
||||
{name: "empty right selection is supplied", rightArgs: []string{"--against-config", ""}, rightSet: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
@@ -100,7 +100,7 @@ func TestPublicConfigDiffUsesPromptKitPairAndPreparedInputs(t *testing.T) {
|
||||
loadedInputs = nil
|
||||
loadedStates = nil
|
||||
loadedSelections = nil
|
||||
args := []string{"config", "diff", "--scope", "promptkit", "--config", "before.yml", "--campaign", "spring"}
|
||||
args := []string{"config", "diff", "--scope", "promptkit", "--config", "before.yml", "--campaign", "spring", "--against-campaign", "spring"}
|
||||
args = append(args, test.rightArgs...)
|
||||
var output bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
@@ -153,7 +153,7 @@ func TestPublicConfigDiffUsesPromptKitPairAndPreparedInputs(t *testing.T) {
|
||||
}
|
||||
|
||||
var diagnostics bytes.Buffer
|
||||
failure := app.Execute(context.Background(), []string{"config", "diff", "--scope", "promptkit", "--config", "bad-left.yml", "--against-config", "right.yml", "--campaign", "spring"}, commandkit.Streams{Out: io.Discard, Err: &diagnostics})
|
||||
failure := app.Execute(context.Background(), []string{"config", "diff", "--scope", "promptkit", "--config", "bad-left.yml", "--against-config", "right.yml", "--campaign", "spring", "--against-campaign", "spring"}, commandkit.Streams{Out: io.Discard, Err: &diagnostics})
|
||||
if failure.Kind != commandkit.OutcomeOperational || !strings.Contains(diagnostics.String(), `Configuration scope "promptkit" (left):`) {
|
||||
t.Fatalf("installed load failure = %#v, diagnostics %q", failure, diagnostics.String())
|
||||
}
|
||||
@@ -224,8 +224,7 @@ func TestPublicConfigDiffDiscoveryAndNarrowedCapabilities(t *testing.T) {
|
||||
func comparisonEngine(t *testing.T, greeting string) *promptkit.Engine {
|
||||
t.Helper()
|
||||
configuration := `prompts:
|
||||
briefing:
|
||||
version: "1"
|
||||
- id: briefing
|
||||
default_profile: default
|
||||
messages:
|
||||
- role: user
|
||||
@@ -234,10 +233,10 @@ func comparisonEngine(t *testing.T, greeting string) *promptkit.Engine {
|
||||
format: text
|
||||
validation_mode: none
|
||||
backends:
|
||||
local:
|
||||
- id: local
|
||||
endpoint: "https://example.invalid/v1"
|
||||
profiles:
|
||||
default:
|
||||
- id: default
|
||||
backend: local
|
||||
model: example
|
||||
`
|
||||
@@ -248,7 +247,7 @@ profiles:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Underlays: []configkit.Underlay{{Inputs: inputs}}}})
|
||||
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Underlays: []configkit.Underlay{{Inputs: inputs}}}}, promptkit.WithBundledOpenRouter(false))
|
||||
if err != nil {
|
||||
t.Fatalf("construct comparison engine: %v", err)
|
||||
}
|
||||
|
||||
@@ -8,11 +8,11 @@ import (
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
configkit "gitea.maximumdirect.net/eric/ConfigKit"
|
||||
promptkit "gitea.maximumdirect.net/eric/promptkit"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
"go.maximumdirect.net/ckprompt"
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
promptkit "go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
type compositionInput struct{ Campaign commandkit.Supplied[string] }
|
||||
@@ -144,8 +144,7 @@ func TestPromptKitAliasesComposeWithInstalledOperations(t *testing.T) {
|
||||
func TestPublicConfigurationAndDefinitionFamiliesRemainIndependent(t *testing.T) {
|
||||
inputs, err := promptkit.FilesystemInputs("composition fixture", fstest.MapFS{
|
||||
"config/prompts.yml": &fstest.MapFile{Data: []byte(`prompts:
|
||||
briefing:
|
||||
version: "1"
|
||||
- id: briefing
|
||||
default_profile: default
|
||||
messages:
|
||||
- role: user
|
||||
@@ -154,17 +153,17 @@ func TestPublicConfigurationAndDefinitionFamiliesRemainIndependent(t *testing.T)
|
||||
format: text
|
||||
validation_mode: none
|
||||
backends:
|
||||
local:
|
||||
- id: local
|
||||
endpoint: "https://example.invalid/v1"
|
||||
profiles:
|
||||
default:
|
||||
- id: default
|
||||
backend: local
|
||||
model: example
|
||||
`)}}, "config")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Underlays: []configkit.Underlay{{Inputs: inputs}}}})
|
||||
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Underlays: []configkit.Underlay{{Inputs: inputs}}}}, promptkit.WithBundledOpenRouter(false))
|
||||
if err != nil {
|
||||
t.Fatalf("construct engine: %v", err)
|
||||
}
|
||||
@@ -226,7 +225,7 @@ profiles:
|
||||
|
||||
output.Reset()
|
||||
outcome = command.Execute(context.Background(), []string{"promptkit", "show", "profile", "default", "--campaign", "spring", "--format", "yaml"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || appAcquisitions != 1 || engineScopeAcquisitions != 1 || loaderCalls != 2 || !bytes.Contains(output.Bytes(), []byte("profile_id: default")) {
|
||||
if outcome.Kind != commandkit.OutcomeSuccess || appAcquisitions != 1 || engineScopeAcquisitions != 1 || loaderCalls != 2 || !bytes.Contains(output.Bytes(), []byte("id: default")) {
|
||||
t.Fatalf("independent profile run = (%#v, output=%q, counts=%d/%d/%d)", outcome, output.String(), appAcquisitions, engineScopeAcquisitions, loaderCalls)
|
||||
}
|
||||
if newInputCalls != 3 || newStateCalls != 2 {
|
||||
|
||||
31
integrations/ckprompt/declarations.go
Normal file
31
integrations/ckprompt/declarations.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package ckprompt
|
||||
|
||||
import commandkit "go.maximumdirect.net/commandkit"
|
||||
|
||||
type requestBinding[I any] struct {
|
||||
flag commandkit.Flag[I]
|
||||
definition requestFlagDefinition
|
||||
}
|
||||
|
||||
// appendRequestBindings installs the selected handles and, when requested,
|
||||
// records their convenience aliases for the exact owning command.
|
||||
func appendRequestBindings[I any](flags []commandkit.Flag[I], path string, aliases *[]commandkit.Declaration, bindings ...requestBinding[I]) []commandkit.Flag[I] {
|
||||
for _, binding := range bindings {
|
||||
flags = append(flags, binding.flag)
|
||||
if aliases != nil {
|
||||
for _, name := range binding.definition.aliases {
|
||||
*aliases = append(*aliases, commandkit.FlagAliasFor(path, "--"+name, "--"+binding.definition.meta.Name))
|
||||
}
|
||||
}
|
||||
}
|
||||
return flags
|
||||
}
|
||||
|
||||
// Declarations returns the canonical PromptKit command family and scoped
|
||||
// convenience aliases for the operations and flags enabled by suite. Command
|
||||
// remains available for installations that want only canonical spellings.
|
||||
func Declarations[I, S any](suite Suite[I, S]) []commandkit.Declaration {
|
||||
var aliases []commandkit.Declaration
|
||||
command := buildCommand(suite, &aliases)
|
||||
return append([]commandkit.Declaration{command}, aliases...)
|
||||
}
|
||||
123
integrations/ckprompt/declarations_test.go
Normal file
123
integrations/ckprompt/declarations_test.go
Normal file
@@ -0,0 +1,123 @@
|
||||
package ckprompt_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/ckprompt"
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
promptkit "go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
func TestDeclarationsInstallOnlySelectedScopedAliases(t *testing.T) {
|
||||
var got ckprompt.PreparationRequest
|
||||
calls := 0
|
||||
suite := ckprompt.WithNamespaces(ckprompt.Suite[struct{}, struct{}]{PrepareRequest: func(_ context.Context, request ckprompt.PreparationRequest, _, _ struct{}) (commandkit.Acquired[*promptkit.PreparedRun], error) {
|
||||
calls++
|
||||
got = request
|
||||
return commandkit.Acquired[*promptkit.PreparedRun]{Value: &promptkit.PreparedRun{}}, nil
|
||||
}}, promptkit.Namespaces{Prompt: "default"})
|
||||
declarations := append(ckprompt.Declarations(suite), commandkit.Alias("preview", "promptkit show prepared"), commandkit.Completion("app"))
|
||||
app, err := commandkit.New(commandkit.Identity{Name: "app"}, declarations...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var help bytes.Buffer
|
||||
for _, args := range [][]string{{"promptkit", "show", "prepared", "--help"}, {"__complete", "promptkit", "show", "prepared", ""}} {
|
||||
result := app.Execute(context.Background(), args, commandkit.Streams{Out: &help, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || calls != 0 {
|
||||
t.Fatalf("metadata %v = %#v calls=%d", args, result, calls)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(help.String(), "--llm-input-text") || !strings.Contains(help.String(), "--input") {
|
||||
t.Fatalf("alias help = %q", help.String())
|
||||
}
|
||||
result := app.Execute(context.Background(), []string{"preview", "p", "--profile=", "--prompt-namespace=", "--input-file=x=path", "--llm-input=x=literal", "--input-text=y=first", "--llm-input-file=y=last", "--input=z=", "--model=fixture"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || calls != 1 || got.Namespaces == nil || got.Namespaces.Prompt != "" || got.Request.Execution == nil || got.Request.Execution.Model != "fixture" || got.Request.Inputs["x"] != promptkit.Inline("literal") || got.Request.Inputs["y"] != promptkit.File("last") || got.Request.Inputs["z"] != promptkit.Inline("") {
|
||||
t.Fatalf("result=%#v request=%#v calls=%d", result, got, calls)
|
||||
}
|
||||
for _, flag := range []string{"--backend=unavailable", "--unknown=value"} {
|
||||
result = app.Execute(context.Background(), []string{"preview", "p", flag}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeUsage || calls != 1 {
|
||||
t.Fatalf("inapplicable %s = %#v", flag, result)
|
||||
}
|
||||
}
|
||||
canonical, err := commandkit.New(commandkit.Identity{Name: "app"}, ckprompt.Command(suite))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
help.Reset()
|
||||
result = canonical.Execute(context.Background(), []string{"promptkit", "show", "prepared", "--help"}, commandkit.Streams{Out: &help, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeSuccess || strings.Contains(help.String(), "--input ") {
|
||||
t.Fatalf("canonical help = %q", help.String())
|
||||
}
|
||||
result = canonical.Execute(context.Background(), []string{"promptkit", "show", "prepared", "p", "--input=x=text"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
if result.Kind != commandkit.OutcomeUsage {
|
||||
t.Fatalf("canonical alias accepted: %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeclarationsDetectAliasConflicts(t *testing.T) {
|
||||
type input struct{ profile string }
|
||||
selector := commandkit.ValueFlag(commandkit.FlagMeta{Name: "profile"}, (*string)(nil), func(v string) (string, error) { return v, nil }, func(i *input, v commandkit.Supplied[string]) { i.profile = v.Value })
|
||||
suite := ckprompt.Suite[input, struct{}]{Selectors: []commandkit.Flag[input]{selector}, PrepareRequest: func(context.Context, ckprompt.PreparationRequest, input, struct{}) (commandkit.Acquired[*promptkit.PreparedRun], error) {
|
||||
return commandkit.Acquired[*promptkit.PreparedRun]{Value: &promptkit.PreparedRun{}}, nil
|
||||
}}
|
||||
if _, err := commandkit.New(commandkit.Identity{Name: "app"}, ckprompt.Declarations(suite)...); err == nil {
|
||||
t.Fatal("selector conflicting with scoped alias was accepted")
|
||||
}
|
||||
if _, err := commandkit.New(commandkit.Identity{Name: "app"}, ckprompt.Command(suite)); err != nil {
|
||||
t.Fatalf("canonical selector unexpectedly rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeclarationsCoverEnabledCommandsAndNamespaces(t *testing.T) {
|
||||
var requirements ckprompt.RequirementsRequest
|
||||
var smoke ckprompt.SmokeRequest
|
||||
suite := ckprompt.WithNamespaces(ckprompt.Suite[struct{}, struct{}]{
|
||||
InspectPrompt: func(context.Context, ckprompt.PromptRequest, struct{}, struct{}) (commandkit.Acquired[*promptkit.PromptInspection], error) {
|
||||
return commandkit.Acquired[*promptkit.PromptInspection]{Value: &promptkit.PromptInspection{}}, nil
|
||||
},
|
||||
InspectProfile: func(context.Context, ckprompt.ProfileRequest, struct{}, struct{}) (commandkit.Acquired[*promptkit.ProfileInspection], error) {
|
||||
return commandkit.Acquired[*promptkit.ProfileInspection]{Value: &promptkit.ProfileInspection{}}, nil
|
||||
},
|
||||
InspectBackend: func(context.Context, ckprompt.BackendRequest, struct{}, struct{}) (commandkit.Acquired[*promptkit.BackendInspection], error) {
|
||||
return commandkit.Acquired[*promptkit.BackendInspection]{Value: &promptkit.BackendInspection{}}, nil
|
||||
},
|
||||
InspectRequirements: func(_ context.Context, req ckprompt.RequirementsRequest, _, _ struct{}) (commandkit.Acquired[*promptkit.RequirementInspection], error) {
|
||||
requirements = req
|
||||
return commandkit.Acquired[*promptkit.RequirementInspection]{Value: &promptkit.RequirementInspection{}}, nil
|
||||
},
|
||||
ValidateRequest: func(context.Context, ckprompt.ValidationRequest, struct{}, struct{}) (commandkit.Acquired[struct{}], error) {
|
||||
return commandkit.Acquired[struct{}]{}, nil
|
||||
},
|
||||
PrepareRequest: func(context.Context, ckprompt.PreparationRequest, struct{}, struct{}) (commandkit.Acquired[*promptkit.PreparedRun], error) {
|
||||
return commandkit.Acquired[*promptkit.PreparedRun]{Value: &promptkit.PreparedRun{}}, nil
|
||||
},
|
||||
SmokeTest: func(_ context.Context, req ckprompt.SmokeRequest, _, _ struct{}) (commandkit.Acquired[*promptkit.SmokeTestReport], error) {
|
||||
smoke = req
|
||||
return commandkit.Acquired[*promptkit.SmokeTestReport]{Value: &promptkit.SmokeTestReport{}}, nil
|
||||
},
|
||||
}, promptkit.Namespaces{Prompt: "original", Profile: "profiles", Backend: "backends"})
|
||||
app, err := commandkit.New(commandkit.Identity{Name: "app"}, ckprompt.Declarations(suite)...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run := func(args ...string) commandkit.Outcome {
|
||||
return app.Execute(context.Background(), args, commandkit.Streams{Out: io.Discard, Err: io.Discard})
|
||||
}
|
||||
if result := run("promptkit", "requirements", "show", "p", "--profile=first", "--llm-profile=last", "--var=x=y", "--profile-namespace=custom"); result.Kind != commandkit.OutcomeSuccess || requirements.Inspection.ProfileID != "last" || requirements.Inspection.Vars["x"] != "y" || requirements.Namespaces == nil || requirements.Namespaces.Profile != "custom" {
|
||||
t.Fatalf("requirements = %#v %#v", result, requirements)
|
||||
}
|
||||
if result := run("promptkit", "test", "authentication", "--backend=local", "--prompt=p", "--temperature=0", "--extra-params={}", "--backend-namespace="); result.Kind != commandkit.OutcomeSuccess || smoke.Request.BackendID != "local" || smoke.Request.PromptID != "p" || smoke.Request.Execution == nil || smoke.Request.Execution.Temperature == nil || *smoke.Request.Execution.Temperature != 0 || smoke.Request.Execution.ExtraParams == nil || smoke.Namespaces == nil || smoke.Namespaces.Backend != "" {
|
||||
t.Fatalf("smoke = %#v %#v", result, smoke)
|
||||
}
|
||||
for _, args := range [][]string{{"promptkit", "show", "prompt", "p", "--prompt-namespace=x"}, {"promptkit", "show", "profile", "p", "--profile-namespace=x"}, {"promptkit", "show", "backend", "p", "--backend-namespace=x"}, {"promptkit", "requirements", "validate", "p", "--input=x=value"}} {
|
||||
if result := run(args...); result.Kind != commandkit.OutcomeSuccess {
|
||||
t.Fatalf("%v = %#v", args, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
// Package ckprompt, provided by go.maximumdirect.net/ckprompt, provides optional
|
||||
// PromptKit configuration comparison,
|
||||
// prompt catalogs, named inspections, requirements discovery and validation,
|
||||
// and native smoke testing for CommandKit. Its command factories return
|
||||
// canonical commandkit.Command declarations. Applications can install
|
||||
// commandkit.RoutingRule aliases alongside them through commandkit.New or
|
||||
// App.Register. Importing ckprompt installs neither family; callers compose its
|
||||
// prepared-request preview, and native smoke testing for CommandKit. Command
|
||||
// returns a canonical declaration; Declarations adds scoped flag aliases.
|
||||
// Applications can install those alongside other declarations through
|
||||
// commandkit.New or App.Register. Importing ckprompt installs neither family; callers compose its
|
||||
// declarations with core and ckconfig explicitly. Provider diagnostics remain
|
||||
// passive until the owning command submits them through the invocation
|
||||
// reporter, separately from any terminal explanation.
|
||||
// reporter, separately from any terminal explanation. This module uses
|
||||
// PromptKit v0.20.0 and its native engine inventory, including configured
|
||||
// bundled resources.
|
||||
package ckprompt
|
||||
|
||||
@@ -2,45 +2,32 @@
|
||||
|
||||
## PromptKit
|
||||
|
||||
Selected module: `gitea.maximumdirect.net/eric/promptkit` at `v0.16.0`.
|
||||
Selected module: `go.maximumdirect.net/promptkit` at `v0.20.0`.
|
||||
|
||||
Copyright (C) 2026 Eric Rakestraw
|
||||
|
||||
SPDX-License-Identifier: LGPL-3.0-or-later
|
||||
|
||||
License and notices: [LGPL v3.0](../../LICENSE) |
|
||||
[LICENSE](https://gitea.maximumdirect.net/eric/promptkit/src/commit/9178f3eb91c2b2138caa78e22be93c048b4bc992/LICENSE).
|
||||
[LICENSE](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/LICENSE).
|
||||
|
||||
[Source](https://gitea.maximumdirect.net/eric/promptkit/src/commit/9178f3eb91c2b2138caa78e22be93c048b4bc992).
|
||||
[Source](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf).
|
||||
|
||||
## ConfigKit
|
||||
|
||||
Selected module: `gitea.maximumdirect.net/eric/ConfigKit` at `v0.8.0` (direct dependency).
|
||||
Selected module: `go.maximumdirect.net/configkit` at `v1.1.0` (direct dependency).
|
||||
|
||||
Copyright (C) 2026 Eric Rakestraw
|
||||
|
||||
SPDX-License-Identifier: LGPL-3.0-or-later
|
||||
|
||||
License and notices: [LGPL v3.0](../../LICENSE) |
|
||||
[LICENSE](https://gitea.maximumdirect.net/eric/ConfigKit/src/commit/137769f3f18a370c68444242fb5d88e620e307e5/LICENSE).
|
||||
[LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/commit/191015e289d7f2b91abb9fdd9c4f2f5cf75b4de9/LICENSE).
|
||||
|
||||
[Source](https://gitea.maximumdirect.net/eric/ConfigKit/src/commit/137769f3f18a370c68444242fb5d88e620e307e5).
|
||||
[Source](https://forge.maximumdirect.net/base-layer/configkit/src/commit/191015e289d7f2b91abb9fdd9c4f2f5cf75b4de9).
|
||||
|
||||
## ReleaseKit
|
||||
|
||||
Selected module: `gitea.maximumdirect.net/eric/ReleaseKit` at `v0.4.1` (transitive Go tool requirement; not a runtime import).
|
||||
|
||||
Copyright (C) 2026 Eric Rakestraw
|
||||
|
||||
SPDX-License-Identifier: LGPL-3.0-or-later
|
||||
|
||||
License and notices: [LGPL v3.0](../../LICENSE) |
|
||||
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/commit/2d5a8110c61e31daf8698766114ae305d0e0e469/LICENSE).
|
||||
|
||||
[Source](https://gitea.maximumdirect.net/eric/ReleaseKit/src/commit/2d5a8110c61e31daf8698766114ae305d0e0e469).
|
||||
|
||||
## ReleaseKit (vanity module)
|
||||
|
||||
Selected module: `go.maximumdirect.net/releasekit` at `v0.9.0` (transitive Go tool requirement; not a runtime import).
|
||||
|
||||
Copyright (C) 2026 Eric Rakestraw
|
||||
|
||||
34
integrations/ckprompt/docs/releases/v0.3.0.md
Normal file
34
integrations/ckprompt/docs/releases/v0.3.0.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# CommandKit ckprompt v0.3.0
|
||||
|
||||
## Summary
|
||||
|
||||
This candidate adopts `go.maximumdirect.net/promptkit v0.18.0`,
|
||||
`go.maximumdirect.net/configkit v1.1.0`, and
|
||||
`go.maximumdirect.net/ckconfig v0.3.0`, while retaining `go.maximumdirect.net/commandkit v0.3.0`. It requires
|
||||
Go 1.27.0. Existing configuration, catalog, inspection, validation, and smoke
|
||||
operations continue to forward the selected engine's native results.
|
||||
|
||||
## Migration
|
||||
|
||||
Change PromptKit and ConfigKit imports to `go.maximumdirect.net/promptkit` and
|
||||
`go.maximumdirect.net/configkit`. Update loaders and consumers together because
|
||||
values from the old and new paths have distinct Go type identities. Migrate
|
||||
PromptKit prompt, profile, and backend maps to lists with explicit IDs, and
|
||||
update source builders, inheritance, import requiredness, and source-root
|
||||
controls as needed. See the pinned [upstream migration guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/d9f6aad30509e538fc73ea16710df3a3ec084502/docs/consumers/configuration-migration.md).
|
||||
|
||||
Prompt catalogs, prompt and requirements inspections, and smoke targets no
|
||||
longer include descriptive prompt versions. Update report consumers accordingly;
|
||||
collection release labels and source version evidence remain. Configuration
|
||||
inspection now exposes native normalized values and source evidence, and
|
||||
native comparisons treat lists atomically.
|
||||
|
||||
PromptKit's default OpenRouter bundle supplies a backend and root profiles.
|
||||
They appear in catalog and configuration reports when enabled. Applications
|
||||
that need an application-only inventory may choose
|
||||
`promptkit.WithBundledOpenRouter(false)` in their engine loader. Review smoke
|
||||
selections and configure appropriate clients and HTTP probes for the application.
|
||||
|
||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.3.0/integrations/ckprompt/COPYRIGHT) |
|
||||
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.3.0/integrations/ckprompt/LICENSE) |
|
||||
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.3.0/integrations/ckprompt/docs/oss/attribution.md)
|
||||
@@ -1,8 +1,9 @@
|
||||
# Composed consumer
|
||||
|
||||
This example uses `go.maximumdirect.net/commandkit v0.3.0`,
|
||||
`go.maximumdirect.net/ckconfig v0.2.0`, and
|
||||
`go.maximumdirect.net/ckprompt v0.2.0`.
|
||||
This example is part of the ckprompt module and uses core v0.3.0, ckconfig
|
||||
v0.3.0, ConfigKit v1.1.0, and PromptKit v0.20.0. It requires Go 1.27.0.
|
||||
The current work uses the aligned local workspace until the required core and
|
||||
ckconfig releases are published.
|
||||
|
||||
This example composes application configuration, PromptKit configuration,
|
||||
PromptKit comparison and catalogs, definition and requirements inspection, and
|
||||
@@ -13,7 +14,8 @@ go run . config scopes
|
||||
go run . config validate --scope all --campaign spring --limit=0
|
||||
go run . config diff --scope app --config fixtures/before.yml --against-config fixtures/after.yml
|
||||
go run . config diff --scope app --config fixtures/before.yml --against-config fixtures/after.yml --campaign spring --limit=0
|
||||
go run . config diff --scope promptkit --config fixtures/before.yml --against-config fixtures/after.yml --campaign spring
|
||||
go run . config diff --scope app --campaign spring --limit=0 --against-campaign autumn --against-limit=0 --set '/campaigns/spring/model="left"' --against-set '/campaigns/spring/model="right"' --details
|
||||
go run . config diff --scope promptkit --config fixtures/before.yml --against-config fixtures/after.yml --campaign spring --against-campaign spring
|
||||
go run . promptkit list prompts --config fixtures/before.yml --campaign spring
|
||||
go run . promptkit list profiles --config fixtures/after.yml --campaign autumn --format yaml
|
||||
go run . promptkit list backends --campaign spring
|
||||
@@ -23,18 +25,21 @@ go run . list collections --campaign spring
|
||||
go run . pk list bundles --campaign spring
|
||||
go run . promptkit list prompts --namespace field-notes --campaign spring
|
||||
go run . promptkit show prompt briefing --campaign spring --format yaml
|
||||
go run . promptkit show prompt briefing --campaign spring --prompt-namespace field-notes
|
||||
go run . promptkit show prepared briefing --campaign spring --input topic=sprint --profile spring --extra-params '{"campaign":"preview"}'
|
||||
go run . pk show prompt briefing --campaign spring --fmt yaml
|
||||
go run . promptkit show profile spring --campaign spring
|
||||
go run . promptkit requirements show briefing --campaign spring
|
||||
go run . promptkit requirements show briefing --campaign spring --var mode=full --format yaml
|
||||
go run . promptkit requirements validate briefing --campaign spring --input topic=fixtures/topic.txt
|
||||
go run . promptkit requirements validate briefing --campaign spring --input topic=fixtures/topic.txt --var mode=full --input notes=fixtures/notes.txt --format yaml
|
||||
go run . promptkit requirements validate briefing --campaign spring --llm-input-file topic=fixtures/topic.txt
|
||||
go run . promptkit requirements validate briefing --campaign spring --llm-input-file topic=fixtures/topic.txt --llm-var mode=full --llm-input-file notes=fixtures/notes.txt --format yaml
|
||||
go run . promptkit requirements validate briefing --campaign spring
|
||||
go run . promptkit test text_inference --campaign spring --prompt briefing --profile spring
|
||||
go run . smoke text_inference --campaign spring --prompt briefing --profile spring
|
||||
go run . promptkit test all --campaign spring --prompt briefing --profile spring
|
||||
go run . smoke text_inference --campaign spring --llm-prompt briefing --llm-profile spring
|
||||
go run . promptkit test all --campaign spring --llm-prompt briefing --llm-profile spring
|
||||
go run . pk --hlep
|
||||
go run . session restore session-42 --campaign spring
|
||||
go run . request inspect --llm-prompt briefing --llm-profile= --llm-model example --llm-input-text topic=sprint --format json
|
||||
```
|
||||
|
||||
`newApp` installs application-owned command and flag aliases alongside the
|
||||
@@ -52,8 +57,11 @@ Bash, then load a shell script as described in the
|
||||
in `composed-example config show --config=fixtures/`. The already-entered `pk`
|
||||
alias selects the PromptKit command context without loading an engine.
|
||||
|
||||
The composition calls `ckconfig.Command(suite)` and `ckprompt.Command(definitions)`
|
||||
directly in a `[]commandkit.Declaration` with root-installed routing rules.
|
||||
The composition installs `ckconfig.Command(suite)` and the complete
|
||||
`ckprompt.Declarations(definitions)` in a `[]commandkit.Declaration` with
|
||||
root-installed routing rules. The PromptKit declarations include scoped aliases;
|
||||
the application-owned `request inspect` command reuses the flag collections
|
||||
with their canonical names and does not install those aliases.
|
||||
Group children remain canonical `Command` values. For command-only slices,
|
||||
convert each `Command` to `Declaration` before appending aliases. The
|
||||
[consumer guide](../../../../docs/consumers/guide.md#application-owned-aliases)
|
||||
@@ -72,18 +80,21 @@ and the suites' GoDoc for initialization timing and ownership.
|
||||
|
||||
The application-scope comparison reports the changed default campaign and the
|
||||
updated `campaigns.spring.model`. The PromptKit-scope comparison selects spring
|
||||
on both sides and reports the native engine change under the spring profile.
|
||||
on both sides and reports the native engine change in the atomic profiles list.
|
||||
The application input check requires `--limit=0` when `--campaign` is supplied.
|
||||
Catalogs use the same selection-aware loader: the prompt catalog includes
|
||||
`briefing` version `1`, and the profile catalog includes the selected `autumn`
|
||||
profile. Prompt inspection uses an ID only; its optional version is descriptive
|
||||
metadata in the report, not a selector. The synthetic `field-notes` collection
|
||||
`briefing`, and the profile catalog includes the selected `autumn` profile.
|
||||
Prompt inspection uses an ID only. The default PromptKit bundle also contributes
|
||||
profiles and a backend to the engine inventory and source reports. The synthetic `field-notes` collection
|
||||
provides one backend, profile, and prompt for collection discovery and native
|
||||
namespace filtering. The example's shared run cache keys successful results by
|
||||
the complete supplied configuration/overlay selection and the supplied
|
||||
campaign, including presence. The campaign override is applied through ConfigKit
|
||||
before loading. These are choices for this example's loader and do not define a
|
||||
CommandKit cache policy.
|
||||
the complete supplied configuration/overlay selection, CLI overrides, and the
|
||||
supplied campaign, including presence. The campaign override and application
|
||||
scope's `--set` records are applied through ConfigKit before loading. The
|
||||
PromptKit configuration scope does not enable `--set` because its released
|
||||
configuration loader has no override handoff. An aggregate operation therefore
|
||||
rejects overrides when that scope is selected. These are choices for this
|
||||
example's loaders and do not define a CommandKit cache policy.
|
||||
|
||||
Smoke testing is explicitly wired with `ckprompt.WithSmokeTesting` and its
|
||||
optional request builder is nil, so CommandKit forwards the selected native
|
||||
@@ -103,7 +114,7 @@ The example injects a small in-memory `promptkit.LLMClient` through its shared
|
||||
run state. Catalog, inspection, and requirements commands do not call it;
|
||||
inference smoke commands do. No model service or credentials are required.
|
||||
Native HTTP checks may retain unsupported or not-applicable observations because
|
||||
the example does not configure a network probe. An aggregate smoke command can
|
||||
the selected local backend does not configure a network probe. An aggregate smoke command can
|
||||
return an operational outcome for a native diagnostic while still delivering
|
||||
the complete aggregate report.
|
||||
|
||||
@@ -115,17 +126,19 @@ not execute the prompt or establish input, credential, or execution readiness.
|
||||
See the [CLI reference](../../../../docs/cli.md#promptkit-requirements) for the
|
||||
command and report contract.
|
||||
|
||||
The validation commands exercise concrete PromptKit request preparation.
|
||||
The validation and preview commands exercise concrete PromptKit request preparation.
|
||||
The first uses the builder's campaign-specific default topic variable and the
|
||||
operator's topic file. The second also selects the notes branch and supplies its
|
||||
file. Both succeed and report only `prompt_id` and `valid: true`; they do not
|
||||
execute the prompt. The final command intentionally fails because the prompt's
|
||||
file. Validation reports only `prompt_id` and `valid: true`; preview returns the
|
||||
prepared request, including rendered messages and effective provider settings.
|
||||
Neither executes the prompt. The validation command without inputs intentionally
|
||||
fails because the prompt's
|
||||
required `topic` artifact is not supplied. The builder defaults variables from
|
||||
the selected campaign but leaves artifact bindings to the operator. The
|
||||
`requirements show` commands remain discovery reports: partial discovery can
|
||||
succeed even when a concrete request would fail validation.
|
||||
|
||||
Run `GOWORK=off go test ./...` from this example directory to check it against
|
||||
the module's declared dependencies. A local workspace can instead select the
|
||||
three current sources, as described in the
|
||||
[developer guide](../../../../docs/development.md#documentation-validation).
|
||||
Use the aligned local workspace to test the three current sources, as described in
|
||||
the [developer guide](../../../../docs/development.md#documentation-validation).
|
||||
Once released dependency requirements are aligned, `GOWORK=off go test ./...`
|
||||
from this example directory checks it against its declared dependencies.
|
||||
|
||||
@@ -2,11 +2,9 @@ default_campaign: autumn
|
||||
campaigns:
|
||||
spring:
|
||||
prompt_id: briefing
|
||||
prompt_version: "1"
|
||||
profile_id: spring
|
||||
model: spring-model-after
|
||||
autumn:
|
||||
prompt_id: briefing
|
||||
prompt_version: "1"
|
||||
profile_id: autumn
|
||||
model: autumn-model
|
||||
|
||||
@@ -2,11 +2,9 @@ default_campaign: spring
|
||||
campaigns:
|
||||
spring:
|
||||
prompt_id: briefing
|
||||
prompt_version: "1"
|
||||
profile_id: spring
|
||||
model: spring-model
|
||||
autumn:
|
||||
prompt_id: briefing
|
||||
prompt_version: "1"
|
||||
profile_id: autumn
|
||||
model: autumn-model
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user