Compare commits

..

167 Commits

Author SHA1 Message Date
2422ccf02d Prepare ckprompt v0.12.0 with released dependencies 2026-11-23 00:43:50 +00:00
cd5cf483a4 Prepare ckconfig v0.11.0 with released core 2026-11-23 00:42:06 +00:00
0b53a63648 Draft coordinated usage reporting release notes 2026-11-23 00:22:36 +00:00
ef92089125 Retire completed usage reporting plans and reviews 2026-11-23 00:20:32 +00:00
33f98db4f7 Clarify local core requirements for unreleased integrations 2026-11-22 22:24:43 +00:00
3e4309f084 Share invocation flag lookup across installation contexts 2026-11-22 22:24:06 +00:00
3415d9337d Partition flag occurrences once per invocation 2026-11-22 22:23:07 +00:00
98e3958dfb Honor help-only input checks before starting features 2026-11-22 22:21:32 +00:00
362afc79b6 Update the smoke report reference 2026-11-22 22:19:57 +00:00
611e66322d Record algorithmic audit findings 2026-11-22 22:04:51 +00:00
367d05b7d9 Record the configuration help integration gap 2026-11-22 21:42:05 +00:00
70cd68f960 Record the usage reporting review finding 2026-11-22 21:33:59 +00:00
b7467c59fa Verify native vLLM authentication findings 2026-11-22 21:07:34 +00:00
a0cdd3d7c5 Document and validate automatic usage reporting 2026-11-22 21:06:39 +00:00
a0608a53ee Demonstrate automatic usage in composed pipeline 2026-11-22 21:02:14 +00:00
07cc832f4a Report observed PromptKit invocation usage 2026-11-22 20:59:23 +00:00
0d5e13c7a9 Adopt PromptKit usage and backend evidence 2026-11-22 20:58:10 +00:00
ba6c9035b1 Verify invocation features through public assembly 2026-11-22 20:56:09 +00:00
d039efb11d Run invocation features and render final reports 2026-11-22 20:54:58 +00:00
b6cb183a71 Parse invocation flags across command discovery 2026-11-22 20:53:25 +00:00
ea3ce25001 Capture and validate invocation features 2026-11-22 20:52:04 +00:00
68515668de Plan automatic usage reporting implementation 2026-11-22 20:26:16 +00:00
f0b4108151 Clarify usage observation boundaries and plan review 2026-11-22 20:19:36 +00:00
e2ffe82324 Clarify usage reporting boundaries and core API design checkpoint 2026-11-22 20:00:43 +00:00
d9df7e2d6b Rewrite the usage reporting roadmap around the agreed target state 2026-11-22 19:39:24 +00:00
78e9c75dfe Record the agreed usage summary fields 2026-11-22 19:34:45 +00:00
d8f2f67671 Record empty usage summary and observation boundary decisions 2026-11-22 19:31:47 +00:00
b1193564e9 Record text-only usage summary decisions 2026-11-22 19:29:16 +00:00
fe4e8d756d Record usage summary reporting decisions 2026-11-22 19:28:02 +00:00
dc0ab74135 Record automatic usage installation decisions 2026-11-22 19:26:17 +00:00
91ef377bcd Record the token reporting flag decision 2026-11-22 19:24:35 +00:00
55e0f8c8b0 Update the usage reporting roadmap for PromptKit v0.25.0 2026-11-22 19:15:35 +00:00
a4aa76de33 Plan automatic PromptKit usage reporting 2026-11-22 09:55:13 +00:00
1138960e96 Retire the completed integration release records 2026-11-21 21:19:47 +00:00
54e951e38a Prepare ckprompt v0.11.0 with released ckconfig 2026-11-21 21:19:07 +00:00
eedbd83e7e Prepare ckconfig v0.10.0 for release 2026-11-21 21:18:11 +00:00
75949de63c Fix campaign prompt identity resolution 2026-11-21 20:53:36 +00:00
b874b1f076 Record the adoption review finding 2026-11-21 20:38:19 +00:00
e70a0ef301 Record adoption validation and release follow-up 2026-11-21 19:50:40 +00:00
2a086b6389 Document shared loading and integration upgrades 2026-11-21 19:48:59 +00:00
6a090ba571 Share application loading in composed example 2026-11-21 19:46:21 +00:00
ca6cf086f2 Migrate PromptKit integration to shared inspection 2026-11-21 19:43:11 +00:00
41bd3a69d4 Add native configuration subtree scopes 2026-11-21 19:38:35 +00:00
0c9e719312 Use native path readers for discovery 2026-11-21 19:35:13 +00:00
8e51ecf77e Select ConfigKit and PromptKit releases 2026-11-21 19:34:00 +00:00
946181a13e Plan the ConfigKit and PromptKit adoption 2026-11-21 19:25:05 +00:00
320526d3fc Resolve the native inspection adapter API direction 2026-11-21 19:08:44 +00:00
1546122b0b Include native inspection adapter in the adoption scope 2026-11-21 18:55:50 +00:00
71ba758a09 Document ConfigKit and PromptKit adoption roadmap 2026-11-21 18:46:48 +00:00
b1c7962f51 Make the Scriptorium format accessor proposal optional 2026-11-20 02:16:44 +00:00
d330d7637f Complete the coordinated dependency refresh releases 2026-11-17 18:20:43 +00:00
c9a56e1b15 Prepare ckprompt v0.10.0 with aligned released dependencies 2026-11-17 18:19:44 +00:00
9962368f0c Prepare ckconfig v0.9.0 with released CommandKit core 2026-11-17 18:17:47 +00:00
b57bfe176c Prepare CommandKit v0.7.0 and record release coordination 2026-11-17 18:15:55 +00:00
db8f6062af Upgrade dependencies and the release toolchain 2026-11-17 17:53:36 +00:00
29694ea874 Retire the completed PromptKit remediation 2026-11-17 01:18:00 +00:00
5905399ef3 Explain the PromptKit struct literal migration 2026-11-17 01:17:33 +00:00
6b9ccbf88b Record the PromptKit upgrade guidance gap 2026-11-17 01:03:55 +00:00
35e100fd94 Retire completed PromptKit adoption records 2026-11-17 00:54:11 +00:00
b1e7c1ee09 Record PromptKit adoption verification 2026-11-17 00:53:48 +00:00
3112068722 Prepare ckprompt v0.9.0 guidance 2026-11-17 00:53:04 +00:00
49fee9f8ee Verify constructor failure precedence 2026-11-17 00:51:51 +00:00
70b3818351 Cover PromptKit constructor configuration failures 2026-11-17 00:50:50 +00:00
46d63de913 Adopt PromptKit v0.23.1 2026-11-17 00:48:42 +00:00
d107b1235a Finalize the PromptKit adoption plan 2026-11-17 00:11:00 +00:00
8513949c20 Plan PromptKit v0.23.1 adoption 2026-11-16 21:12:17 +00:00
bf45a3fe2c Correct the published integration version table 2026-11-16 19:08:11 +00:00
263dc420b4 Record integration v0.8.0 releases and retire completed plans 2026-11-16 19:07:57 +00:00
6c7d7c90de Prepare ckprompt v0.8.0 with released ckconfig 2026-11-16 19:07:01 +00:00
735b35a0a1 Record completed configuration outcome remediation 2026-11-16 19:03:21 +00:00
21dac4f89e Preserve configuration diagnostics from request builders 2026-11-16 19:02:40 +00:00
9b673d0485 Record configuration outcome review findings 2026-11-16 18:45:50 +00:00
8a22dd6a4f Document configuration outcomes and release handoff 2026-11-16 18:08:33 +00:00
20d2924338 Verify smoke and composed configuration outcomes 2026-11-16 18:06:45 +00:00
2bd216f0d3 Classify PromptKit inspection failures 2026-11-16 18:05:24 +00:00
1c531e7109 Classify configuration command failures 2026-11-16 18:03:24 +00:00
b9cede22f9 Classify configuration loading errors 2026-11-16 18:01:26 +00:00
9d3ffff69f Plan configuration outcome implementation 2026-11-16 17:56:34 +00:00
a53bf9f916 Record configuration classification decisions 2026-11-16 17:46:31 +00:00
ed6060f344 Plan invalid configuration outcome handling 2026-11-16 17:36:31 +00:00
1e92a87706 Record completed integration releases 2026-11-10 15:34:42 +00:00
f369d6a782 Prepare ckprompt v0.7.0 with released ckconfig 2026-11-10 15:33:47 +00:00
64f6453b84 Adopt PromptKit v0.21.0 and prepare integration release notes 2026-11-10 15:30:59 +00:00
07a329033c Adopt ConfigKit v1.2.0 in both integrations 2026-11-10 15:13:00 +00:00
1ca660e35f Prepare ckprompt v0.6.0 with released dependencies 2026-11-08 15:23:50 +00:00
5ed947bd26 Prepare ckconfig v0.6.0 with released core 2026-11-08 15:22:33 +00:00
1613ff95ca Require downstream integration releases for dependency updates 2026-11-08 15:13:39 +00:00
68288ed684 Retire completed shared debug roadmap 2026-11-08 15:11:40 +00:00
56e3b013f9 Verify shared debug binding implementation 2026-11-08 15:11:15 +00:00
96c96bb793 Document shared debug input and reporting mode 2026-11-08 15:10:00 +00:00
d914295ced Align shared debug help and completion 2026-11-08 15:08:50 +00:00
a54ff03aef Cover shared debug binding composition 2026-11-08 15:03:24 +00:00
7aff296c86 Parse shared debug input once 2026-11-08 15:02:00 +00:00
3271c18b77 Accept shared debug bindings 2026-11-08 15:00:34 +00:00
7dd30f7df3 Expose invocation reporting mode 2026-11-08 14:59:37 +00:00
5e5f61a306 Plan shared debug bindings and reporting mode access 2026-11-08 14:51:21 +00:00
6727d22ce6 Adopt ordinary application settings for shared debug bindings 2026-11-08 13:59:34 +00:00
f23af30234 Select ordinary BoolFlag registration for shared debug input 2026-11-08 13:55:37 +00:00
ec0e58efff Plan shared debug binding and reporting mode access 2026-11-08 13:52:48 +00:00
69257066e2 Record completion of the integration releases 2026-11-08 00:34:41 +00:00
88ac6e76e4 Prepare ckprompt v0.5.0 with aligned release dependencies 2026-11-08 00:33:46 +00:00
5c96053255 Prepare ckconfig v0.5.0 with released core dependencies 2026-11-08 00:31:21 +00:00
49f2d09ccd Fix reporting contract link 2026-11-07 23:58:23 +00:00
af7cc1da3e Trim release profile tests to module and publication safeguards 2026-11-07 23:52:39 +00:00
ee4e226914 Clarify dependency upgrades between module releases 2026-11-07 23:43:35 +00:00
c648d1de33 Refresh operator documentation and CLI help 2026-11-07 23:31:14 +00:00
69fe35c480 Record the documentation refresh roadmap 2026-11-07 23:04:44 +00:00
68825de200 Write release notes for CommandKit v0.5.0 2026-11-07 19:08:24 +00:00
0435a632b3 Remove completed audit and remediation records 2026-11-07 17:08:32 +00:00
aac0e11ae6 Reuse the declaration validation path across siblings 2026-11-07 17:00:12 +00:00
e46d28a924 Record the remaining declaration validation inefficiency 2026-11-07 16:52:58 +00:00
1cba65fffe Record audit remediation verification 2026-11-07 16:03:39 +00:00
d1102e12c5 Correct reporting and release navigation 2026-11-07 16:01:14 +00:00
e950f61c7f Decode native diff paths without revalidation 2026-11-07 16:00:28 +00:00
c4b5bcdbc2 Simplify typed input preparation 2026-11-07 15:59:28 +00:00
b66a00da26 Separate configuration suite capture 2026-11-07 15:58:16 +00:00
a62f1f056b Separate configuration operation preparation 2026-11-07 15:57:32 +00:00
0a81be84f6 Format declaration paths only for issues 2026-11-07 15:56:25 +00:00
83386217db Reuse alias tree for discovery and help 2026-11-07 15:55:43 +00:00
0d3f7299cc Memoize flag alias resolution by context 2026-11-07 15:54:36 +00:00
02cd49d6b6 Share flag consumption between parsing and completion 2026-11-07 15:53:32 +00:00
51a147a6e5 Remove unused parser resource plumbing 2026-11-07 15:51:19 +00:00
f2822f055c Share diagnostic adaptation across integrations 2026-11-07 15:49:49 +00:00
27500dbc6c Expose ConfigKit diagnostic adaptation 2026-11-07 15:48:57 +00:00
3b75ae7d2e Document flag declaration rules 2026-11-07 15:47:54 +00:00
52f1d99994 Clarify configuration evidence providers 2026-11-07 15:47:17 +00:00
ac113291fc Share reporter detail rendering 2026-11-07 15:45:37 +00:00
8dbb25aba9 Release reporter destination references after finalization 2026-11-07 15:44:55 +00:00
7c7d1df13f Repair completion and reporting examples 2026-11-07 15:43:59 +00:00
4346b840db Separate show cancellation from rendering errors 2026-11-07 15:42:22 +00:00
552b91c0a2 Reject missing prepared requests 2026-11-07 15:41:18 +00:00
1fc6409f95 Close deferred reporting before final delivery 2026-11-07 15:40:01 +00:00
c82235100e Isolate parsed provider parameters 2026-11-07 15:38:06 +00:00
b66d265032 Preserve cancellation in aggregate smoke tests 2026-11-07 15:36:23 +00:00
a806a9a62e Clarify continuous execution of the remediation plan 2026-11-07 15:33:51 +00:00
118b49ee55 Plan the audit remediation sprint 2026-11-07 15:30:02 +00:00
d492c77471 Remove the completed shared reporting remediation plan 2026-11-07 15:20:25 +00:00
264b82bd57 Add the audit remediation roadmap 2026-11-07 15:16:03 +00:00
d131999c7c Finalize audit remediation decisions for implementation planning 2026-11-07 15:09:19 +00:00
c7f898e56e Record alias tree decision and private refactoring analysis 2026-11-07 14:52:56 +00:00
485a27a662 Record flag consumption decision and joint alias analysis 2026-11-07 14:49:56 +00:00
9e0f2d28cd Record diagnostic adapter decision and flag consumption analysis 2026-11-07 14:45:44 +00:00
2a93b45419 Record flag naming decision and diagnostic adapter analysis 2026-11-07 14:40:52 +00:00
9d4c963c53 Add audit remediation analysis and flag naming recommendation 2026-11-07 14:36:56 +00:00
1798dcde2e Record audit remediation decisions 2026-11-07 14:11:19 +00:00
f00fe1909d Consolidate and prioritize the audit findings 2026-11-07 13:48:22 +00:00
db732e3a1d Record the architectural responsibility review 2026-11-07 13:33:33 +00:00
4a91f29bcd Record the documentation consistency audit 2026-11-07 13:20:54 +00:00
efb5f77417 Record the resource management audit 2026-11-07 13:06:37 +00:00
8fe8b67b29 Record the concurrency audit 2026-11-07 12:58:48 +00:00
2ea26afcc5 Record the complexity and maintainability audit 2026-11-07 12:50:55 +00:00
1e4fb73d15 Record the algorithmic efficiency audit 2026-11-07 12:43:07 +00:00
d8da761a21 Record the functional correctness audit 2026-11-07 12:35:25 +00:00
7b2dc2f2c9 Prepare subtree filter prefixes once per discovery 2026-11-07 12:14:11 +00:00
7bb7326ed1 Reconstruct and merge ordered inputs without general sorting 2026-11-07 12:10:40 +00:00
d72c9a788f Build validation filter sets once per invocation 2026-11-07 12:07:50 +00:00
3223b5cb82 Preserve YAML string types and explicit numeric evidence 2026-11-07 12:06:50 +00:00
d7a85f5f35 Preserve ConfigKit result evidence alongside loader errors 2026-11-07 12:04:46 +00:00
07e1634e79 Retain captured PromptKit evidence after cancellation 2026-11-07 12:03:23 +00:00
c61e125649 Render configuration explanations from acquired reports 2026-11-07 12:01:53 +00:00
3a7e2d4ce7 Record algorithmic audit findings 2026-11-07 11:56:34 +00:00
f5b2d1f80c Record reporting and evidence review findings 2026-11-07 11:32:11 +00:00
f83866e44a Retire the completed adoption roadmap 2026-11-07 11:24:19 +00:00
2f43f78f76 Align ckprompt with released dependencies 2026-11-07 11:23:15 +00:00
668c609062 Record the ckconfig source release 2026-11-07 11:17:32 +00:00
bd115c8bee Prepare the ckconfig release candidate 2026-11-07 11:12:23 +00:00
f66502cb23 Record the core source release 2026-11-07 11:09:46 +00:00
152 changed files with 7319 additions and 4505 deletions

View File

@@ -1,34 +1,26 @@
# CommandKit
CommandKit is a Go library for typed command declarations, shared CLI behavior,
and application-owned execution. The core `commandkit` module is usable by
itself. ConfigKit and PromptKit support lives in separately versioned optional
modules, so applications choose which upstream libraries they add.
CommandKit helps Go applications build consistent command-line interfaces. It
provides typed flags and arguments, help, output formatting, and error reporting.
Optional integrations add commands for inspecting configuration and working with
PromptKit.
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
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.
CommandKit is in alpha. Start with the [consumer guide](docs/consumers/guide.md#core-commands)
to define a command, or run the [core example](examples/core/README.md).
Applications supply their own command handlers and decide when to exit;
CommandKit returns the result of each invocation.
## Modules
| Module | Package | Provides |
| --- | --- | --- |
| `go.maximumdirect.net/commandkit` | `commandkit` | Typed commands, bindings, execution reporting and outcomes, help, and version. |
| `go.maximumdirect.net/ckconfig` | `ckconfig` | ConfigKit-backed `config` scopes, including configuration source evidence. |
| `go.maximumdirect.net/ckprompt` | `ckprompt` | PromptKit engine configuration/comparison, five catalogs, named inspection, requirements discovery, concrete request validation, and native smoke tests. |
| `go.maximumdirect.net/commandkit` | `commandkit` | Commands, typed inputs, shared output and error reporting, help, and version. |
| `go.maximumdirect.net/ckconfig` | `ckconfig` | Commands to view, validate, explain, and compare ConfigKit configuration. |
| `go.maximumdirect.net/ckprompt` | `ckprompt` | Commands to list and inspect PromptKit resources, discover required inputs, validate and preview requests, and run smoke tests. |
Importing an integration does not install commands. The published ckconfig and
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.
Importing an integration does not install commands. Core and the integrations
are versioned separately; see the [consumer guide](docs/consumers/guide.md#module-selection)
for published versions, compatibility, and installation choices.
## Examples

5
app.go
View File

@@ -16,17 +16,22 @@ type App struct {
aliases *alias.Resolver
flagAliases map[string]resolvedFlagAliases
discoveryFlags map[string]resolvedFlagAliases
features []*invocationFeatureRecord
featureFlags []commandmeta.Flag
snapshot *routingSnapshot
}
type routingSnapshot struct {
metadata *commandmeta.Command
runners map[commandmeta.Key]commandPayload
builtins map[commandmeta.Key]bool
aliases *alias.Resolver
canonical map[string]*canonicalNode
commandAliases []commandmeta.CommandAlias
flagAliases map[string]resolvedFlagAliases
discoveryFlags map[string]resolvedFlagAliases
features []*invocationFeatureRecord
featureFlags []commandmeta.Flag
completion bool
}

View File

@@ -3,7 +3,6 @@ package commandkit
import (
"errors"
"fmt"
"sort"
"strconv"
commandmeta "go.maximumdirect.net/commandkit/internal/commandmeta"
@@ -65,6 +64,7 @@ func OccurrenceFlag[I, V any](meta FlagMeta, parse func(string) (V, error), set
// RenameFlag returns an independent binding with a new long name and no short
// spelling. Parsing, defaults, completion, requiredness, and setters are retained.
// The name follows the declaration rules in [FlagMeta].
func RenameFlag[I any](flag Flag[I], name string) Flag[I] {
binding := flag.binding
binding.meta.Name = name
@@ -84,6 +84,12 @@ func RenameFlag[I any](flag Flag[I], name string) Flag[I] {
// 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.
//
// A BoolFlag named debug receives the shared reporting flag's input. Its
// default and requiredness apply to application input, not reporting mode;
// explicit false satisfies requiredness. Its optional short spelling and
// completion metadata follow ordinary flag rules. The final input value can
// differ from [Invocation.ReportingMode] when other mode flags are supplied.
func BoolFlag[I any](meta FlagMeta, defaultValue bool, set func(*I, Supplied[bool])) Flag[I] {
binding := flagBinding[I]{identity: newBindingIdentity(), meta: meta, defaultText: fmt.Sprint(defaultValue), boolean: true}
if set == nil {
@@ -239,17 +245,6 @@ func (p preparedInput[I]) build() I {
return input
}
// prepareInput parses all supplied bindings into typed closures before it
// creates an input value. When enforceRequired is false, missing required flags
// and operands are allowed so metadata help can validate supplied syntax.
func prepareInput[I any](spec CommandSpec[I], flagValues [][]string, operands []string, enforceRequired bool) (preparedInput[I], error) {
return prepareInputWithSpellings(spec, flagValues, nil, operands, enforceRequired)
}
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))
@@ -272,18 +267,7 @@ func prepareInputWithOccurrences[I any](spec CommandSpec[I], flagValues, flagSpe
binding := flag.binding
value, err := binding.prepare(flagValues[i])
if err != nil {
var occurrenceErr *flagOccurrenceError
if errors.As(err, &occurrenceErr) {
spelling := "--" + binding.meta.Name
if occurrenceErr.index >= 0 && occurrenceErr.index < len(flagSpellings[i]) && flagSpellings[i][occurrenceErr.index] != "" {
spelling = flagSpellings[i][occurrenceErr.index]
}
return preparedInput[I]{}, &flagConversionError{
binding: binding.meta.Name, spelling: spelling,
occurrence: occurrenceErr.index + 1, cause: occurrenceErr.cause,
}
}
return preparedInput[I]{}, fmt.Errorf("flag --%s: %w", binding.meta.Name, err)
return preparedInput[I]{}, attributeFlagConversionError(binding.meta.Name, flagSpellings[i], err)
}
preparedFlags[i] = value
for index, occurrence := range value.ordered {
@@ -298,7 +282,14 @@ func prepareInputWithOccurrences[I any](spec CommandSpec[I], flagValues, flagSpe
fallbackOrdinal++
}
if occurrence.apply != nil {
if occurrences == nil {
ordered = append(ordered, occurrence)
} else {
if ordered == nil {
ordered = make([]preparedOccurrence[I], len(occurrences))
}
ordered[*occurrence.ordinal] = occurrence
}
}
}
if enforceRequired && binding.meta.Required && !binding.deferredRequired && !value.supplied && missingRequired == "" {
@@ -308,26 +299,50 @@ func prepareInputWithOccurrences[I any](spec CommandSpec[I], flagValues, flagSpe
if missingRequired != "" {
return preparedInput[I]{}, fmt.Errorf("required flag --%s was not supplied", missingRequired)
}
argumentValues, err := allocateOperands(operands, spec.Arguments, enforceRequired)
arguments, err := prepareOperands(operands, spec.Arguments, enforceRequired)
if err != nil {
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 })
// Parsed occurrences use dense parser positions; without a parser log the
// fallback ordinals were assigned in the same order as the append above.
for _, occurrence := range ordered {
if occurrence.apply != nil {
preparedValues = append(preparedValues, preparedValue[I]{apply: occurrence.apply})
}
for i, argument := range spec.Arguments {
binding := argument.binding
value, err := binding.prepare(argumentValues[i])
if err != nil {
return preparedInput[I]{}, fmt.Errorf("argument %q: %w", binding.meta.Name, err)
}
preparedValues = append(preparedValues, value)
}
preparedValues = append(preparedValues, arguments...)
return preparedInput[I]{newInput: spec.NewInput, values: preparedValues}, nil
}
func attributeFlagConversionError(name string, spellings []string, err error) error {
var occurrenceErr *flagOccurrenceError
if errors.As(err, &occurrenceErr) {
spelling := "--" + name
if occurrenceErr.index >= 0 && occurrenceErr.index < len(spellings) && spellings[occurrenceErr.index] != "" {
spelling = spellings[occurrenceErr.index]
}
return &flagConversionError{binding: name, spelling: spelling, occurrence: occurrenceErr.index + 1, cause: occurrenceErr.cause}
}
return fmt.Errorf("flag --%s: %w", name, err)
}
func prepareOperands[I any](operands []string, definitions []Argument[I], enforceRequired bool) ([]preparedValue[I], error) {
values, err := allocateOperands(operands, definitions, enforceRequired)
if err != nil {
return nil, err
}
prepared := make([]preparedValue[I], 0, len(definitions))
for i, argument := range definitions {
value, err := argument.binding.prepare(values[i])
if err != nil {
return nil, fmt.Errorf("argument %q: %w", argument.binding.meta.Name, err)
}
prepared = append(prepared, value)
}
return prepared, nil
}
func newBindingIdentity() *bindingIdentity { return &bindingIdentity{marker: 1} }
func allocateOperands[I any](operands []string, definitions []Argument[I], enforceRequired bool) ([][]string, error) {

View File

@@ -36,7 +36,7 @@ func TestScalarBindingsKeepDefaultsSeparateFromPresence(t *testing.T) {
t.Fatal(err)
}
defaultMessage = "changed after declaration"
prepared, err := prepareInput(spec, [][]string{nil, nil, nil}, nil, true)
prepared, err := prepareInputWithOccurrences(spec, [][]string{nil, nil, nil}, nil, nil, nil, true)
if err != nil {
t.Fatal(err)
}
@@ -60,7 +60,7 @@ func TestScalarBindingsKeepDefaultsSeparateFromPresence(t *testing.T) {
t.Fatalf("NewInput runtime value = %q, want caller value", input.runtime)
}
prepared, err = prepareInput(spec, [][]string{{"", "last"}, {"0"}, {"true", "false"}}, nil, true)
prepared, err = prepareInputWithOccurrences(spec, [][]string{{"", "last"}, {"0"}, {"true", "false"}}, nil, nil, nil, true)
if err != nil {
t.Fatal(err)
}
@@ -75,7 +75,7 @@ func TestScalarBindingsKeepDefaultsSeparateFromPresence(t *testing.T) {
t.Fatalf("enabled = %#v, want explicit false", input.enabled)
}
prepared, err = prepareInput(spec, [][]string{{""}, nil, nil}, nil, true)
prepared, err = prepareInputWithOccurrences(spec, [][]string{{""}, nil, nil}, nil, nil, nil, true)
if err != nil {
t.Fatal(err)
}
@@ -83,7 +83,7 @@ func TestScalarBindingsKeepDefaultsSeparateFromPresence(t *testing.T) {
if input.message.Value != "" || !input.message.Set {
t.Fatalf("message = %#v, want explicitly supplied empty string", input.message)
}
prepared, err = prepareInput(spec, [][]string{nil, nil, nil}, nil, true)
prepared, err = prepareInputWithOccurrences(spec, [][]string{nil, nil, nil}, nil, nil, nil, true)
if err != nil {
t.Fatal(err)
}
@@ -207,7 +207,7 @@ func TestRepeatArgumentAllocationReservesLaterMinimums(t *testing.T) {
if err := validateCommandDeclaration(NewCommand(spec)); err != nil {
t.Fatal(err)
}
prepared, err := prepareInput(spec, nil, []string{"a", "b", "id-1", "x", "y"}, true)
prepared, err := prepareInputWithOccurrences(spec, nil, nil, nil, []string{"a", "b", "id-1", "x", "y"}, true)
if err != nil {
t.Fatal(err)
}
@@ -237,10 +237,10 @@ func TestIncompletePreparationSkipsMissingRequirementsAndInputFactory(t *testing
if err := validateCommandDeclaration(NewCommand(spec)); err != nil {
t.Fatal(err)
}
if _, err := prepareInput(spec, [][]string{nil}, nil, true); err == nil {
if _, err := prepareInputWithOccurrences(spec, [][]string{nil}, nil, nil, nil, true); err == nil {
t.Fatal("strict preparation accepted missing requirements")
}
if _, err := prepareInput(spec, [][]string{nil}, nil, false); err != nil {
if _, err := prepareInputWithOccurrences(spec, [][]string{nil}, nil, nil, nil, false); err != nil {
t.Fatalf("help preparation rejected omitted execution inputs: %v", err)
}
if factoryCalls != 0 {

View File

@@ -32,8 +32,8 @@ func (a *App) builtinCommands() []Declaration {
help := captureCommand(CommandSpec[helpInput]{
Name: "help",
Summary: "Show help for commands.",
Description: "Describe registered commands and their inputs.",
Arguments: []Argument[helpInput]{RepeatArgument(ArgumentMeta{Name: "COMMAND", Usage: "registered command path"}, 0, -1,
Description: "Show available commands, flags, and arguments.",
Arguments: []Argument[helpInput]{RepeatArgument(ArgumentMeta{Name: "COMMAND", Usage: "Command path to describe."}, 0, -1,
func(value string) (string, error) { return value, nil },
func(input *helpInput, value Supplied[[]string]) { input.Targets = value })},
}, func(current commandExecution, input helpInput) Outcome {
@@ -43,9 +43,9 @@ func (a *App) builtinCommands() []Declaration {
version := NewCommand(CommandSpec[versionInput]{
Name: "version",
Summary: "Show application or CommandKit version.",
Description: "Report identity and build metadata without loading application configuration.",
Description: "Show the name, version, and revision 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: "scope", Usage: "Show the app or CommandKit version.", Completion: CompleteChoices(CompletionChoice{Value: "app"}, CompletionChoice{Value: "commandkit"})}, &scopeDefault, parseVersionScope, func(input *versionInput, value Supplied[string]) { input.Scope = value.Value }),
},
Run: func(invocation Invocation, input versionInput) Outcome {
identity := a.identity
@@ -58,6 +58,8 @@ func (a *App) builtinCommands() []Declaration {
return renderVersionOutcome(identity, invocation.Reporter())
},
})
help.record.builtin = true
version.record.builtin = true
return []Declaration{help, version}
}

View File

@@ -17,6 +17,10 @@ import (
// before changing an App registry.
type Command struct{ record *commandRecord }
// ErrHelpRequested may be returned by CommandSpec.CheckInput to display command
// help without starting invocation features or enforcing their required flags.
var ErrHelpRequested = errors.New("command help requested")
// Declaration is a captured canonical command or application routing rule
// accepted by New and App.Register. Use []Declaration when collecting both
// kinds. Group and RootGroup children remain Commands; install routing rules
@@ -71,10 +75,12 @@ type commandRecord struct {
summary string
description string
children []Command
features []InvocationFeature
payload commandPayload
issues []error
rootOnly bool
completion bool
builtin bool
absent bool
invalid bool
}
@@ -90,10 +96,15 @@ type Supplied[T any] struct {
// FlagMeta describes a command flag. Required applies when execution prepares
// the selected command; help reports the metadata without requiring the value.
// Invalid declarations are reported when installed.
type FlagMeta struct {
// Name is the flag name without leading dashes.
// Name is a nonempty long name without leading dashes. It consists of
// Unicode lowercase letters or digits in segments separated by single
// hyphens; digit-leading and numeric-only names are valid. The names help,
// quiet, verbose, debug, progress and format are reserved, except that a
// BoolFlag named debug attaches to the shared reporting flag.
Name string
// Short is an optional one-byte spelling.
// Short is an optional one-byte spelling other than '-' or the reserved 'h'.
Short string
// Usage briefly describes the flag.
Usage string
@@ -182,7 +193,8 @@ type CommandSpec[I any] struct {
Flags []Flag[I]
// Arguments declares the command's positional inputs.
Arguments []Argument[I]
// CheckInput validates declared combinations of parsed inputs.
// CheckInput validates declared combinations of parsed inputs. Returning
// ErrHelpRequested displays help without running the command or its features.
CheckInput func(I) error
// Run handles an invocation. It may be nil for a command used as a group.
Run func(Invocation, I) Outcome
@@ -251,9 +263,16 @@ func (c typedCommand[I]) prepare(flagValues, flagSpellings [][]string, occurrenc
input := prepared.build()
if c.spec.CheckInput != nil {
if err := c.spec.CheckInput(input); err != nil {
if errors.Is(err, ErrHelpRequested) {
return current.renderHelp(current.route.canonicalPath)
}
return classifyInputError(err)
}
}
if current.featureEnabled && current.featureRequiredError != nil {
return classifyInputError(current.featureRequiredError)
}
current.startFeatures()
if c.privateRun != nil {
return c.privateRun(current.commandContext(), input)
}
@@ -352,6 +371,7 @@ func Alias(path, target string) RoutingRule {
// wherever its canonical target flag is available and contributes nothing on
// commands without that flag. Identical mappings are accepted; different
// targets for the same source spelling in this scope are installation errors.
// Long and short spelling forms follow the grammar described by [FlagMeta].
func FlagAlias(spelling, target string) RoutingRule {
record := &routingRuleRecord{
kind: globalFlagAliasRule,
@@ -368,6 +388,7 @@ func FlagAlias(spelling, target string) RoutingRule {
// available in the complete installation. Scoped mappings take precedence over
// application-wide mappings with the same source spelling. Identical mappings
// are accepted; competing targets in the same scope are installation errors.
// Long and short spelling forms follow the grammar described by [FlagMeta].
func FlagAliasFor(commandPath, spelling, target string) RoutingRule {
record := &routingRuleRecord{
kind: scopedFlagAliasRule,
@@ -437,27 +458,40 @@ func validateCommandDeclaration(command Command) error {
func validateCommandPlacement(command Command) error {
var issues []error
collectDeclarationIssues(command, nil, true, &issues)
return errors.Join(issues...)
}
func collectDeclarationIssues(command Command, parents []string, root bool, issues *[]error) {
// Keep the grown slice header across recursive calls so siblings reuse capacity.
var path []string
var collectDeclarationIssues func(Command, bool)
collectDeclarationIssues = func(command Command, root bool) {
if command.record == nil {
*issues = append(*issues, errors.New("invalid zero command declaration"))
issues = append(issues, errors.New("invalid zero command declaration"))
return
}
record := command.record
path := append(append([]string(nil), parents...), record.name)
label := commandpath.FromTokens(path).String()
length := len(path)
path = append(path, record.name)
defer func() { path = path[:length] }()
var label string
if len(record.issues) > 0 || (record.rootOnly && !root) {
label = commandpath.Path(path).String()
}
for _, issue := range record.issues {
if label != "" {
*issues = append(*issues, fmt.Errorf("command %q: %w", label, issue))
issues = append(issues, fmt.Errorf("command %q: %w", label, issue))
} else {
*issues = append(*issues, issue)
issues = append(issues, issue)
}
}
for _, feature := range record.features {
if feature.record == nil {
issues = append(issues, fmt.Errorf("command %q: invalid zero invocation feature", record.name))
continue
}
for _, issue := range feature.record.issues {
issues = append(issues, fmt.Errorf("command %q invocation feature: %w", record.name, issue))
}
}
if record.rootOnly && !root {
*issues = append(*issues, fmt.Errorf("root-only command %q is nested beneath another command", label))
issues = append(issues, fmt.Errorf("root-only command %q is nested beneath another command", label))
}
if record.invalid || record.absent {
return
@@ -466,8 +500,11 @@ func collectDeclarationIssues(command Command, parents []string, root bool, issu
if child.record == nil {
continue
}
collectDeclarationIssues(child, path, false, issues)
collectDeclarationIssues(child, false)
}
}
collectDeclarationIssues(command, true)
return errors.Join(issues...)
}
func validateCommandName(name string) error {
@@ -485,7 +522,7 @@ func validateBindings[I any](flags []Flag[I], arguments []Argument[I]) error {
if binding.meta.Name == "help" {
return fmt.Errorf("flag name %q is reserved for help", binding.meta.Name)
}
if commandmeta.IsReportingFlag(binding.meta.Name) {
if commandmeta.IsReportingFlag(binding.meta.Name) && !(binding.meta.Name == "debug" && binding.boolean) {
return fmt.Errorf("flag name %q is reserved for reporting", binding.meta.Name)
}
if _, exists := flagNames[binding.meta.Name]; exists {

View File

@@ -28,8 +28,12 @@ func Completion(executable string) Command {
},
}))
}
for _, child := range children {
child.record.builtin = true
}
command := RootGroup("completion", "Generate shell completion scripts.", children...)
command.record.completion = true
command.record.builtin = true
if !validCompletionExecutable(executable) {
return WithError(command, fmt.Errorf("unsupported completion executable basename %q", executable))
}

View File

@@ -35,7 +35,7 @@ func resolveCompletionContext(snapshot *routingSnapshot, completed []string, cur
context.aliases = snapshot.flagAliases[context.route.canonicalPath.Key()].lookupRecords()
context.commandPosition = len(context.tail) == 0
case routeDiscovery:
context.command = &commandmeta.Command{CoreFlags: commandmeta.ReportingFlags()}
context.command = &commandmeta.Command{CoreFlags: commandmeta.ReportingFlags(), InvocationFlags: snapshot.featureFlags}
context.tail = append([]string(nil), context.route.args...)
context.aliases = snapshot.discoveryFlags[context.route.discoveryPath.Key()].lookupRecords()
}

View File

@@ -35,8 +35,7 @@ type completionFlagState struct {
func completionFlags(context completionContext) []commandmeta.Flag {
flags := make([]commandmeta.Flag, 0, len(context.command.Flags)+len(context.command.CoreFlags)+1)
flags = append(flags, commandmeta.HelpFlag())
flags = append(flags, context.command.CoreFlags...)
flags = append(flags, context.command.Flags...)
flags = append(flags, commandmeta.EffectiveFlags(append(append([]commandmeta.Flag(nil), context.command.Flags...), context.command.InvocationFlags...), context.command.CoreFlags)...)
return flags
}
@@ -53,44 +52,26 @@ func walkCompletionFlags(tokens []string, lookup commandmeta.FlagLookup) complet
state.ended = true
case commandmeta.OperandToken:
state.operands = append(state.operands, token)
case commandmeta.LongFlagToken:
spelling, _, attached := commandmeta.SplitLongFlag(token)
flag, ok := lookup.Find(spelling)
if !ok {
case commandmeta.LongFlagToken, commandmeta.ShortFlagToken:
for offset := 1; ; {
fact := commandmeta.ConsumeFlag(lookup, token, offset)
if !fact.Found {
state.invalid = true
return state
}
state.supplied[flag.Name] = true
if !flag.Boolean && !attached {
state.supplied[fact.Flag.Name] = true
if fact.NeedsNext {
if index+1 == len(tokens) {
flag := fact.Flag
state.pending = &flag
return state
}
index++
}
case commandmeta.ShortFlagToken:
for offset := 1; offset < len(token); offset++ {
flag, ok := lookup.Find("-" + token[offset:offset+1])
if !ok {
state.invalid = true
return state
}
state.supplied[flag.Name] = true
suffix := token[offset+1:]
if flag.Boolean {
if strings.HasPrefix(suffix, "=") {
if fact.NextOffset == 0 {
break
}
continue
}
if suffix == "" {
if index+1 == len(tokens) {
state.pending = &flag
return state
}
index++
}
break
offset = fact.NextOffset
}
}
}
@@ -132,10 +113,10 @@ func completionOptionTarget(current string, flags []commandmeta.Flag, lookup com
return completionTarget{kind: completionTargetFlags, choices: completionFlagNames(flags, supplied, current)}
}
if strings.HasPrefix(current, "--") {
spelling, value, attached := commandmeta.SplitLongFlag(current)
if attached {
if flag, ok := lookup.Find(spelling); ok {
return completionTarget{kind: completionTargetValue, hint: flag.Completion, prefix: spelling + "=", valuePrefix: value}
fact := commandmeta.ConsumeFlag(lookup, current, 1)
if fact.Attached {
if fact.Found {
return completionTarget{kind: completionTargetValue, hint: fact.Flag.Completion, prefix: fact.Spelling + "=", valuePrefix: fact.Value}
}
return completionTarget{}
}
@@ -145,25 +126,26 @@ func completionOptionTarget(current string, flags []commandmeta.Flag, lookup com
for name, value := range supplied {
used[name] = value
}
for offset := 1; offset < len(current); offset++ {
flag, ok := lookup.Find("-" + current[offset:offset+1])
if !ok {
for offset := 1; offset < len(current); {
fact := commandmeta.ConsumeFlag(lookup, current, offset)
if !fact.Found {
return completionTarget{}
}
used[flag.Name] = true
suffix := current[offset+1:]
if flag.Boolean {
if strings.HasPrefix(suffix, "=") {
return completionTarget{kind: completionTargetValue, hint: flag.Completion, prefix: current[:offset+2], valuePrefix: suffix[1:]}
}
continue
used[fact.Flag.Name] = true
if fact.Flag.Boolean && fact.Attached {
return completionTarget{kind: completionTargetValue, hint: fact.Flag.Completion, prefix: current[:offset+2], valuePrefix: fact.Value}
}
if !fact.Flag.Boolean {
prefix := current[:offset+1]
if strings.HasPrefix(suffix, "=") {
if strings.HasPrefix(current[offset+1:], "=") {
prefix += "="
suffix = suffix[1:]
}
return completionTarget{kind: completionTargetValue, hint: flag.Completion, prefix: prefix, valuePrefix: suffix}
return completionTarget{kind: completionTargetValue, hint: fact.Flag.Completion, prefix: prefix, valuePrefix: fact.Value}
}
if fact.NextOffset == 0 {
break
}
offset = fact.NextOffset
}
var choices []commandmeta.CompletionChoice
for _, flag := range flags {

View File

@@ -70,6 +70,34 @@ func TestCompletionFlagAndValuePositions(t *testing.T) {
}
}
func TestSharedDebugCompletionHints(t *testing.T) {
for _, tc := range []struct {
name string
hint CompletionHint
want commandmeta.CompletionKind
}{
{"none", NoCompletion(), commandmeta.CompletionNone},
{"choices", CompleteChoices(CompletionChoice{Value: "true"}), commandmeta.CompletionChoices},
{"files", CompleteFiles(), commandmeta.CompletionFiles},
{"directories", CompleteDirectories(), commandmeta.CompletionDirectories},
} {
t.Run(tc.name, func(t *testing.T) {
command := NewCommand(CommandSpec[struct{}]{Name: "run", Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "debug", Short: "d", Completion: tc.hint}, false, func(*struct{}, Supplied[bool]) {})}, Run: func(Invocation, struct{}) Outcome { return Success() }})
app, err := New(Identity{Name: "example"}, command)
if err != nil {
t.Fatal(err)
}
snapshot := app.routeSnapshot()
for _, current := range []string{"--debug=", "-d="} {
target := completionTargetFor(snapshot, resolveCompletionContext(snapshot, []string{"run"}, current))
if target.kind != completionTargetValue || target.hint.Kind != tc.want {
t.Fatalf("%s: %#v", current, target)
}
}
})
}
}
func TestCompletionOperandAllocation(t *testing.T) {
arguments := []commandmeta.Argument{
{Name: "optional", Min: 0, Max: 1, Completion: commandmeta.CompletionHint{Kind: commandmeta.CompletionFiles}},

View File

@@ -120,3 +120,51 @@ func TestCompletionQueryDiscovery(t *testing.T) {
t.Fatalf("discovery outcome=%#v reply=%q", outcome, output.String())
}
}
func TestSharedDebugHelpAndCompletion(t *testing.T) {
var factories, setters, checks, handlers int
command := NewCommand(CommandSpec[struct{}]{
Name: "run",
NewInput: func() struct{} { factories++; return struct{}{} },
Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "debug", Short: "d", Usage: "application tracing", Required: true, Completion: CompleteChoices(CompletionChoice{Value: "true"}, CompletionChoice{Value: "trace"})}, true, func(*struct{}, Supplied[bool]) { setters++ })},
CheckInput: func(struct{}) error { checks++; return nil },
Run: func(Invocation, struct{}) Outcome { handlers++; return Success() },
})
app, err := New(Identity{Name: "example"}, command, Completion("example"), Alias("shortcut", "run"))
if err != nil {
t.Fatal(err)
}
for _, args := range [][]string{{"run", "--help"}, {"help", "run"}, {"shortcut", "--help"}, {"help", "shortcut"}, {"run", "--unknown"}, {"shortcut", "--unknown"}} {
var output, diagnostic bytes.Buffer
result := app.Execute(context.Background(), args, Streams{Out: &output, Err: &diagnostic})
text := output.String() + diagnostic.String()
if strings.Count(text, "--debug") != 1 || !strings.Contains(text, "-d") || !strings.Contains(text, "application tracing") || !strings.Contains(text, "application input defaults to true") || !strings.Contains(text, "required") || !strings.Contains(text, "default: false") {
t.Fatalf("%v: outcome=%#v text=%q", args, result, text)
}
}
for _, tc := range []struct {
args []string
want string
count int
}{
{[]string{"__complete", "run", "--deb"}, "--debug", 1},
{[]string{"__complete", "run", "-"}, "\n-d\t", 1},
{[]string{"__complete", "run", "--debug=tr"}, "trace", 1},
{[]string{"__complete", "run", "-d=tr"}, "trace", 1},
} {
var output bytes.Buffer
result := app.Execute(context.Background(), tc.args, Streams{Out: &output, Err: io.Discard})
if result.Kind != OutcomeSuccess || strings.Count(output.String(), tc.want) != tc.count {
t.Fatalf("%v: %#v %q", tc.args, result, output.String())
}
}
if factories != 0 || setters != 0 || checks != 0 || handlers != 0 {
t.Fatalf("callbacks: %d %d %d %d", factories, setters, checks, handlers)
}
if result := app.Execute(context.Background(), []string{"run", "--debug=invalid", "--help"}, Streams{Out: io.Discard, Err: io.Discard}); result.Kind != OutcomeUsage {
t.Fatalf("help skipped boolean validation: %#v", result)
}
if result := app.Execute(context.Background(), []string{"run", "--debug=trace"}, Streams{Out: io.Discard, Err: io.Discard}); result.Kind != OutcomeUsage {
t.Fatalf("suggestion bypassed boolean parsing: %#v", result)
}
}

View File

@@ -32,9 +32,9 @@ func TestCompletionConsumerInShells(t *testing.T) {
directory bool
}{
{"canonical command", "probe ru", []string{"run"}, false},
{"entered alias", "probe shortcut --format=ya", []string{"shortcut", "--format=yaml"}, false},
{"choice", "probe run --format=te", []string{"run", "--format=text"}, false},
{"no file fallback", `probe run --format=./partial\ f`, []string{"run", "--format=./partial f"}, false},
{"entered alias", "probe shortcut --choice=ya", []string{"shortcut", "--choice=yaml"}, false},
{"choice", "probe run --choice=te", []string{"run", "--choice=text"}, false},
{"no file fallback", `probe run --choice=./partial\ f`, []string{"run", "--choice=./partial f"}, false},
{"separated file", `probe run --config ./partial\ f`, []string{"run", "--config", "./partial file"}, false},
{"attached file", `probe run --config=./partial\ f`, []string{"run", "--config=./partial file"}, false},
{"short attached file", `probe run -c./partial\ f`, []string{"run", "-c./partial file"}, false},
@@ -42,7 +42,7 @@ func TestCompletionConsumerInShells(t *testing.T) {
{"separated directory", "probe run --directory ./partial", []string{"run", "--directory", "./partial dir"}, true},
{"attached directory", "probe run --directory=./partial", []string{"run", "--directory=./partial dir"}, true},
{"empty operand", "probe run ", []string{"run", "alpha"}, false},
{"leading dash", "probe run --for", []string{"run", "--format"}, false},
{"leading dash", "probe run --cho", []string{"run", "--choice"}, false},
}
for _, shell := range []string{"bash", "zsh", "fish"} {
generator := exec.Command(app, "completion", shell)
@@ -82,7 +82,7 @@ func TestCompletionConsumerInShells(t *testing.T) {
})
}
t.Run(shell+"/descriptions", func(t *testing.T) {
terminal := exec.Command("python3", "internal/cobra/testdata/completion_terminal.py", shell, scriptPath, "probe run --format=")
terminal := exec.Command("python3", "internal/cobra/testdata/completion_terminal.py", shell, scriptPath, "probe run --choice=")
terminal.Env = append(os.Environ(), "PATH="+dir+string(os.PathListSeparator)+os.Getenv("PATH"), "HOME="+dir, "TERM=xterm", "PROBE_LOG="+filepath.Join(dir, "log"), "PROBE_DIR="+dir, "PROBE_LIST=1")
output, err := terminal.CombinedOutput()
if err != nil || !strings.Contains(string(output), "Readable text") || !strings.Contains(string(output), "YAML output") {

View File

@@ -79,3 +79,40 @@ func TestCompletionChoicesDoNotRestrictExecution(t *testing.T) {
t.Fatalf("outcome=%#v input=%#v", outcome, received)
}
}
func TestCompletionConsumesFlagGrammarAndKeepsPendingValues(t *testing.T) {
flags := []commandmeta.Flag{{Name: "verbose", Short: "v", Boolean: true}, {Name: "choice", Short: "c", Completion: commandmeta.CompletionHint{Kind: commandmeta.CompletionChoices}}}
lookup := commandmeta.NewFlagLookup(flags, []commandmeta.FlagAlias{{Source: "-x", Target: "--choice"}})
for _, tc := range []struct {
name string
tokens []string
pending, operand string
invalid bool
}{
{name: "cluster attached empty", tokens: []string{"-vc="}, operand: ""},
{name: "option-looking value", tokens: []string{"-vx", "--other"}, operand: ""},
{name: "pending", tokens: []string{"-vx"}, pending: "choice"},
{name: "unknown cluster", tokens: []string{"-vz"}, invalid: true},
{name: "terminator", tokens: []string{"--", "--choice"}, operand: "--choice"},
} {
t.Run(tc.name, func(t *testing.T) {
state := walkCompletionFlags(tc.tokens, lookup)
if state.invalid != tc.invalid {
t.Fatalf("state=%#v", state)
}
if tc.pending != "" && (state.pending == nil || state.pending.Name != tc.pending) {
t.Fatalf("pending=%#v", state.pending)
}
if tc.pending == "" && state.pending != nil {
t.Fatalf("unexpected pending=%#v", state.pending)
}
if tc.operand != "" && (len(state.operands) != 1 || state.operands[0] != tc.operand) {
t.Fatalf("operands=%v", state.operands)
}
})
}
target := completionOptionTarget("-vc=", flags, lookup, nil)
if target.kind != completionTargetValue || target.prefix != "-vc=" || target.valuePrefix != "" {
t.Fatalf("partial target = %#v", target)
}
}

18
doc.go
View File

@@ -1,8 +1,12 @@
// Package commandkit provides the core instance-owned CLI dispatcher, typed
// command declarations, application-owned command and flag aliases, input
// bindings, invocation-scoped reporting, and outcomes with separate operation
// causes and presentation observations. New and App.Register accept canonical
// Command declarations and RoutingRule declarations together. Optional
// integration modules provide ConfigKit and PromptKit-specific commands;
// importing those modules does not install their commands.
// Package commandkit helps Go applications build consistent command-line
// interfaces with typed flags and arguments, help, and shared output formatting.
// Define commands with NewCommand and install them with New or App.Register.
// Commands and command or flag aliases can be installed together.
//
// App.Execute runs a command and returns an Outcome; the application decides
// when to exit. Handlers use Invocation.Reporter for output and messages.
// Invocation features can add application-wide flags, decorate the invocation
// context after CheckInput succeeds, and produce diagnostic reports at finalization.
// Optional ckconfig and ckprompt modules add inspection and testing commands;
// applications install those commands explicitly.
package commandkit

View File

@@ -3,9 +3,11 @@
## 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.
The structured-report formatting extension is implemented; its adoption record
is preserved in [Git history](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/2f43f78f76439f5d11ef313cd379bec036543504/docs/roadmap/promptkit-v0.20.0.md#shared-core-report-output-prerequisite).
The future-tense implementation and roadmap references in the decision and
consequences below are historical. Current contracts are owned by the
[reporting GoDoc](../../report.go) and [CLI reference](../cli.md#reporting).
## Date

File diff suppressed because it is too large Load Diff

View File

@@ -1,50 +1,75 @@
# Consumer guide
CommandKit is distributed as three Go modules. Start with the core and add an
integration module only when the application uses that library. Core and
compatible integration command factories return canonical `commandkit.Command` values.
Applications may install those alongside application-owned `RoutingRule`
declarations through `commandkit.New` or `App.Register`; routing rules are
installed at the application root, not as group children.
Start with core to build commands with typed inputs and shared output
formatting. Add an integration when your application uses ConfigKit or
PromptKit. The [core command example](#core-commands) below shows the basic
API; the [maintained examples](../../README.md#examples) show complete
applications.
## Module selection
| Import | Use when |
| --- | --- |
| `go.maximumdirect.net/commandkit` | The application needs typed command declarations and common CLI behavior. |
| `go.maximumdirect.net/ckconfig` | The application wants ConfigKit-backed configuration scopes and reports. |
| `go.maximumdirect.net/ckprompt` | The application wants PromptKit engine configuration/comparison, five catalogs, named inspection, requirements discovery, request validation, or native smoke testing. |
| `go.maximumdirect.net/commandkit` | You need commands, typed inputs, help, and common output handling. |
| `go.maximumdirect.net/ckconfig` | You want operators to view, validate, explain, and compare ConfigKit configuration. |
| `go.maximumdirect.net/ckprompt` | You want operators to inspect PromptKit resources, check and preview requests, or run smoke tests. |
The published matched releases are core v0.3.0, ckconfig v0.2.0, and ckprompt v0.2.0.
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.
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`.
ckconfig v0.11.0 and ckprompt v0.11.0 select ConfigKit v1.4.0.
ckprompt v0.11.0 selects PromptKit v0.24.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.
| Selection | Core | ckconfig | ckprompt | Upstream libraries and status |
| --- | --- | --- | --- | --- |
| Published core | v0.8.0 | — | — | Usable independently. |
| ConfigKit integration | v0.8.0 | v0.11.0 | — | ConfigKit v1.4.0. |
| PromptKit integration | v0.7.0 | v0.10.0 | v0.11.0 | ConfigKit v1.4.0 and PromptKit v0.24.0. |
| Earlier matched integration set | v0.3.0 | v0.2.0 | v0.2.0 | ConfigKit v0.8.0 and PromptKit v0.16.0, using their earlier import paths. |
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
declarations to core. The [maintained examples](../../README.md#examples) show
core-only, ConfigKit-only, and composed applications.
For applications moving from ckprompt v0.8.0, the
[v0.9.0 upgrade notes](../../integrations/ckprompt/docs/releases/v0.9.0.md#compatibility-and-upgrade)
cover migration of positional literals for affected native PromptKit structs.
Install the published core with:
```sh
go get go.maximumdirect.net/commandkit@v0.8.0
```
Select either integration with `go get go.maximumdirect.net/ckconfig@v0.11.0`
or `go get go.maximumdirect.net/ckprompt@v0.11.0`. ckconfig v0.11.0 selects
core v0.8.0. ckprompt v0.11.0 selects core v0.7.0 and ckconfig v0.10.0, including native subtree
scopes and path readers. These releases build independently.
Published ckconfig v0.3.0 also uses ConfigKit v1.1.0 and does not compose with
ckprompt v0.2.0's earlier ConfigKit dependency.
ConfigKit v1.2.0 adds fields to `Input` and `LayeredOptions`, so application
loaders should use keyed struct literals when constructing them. ConfigKit's
release notes describe
main-relative imports and overlay contexts. [ConfigKit v1.2.0 upgrade guidance](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.2.0/docs/releases/v1.2.0.md#upgrade-notes).
The current ckprompt checkout selects PromptKit v0.25.0, published core v0.8.0,
and published ckconfig v0.11.0; it builds independently with the workspace disabled.
Complete documents put
settings under `promptkit`; wrapperless fragments use `SettingsInput`, and
collection fragments use `CollectionInput`. Consult the [upstream migration
guide](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/consumers/configuration-migration.md)
and [format reference](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/formats.md)
for the exact migration and schema rules.
Importing a module does not install its commands. Pass commands to
`commandkit.New` or `App.Register` explicitly. ckprompt depends on ckconfig's
public APIs, but you can install its `promptkit` commands without installing
the `config` family.
## Go compatibility
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
All three modules in the current checkout declare a consumer minimum of
Go 1.27.0. Core v0.7.0 raises its minimum from v0.6.0's Go 1.26.0. The root module
selects ReleaseKit v0.10.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
even though production packages do not import ReleaseKit. ReleaseKit v0.10.0
requires Go 1.27.0 and raises core's consumer minimum from Go 1.26.0. The
[release policy](../policy/release.md#consumer-minimum-and-release-toolchain)
defines the support assumption. Maintainers use Go 1.27.0 for validation and
defines the support assumption. Maintainers use Go 1.27.4 for validation and
publication; see the [release procedure](../release.md#release-toolchain).
## Core commands
@@ -57,7 +82,6 @@ default from an explicitly supplied empty, false, or zero value.
package example
import (
"fmt"
"strconv"
commandkit "go.maximumdirect.net/commandkit"
@@ -81,8 +105,12 @@ func Greeting() commandkit.Command {
),
},
Run: func(invocation commandkit.Invocation, input GreetInput) commandkit.Outcome {
if _, err := fmt.Fprintln(invocation.Reporter().Output(), input.Count.Value); err != nil {
return commandkit.Failure("Could not write the greeting.").WithCause(err)
greetings := []string{}
for i := 0; i < input.Count.Value; i++ {
greetings = append(greetings, "Hello!")
}
if err := invocation.Reporter().Report(commandkit.Report{Value: greetings}); err != nil {
return commandkit.Failure("Could not write the greetings.").WithCause(err)
}
return commandkit.Success()
},
@@ -90,6 +118,10 @@ func Greeting() commandkit.Command {
}
```
Install `Greeting()` with `commandkit.New(identity, Greeting())`. By default,
`greet` prints `Hello!`; `greet --count=2` prints it twice. Add `--format
json` to receive a JSON list. A count of zero produces an empty list.
The application supplies `context.Context`, argv without the executable name,
and output streams to `App.Execute`; it decides how the returned status maps to
process exit. `New` installs generated help/version and caller declarations as
@@ -134,13 +166,42 @@ installation alongside aliases and integration commands.
## Invocation reporting
`Invocation.Reporter()` supplies the reporter for the current handler. Use
`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.
Use `Invocation.Reporter().Report` to print a value in the selected output
format. Pass ordinary Go values and, optionally, a `text/template` for text
output. Use `Warn`, `Info`, `Progress`, and `Debug` for categorized messages.
Queue a summary with `AtEnd().Info` when it belongs after the handler returns.
Deferred submissions are accepted until finalization begins; later submissions
return `ErrReporterClosed`. The [CLI reference](../cli.md#reporting) owns flag
grammar, visibility, prefixes, and status behavior.
An application can attach a boolean input to the shared `--debug` option and
inspect the reporting selection separately. For example:
```go
type input struct { debug commandkit.Supplied[bool] }
command := commandkit.NewCommand(commandkit.CommandSpec[input]{
Name: "run",
Flags: []commandkit.Flag[input]{
commandkit.BoolFlag(commandkit.FlagMeta{Name: "debug", Short: "d"}, false,
func(in *input, value commandkit.Supplied[bool]) { in.debug = value }),
},
Run: func(inv commandkit.Invocation, in input) commandkit.Outcome {
captureArtifacts := in.debug.Value
quiet := inv.ReportingMode() == commandkit.ReportingModeQuiet
_, _ = captureArtifacts, quiet // Apply application policy here.
return commandkit.Success()
},
})
_ = command
```
With `run --debug --quiet`, the input is true and explicitly supplied, while
the selected reporting mode is quiet. Application defaults and requiredness
affect input, not mode selection; explicit false counts as supplied. Captured
bindings retain the usual selection and application behavior. Applications own
any artifact creation and other effects. The mode reports selection rather than
successful delivery; see [Invocation.ReportingMode](../../identity.go).
Reports use JSON serialization to establish the common value representation
for YAML and JSON. A text template receives the original value; without one,
@@ -157,22 +218,29 @@ write to their supplied writer only while the callback runs; they must not
submit another message or start another rendering operation through the same
reporter.
For example, a handler can report a count as a small mapping:
```go
Run: func(invocation commandkit.Invocation, input GreetInput) commandkit.Outcome {
if _, err := fmt.Fprintln(invocation.Reporter().Output(), input.Count.Value); err != nil {
return commandkit.Failure("Could not write the greeting.").WithCause(err)
}
return commandkit.Success()
if err := invocation.Reporter().Report(commandkit.Report{
Value: map[string]int{"count": input.Count.Value},
}); err != nil {
return commandkit.Failure("Could not write the count.").WithCause(err)
}
return commandkit.Success()
```
This uses YAML automatically and supports `--format json` without a separate
encoder. Use `Output()` or `RenderOutput()` instead when you deliberately need
raw output; `--format` does not reformat those bytes.
After `App.Execute`, inspect the returned `Outcome`. Its `Cause` retains the
operation error; `Presentation.Output` and `Presentation.Diagnostics` report
delivery state and the first rendering or write errors for their destinations.
CommandKit does not retain a message transcript. Reporter operations for one
invocation are safe concurrently, but concurrent submission order is not
specified. The caller owns the writers passed to `Execute`; CommandKit does not
close them.
Joined operation errors support `errors.Is` and `errors.As` where the
underlying errors do. CommandKit does not retain a message transcript.
Reporter operations for one invocation are safe concurrently, but concurrent
submission order is not specified. The caller owns the writers passed to
`Execute`; CommandKit does not close them.
## Application-owned aliases
@@ -233,26 +301,49 @@ values.
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. `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
acquisition state or a custom comparison provider. A declared `Diff`
capability uses `Scope.Compare`; `ckconfig.FromConfigKit` and `AppCommand`
provide the 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
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 application owns the state type and what it caches.
`ckconfig.FromConfigKitSubtree(name, summary, path, load)` adapts the same typed
loader to a focused native inspection. The loader validates the whole result;
its sources and findings retain whole-load context. Listing uses the focused
native paths, while explicit paths and comparison retain native semantics. The
[composed example](../../integrations/ckprompt/examples/composed/main.go) uses
this adapter for `storage` and passes the same application result to
`promptkit.NewFromConfig`. The application composes `promptkit.Configure` and
selects `BundledOpenRouterUnderlay` before loading when it needs that catalog.
`ckconfig.FromConfigKit` adapts a typed ConfigKit loader without calling it
during construction. The bundled comparison adapters call the loader for the
left side before the right, retain left diagnostics if right loading fails,
and collect diagnostics from both loads before native comparison. Custom
comparison callbacks own their loading and diagnostics; loader calls need not
reread sources if the application caches them.
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. `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
`View.Paths` supplies native discovery candidates; when nil, `View.Metadata`
supplies them for existing custom providers. Metadata remains required for
filtering and describing candidates. `View.Findings` carries diagnostic records
when available. `Findings.Messages` contains presentations associated
with those records, while `Acquired.Diagnostics` carries independent messages.
Custom explanation providers implement `Explain`; CommandKit renders the
acquired evidence. See `EffectiveWriter` and `ExplanationReader` in the
[ckconfig GoDoc](../../integrations/ckconfig/contracts.go) for the provider boundary.
`ckconfig.AdaptDiagnostics` captures native diagnostic presentation evidence
for applications providing their own ConfigKit-backed CLI integration.
[`ckconfig.ClassifyConfigurationError`](../../integrations/ckconfig/errors.go)
provides the standard CLI outcome classification for ConfigKit errors; callers
construct their own outcomes, explanations, and causes. The [CLI reference](../cli.md#configuration-failure-classification)
describes the standard commands' status behavior.
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
@@ -264,8 +355,10 @@ parses CLI records but cannot add them to an already-loaded result. The
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.
Its override feature is disabled by default. Applications may enable it only
when their own loader applies the supplied overrides.
### Install resource commands and optional checks
`ckprompt.FromEngine(loadEngine)` supplies nine callbacks: prompt, profile,
backend, namespace, and collection catalogs; named prompt, profile, and backend
@@ -301,11 +394,37 @@ suite := ckprompt.WithRequestValidation(
validationCommand := ckprompt.Command(suite)
```
### Automatic usage reporting
Installing a nonempty ckprompt family with either `Command` or `Declarations`
adds `--show-tokens` to application commands as well as PromptKit commands.
An empty suite adds nothing. The flag defaults to false; explicit false and
repeated selections use the ordinary Boolean rules. Applications pass
`Invocation.Context` into PromptKit and wait for their own work before returning.
The observer starts after command input construction and successful `CheckInput`,
before `Run`; validation or acquisition inside `Run` is included.
`CommandSpec.CheckInput` may return `commandkit.ErrHelpRequested` for a
help-only preflight result; core renders help without starting features or
requiring execution-only invocation flags. ckconfig uses this for bare
`config explain`. Help, version,
completion, parse errors, and rejected command inputs do not start observation.
The requested summary is text on diagnostics after deferred messages and before
any failure explanation, independently of the main report's `--format`. Quiet
suppresses delivery. Counts and cost preserve unknown and incomplete states,
known zero, cost source, and terminal coverage; the cache ratio is shown only when
available. Smoke tests report their own usage separately. An empty ordinary
summary is not a measurement of smoke-test usage. See the [operator reference](../cli.md#promptkit-usage-reporting).
### Request builders and loading
If the loader is nil, the returned suite retains a wiring issue for installation
to report, even if capabilities are narrowed later. A builder runs before the
engine loader and receives the seed request, selection, typed input, shared
state, and invocation context. It returns the
concrete request; the adapter does not merge seed fields back afterward. The
concrete request; the adapter does not merge seed fields back afterward. For
validation replacements use `*promptkit.OutputContractInput`: a nil repair
budget remains omitted and a pointer to zero explicitly disables repair. The
loader receives the original selection. Builders should start from the seed,
preserve operator values and bindings, and apply defaults only when a map key is
absent, so explicitly supplied empty values stay meaningful. Applications that
@@ -338,6 +457,12 @@ and state. `FromEngine` uses PromptKit's public listing and inspection methods,
including `Engine.InspectRequirements`; validation must be opted into separately
and uses `Engine.ValidateRequest`.
Applications own engine construction and may build complete native requests in
callbacks. Preparation and validation use the supplied context; execution owns
prepared notifications and operation timeouts. See the [PromptKit consumer
guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/docs/consumers/pkg-promptkit.md)
for conversation and execution capabilities.
`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
@@ -350,6 +475,8 @@ 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.
### Enable namespace flags
`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.
@@ -372,7 +499,7 @@ complete return value is authoritative. The [CLI reference](../cli.md#promptkit-
and reports.
The [composed example](../../integrations/ckprompt/examples/composed/README.md)
combines app and PromptKit config scopes, comparison and catalogs, named and
combines app, storage, and PromptKit config scopes, comparison and catalogs, named and
requirements inspection, request validation, smoke testing, and an
application-owned `session restore` command.
@@ -396,7 +523,7 @@ 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).
[namespace API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/namespaces.go).
## Outcomes and ownership
@@ -410,8 +537,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 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).
[ConfigKit v1.4.0 source records](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3/records.go),
[PromptKit engine methods](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/engine.go),
[configuration inspection](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/configuration_inspection.go),
[smoke diagnostics](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/smoke_diagnostics.go),
and [PromptKit v0.25.0 consumer guidance](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/docs/consumers/pkg-promptkit.md).

View File

@@ -62,6 +62,7 @@ capability proposals in [future work](roadmap/future.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 documentation refresh | [Retired refresh record](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/5c960532552037d38119941389e558f78bf73aad/docs/roadmap/documentation-refresh.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 |
| Release tooling | [Maintainer release procedure](release.md) |
| Performance maintenance | [Internal overview](internal/overview.md), existing benchmarks, and [possible further efficiency work](roadmap/future.md#possible-further-efficiency-work) |
@@ -72,7 +73,10 @@ 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 [PromptKit v0.18.0 adoption and implementation](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/540e2359d66d604a563df0be1c9fc961588f5b9c/docs/roadmap),
including [shared debug binding and reporting-mode implementation](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/56e3b013f9f83c9c9494f11602e802ce5ed8814e/docs/roadmap),
[audit remediation and its declaration-path follow-up](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/aac0e11ae67c78a35745ed9a25688aa51c15e793/docs/roadmap),
[shared reporting and PromptKit v0.20.0 implementation](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/2f43f78f76439f5d11ef313cd379bec036543504/docs/roadmap),
[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).
@@ -80,6 +84,9 @@ These records are not assignments to restart completed work. The
[future work record](roadmap/future.md) preserves unfinished work and unselected
proposals separately from current contracts.
The [ckprompt release errata](../integrations/ckprompt/docs/releases/errata.md)
corrects navigation in a historical release note.
## Documentation validation
For current prose work, inspect relevant diffs, check local links and fragment
@@ -101,13 +108,22 @@ Sibling-checkout references in retired planning records are historical review
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
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:
The root module does not traverse nested modules. With Go 1.27.4 on `PATH`,
create the local workspace from the repository root if `go.work` is absent:
```sh
go work init . ./integrations/ckconfig ./integrations/ckprompt
```
If a workspace already exists, ensure it includes these three modules. Preserve
the ignored `go.work` and `go.work.sum`; do not commit them. Use
`GOWORK=off GOTOOLCHAIN=local` for dependency preparation
and independent module suites. Both integrations select released core v0.8.0;
ckprompt selects released ckconfig v0.11.0. All three modules build independently
against their published dependencies. Run independent suites with
`GOWORK=off GOTOOLCHAIN=local go test ./...` from the module directory.
The aligned workspace exercises local sources together. From the root,
all three modules can also run:
```sh
GOTOOLCHAIN=local go test ./...

View File

@@ -38,9 +38,21 @@ collected parser events through that selection. The selected mode therefore
applies to command execution, help, and version; routing and parsing failures
remain visible in every mode.
An effective flag view combines a shared application debug binding with the
core declaration for parsing, help, and completion, while preserving the
application binding's position. The same occurrence stream selects reporting
mode independently of the prepared application value. The invocation's mode
accessor reads the reporter's selection under its existing state mutex.
Captured invocation features contribute application-wide flags through the same
parser and alias views. The installer deduplicates handles and validates the
prospective registry atomically. Each invocation prepares feature values, starts
features after successful command input checking, and retains returned report
producers only until finalization. Generated builtins do not start features.
The reporter owns invocation-scoped visibility, message formatting, managed
report rendering, delivery observations, and finalization. It presents queued
messages after the handler returns, then a failed outcome's explanation, and
messages after the handler returns, then feature reports, then a failed outcome's explanation, and
closes its handles before `Execute` returns. It records rendering and write
errors separately for result and diagnostic destinations; the returned
`Outcome.Presentation` exposes those observations independently from the
@@ -76,6 +88,8 @@ rendering. A session owns the mutable backend tree for one invocation; parsing
and presentation reuse that session. The adapter returns raw values and neutral
syntax failures to core. It does not own the registry, typed input preparation,
integration declarations, provider acquisition, or native report rendering.
Parser options carry flag-alias selection; invocation context and streams stay
with core, while backend output destinations discard and help uses a local buffer.
Cobra and pflag imports remain inside this package.
## Optional modules
@@ -83,7 +97,9 @@ Cobra and pflag imports remain inside this package.
`integrations/ckconfig` owns ConfigKit adaptation, scope capture, the standard
`config` command family, and native validate/show/sources/explain/diff behavior.
It depends on the public core facade and ConfigKit; it does not depend on
PromptKit. Each selected scope or comparison side receives an independently
PromptKit. Whole-result and subtree scopes share loader and diagnostic adaptation;
subtree scopes delegate focused path enumeration and comparison to native
ConfigKit inspection. Each selected scope or comparison side receives an independently
initialized input, while one suite-owned state value is shared by an invocation's
acquisitions or comparison callback.

View File

@@ -2,18 +2,18 @@
## Cobra
Selected module: `github.com/spf13/cobra` at `v1.10.1`.
Selected module: `github.com/spf13/cobra` at `v1.10.2`.
SPDX-License-Identifier: Apache-2.0
License and notices: [Apache 2.0](licenses/Apache-2.0.txt) |
[LICENSE.txt](https://github.com/spf13/cobra/blob/7da941c3547e93b8c9f70bbd3befca79c6335388/LICENSE.txt).
[LICENSE.txt](https://github.com/spf13/cobra/blob/88b30ab89da2d0d0abb153818746c5a2d30eccec/LICENSE.txt).
[Source](https://github.com/spf13/cobra/tree/7da941c3547e93b8c9f70bbd3befca79c6335388).
[Source](https://github.com/spf13/cobra/tree/88b30ab89da2d0d0abb153818746c5a2d30eccec).
## pflag
Selected module: `github.com/spf13/pflag` at `v1.0.9`.
Selected module: `github.com/spf13/pflag` at `v1.1.0`.
Copyright (c) 2012 Alex Ogier. All rights reserved.
@@ -22,13 +22,13 @@ Copyright (c) 2012 The Go Authors. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) |
[LICENSE](https://github.com/spf13/pflag/blob/10438578954bba2527fe5cae3684d4532b064bbe/LICENSE).
[LICENSE](https://github.com/spf13/pflag/blob/f8a990678a6d44385313e9b19e40737f889f9b14/LICENSE).
[Source](https://github.com/spf13/pflag/tree/10438578954bba2527fe5cae3684d4532b064bbe).
[Source](https://github.com/spf13/pflag/tree/f8a990678a6d44385313e9b19e40737f889f9b14).
## go-yaml v4
Selected module: `go.yaml.in/yaml/v4` at `v4.0.0-rc.6`.
Selected module: `go.yaml.in/yaml/v4` at `v4.0.0`.
Copyright 2006-2010 Kirill Simonov
@@ -38,14 +38,14 @@ Copyright 2025 The go-yaml Project Contributors
License and notices: [Apache 2.0](licenses/Apache-2.0.txt) |
[MIT](licenses/MIT.txt) |
[LICENSE](https://github.com/yaml/go-yaml/blob/1c17b9cee72bf81ae73a8be50fbd7dd3a9985125/LICENSE) |
[NOTICE](https://github.com/yaml/go-yaml/blob/1c17b9cee72bf81ae73a8be50fbd7dd3a9985125/NOTICE).
[LICENSE](https://github.com/yaml/go-yaml/blob/f2f9563503f11b7a60da0c532175dcc693ce8d5a/LICENSE) |
[NOTICE](https://github.com/yaml/go-yaml/blob/f2f9563503f11b7a60da0c532175dcc693ce8d5a/NOTICE).
[Source](https://github.com/yaml/go-yaml/tree/1c17b9cee72bf81ae73a8be50fbd7dd3a9985125).
[Source](https://github.com/yaml/go-yaml/tree/f2f9563503f11b7a60da0c532175dcc693ce8d5a).
## go-yaml v3
Selected module: `gopkg.in/yaml.v3` at `v3.0.1` (transitive dependency).
Selected module: `go.yaml.in/yaml/v3` at `v3.0.4` (transitive dependency).
Copyright (c) 2006-2010 Kirill Simonov
@@ -55,10 +55,10 @@ Copyright 2011-2016 Canonical Ltd.
License and notices: [MIT](licenses/MIT.txt) |
[Apache 2.0](licenses/Apache-2.0.txt) |
[LICENSE](https://github.com/go-yaml/yaml/blob/f6f7691b1fdeb513f56608cd2c32c51f8194bf51/LICENSE) |
[NOTICE](https://github.com/go-yaml/yaml/blob/f6f7691b1fdeb513f56608cd2c32c51f8194bf51/NOTICE).
[LICENSE](https://github.com/yaml/go-yaml/blob/c3552c15f996075a7634df5159d9161c67bf3d76/LICENSE) |
[NOTICE](https://github.com/yaml/go-yaml/blob/c3552c15f996075a7634df5159d9161c67bf3d76/NOTICE).
[Source](https://github.com/go-yaml/yaml/tree/f6f7691b1fdeb513f56608cd2c32c51f8194bf51).
[Source](https://github.com/yaml/go-yaml/tree/c3552c15f996075a7634df5159d9161c67bf3d76).
## go-md2man
@@ -144,52 +144,54 @@ License and notices: [CC BY-SA 4.0](licenses/CC-BY-SA-4.0.txt) |
## ReleaseKit
Selected module: `go.maximumdirect.net/releasekit` at `v0.9.0` (selected Go tool; not a runtime import).
Selected module: `go.maximumdirect.net/releasekit` at `v0.10.0` (selected Go tool; 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://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4/LICENSE).
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243/LICENSE).
[Source](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4).
[Source](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243).
## Goldmark
Selected module: `github.com/yuin/goldmark/v2` at `v2.1.6` (ReleaseKit tool dependency).
Selected module: `github.com/yuin/goldmark/v2` at `v2.1.16` (ReleaseKit tool dependency).
Copyright (c) 2019 Yusuke Inuzuka
SPDX-License-Identifier: MIT
License and notices: [MIT](licenses/MIT.txt) |
[LICENSE](https://github.com/yuin/goldmark/blob/a8d4ee5a0bd7d5493fdd1e339b4e75df92f8684c/LICENSE).
[LICENSE](https://github.com/yuin/goldmark/blob/c3f939122ba4dd6f80e05043ad195b82e77fcb41/LICENSE).
[Source](https://github.com/yuin/goldmark/tree/a8d4ee5a0bd7d5493fdd1e339b4e75df92f8684c).
[Source](https://github.com/yuin/goldmark/tree/c3f939122ba4dd6f80e05043ad195b82e77fcb41).
## Go modules
Selected module: `golang.org/x/mod` at `v0.40.0` (ReleaseKit tool dependency).
Selected module: `golang.org/x/mod` at `v0.43.0` (ReleaseKit tool dependency).
Copyright 2009 The Go Authors.
SPDX-License-Identifier: BSD-3-Clause
License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) |
[LICENSE](https://go.googlesource.com/mod/+/d3398d06de5fa5c71083d3d1c26f2cda73508e0f/LICENSE).
[LICENSE](https://go.googlesource.com/mod/+/d4f320b9266480df5ed3d791e0c68e64c58c5dde/LICENSE) |
[PATENTS](https://go.googlesource.com/mod/+/d4f320b9266480df5ed3d791e0c68e64c58c5dde/PATENTS).
[Source](https://go.googlesource.com/mod/+/d3398d06de5fa5c71083d3d1c26f2cda73508e0f).
[Source](https://go.googlesource.com/mod/+/d4f320b9266480df5ed3d791e0c68e64c58c5dde).
## Go tools
Selected module: `golang.org/x/tools` at `v0.49.0` (ReleaseKit tool graph dependency).
Selected module: `golang.org/x/tools` at `v0.52.0` (ReleaseKit tool graph dependency).
Copyright (c) 2009 The Go Authors. All rights reserved.
Copyright 2009 The Go Authors.
SPDX-License-Identifier: BSD-3-Clause
License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) |
[LICENSE](https://go.googlesource.com/tools/+/18332fec72972efbb8ab9881984fec2d8cfc2b58/LICENSE).
[LICENSE](https://go.googlesource.com/tools/+/16517d951552611e7bd358c48ee1051fd0e57b0c/LICENSE) |
[PATENTS](https://go.googlesource.com/tools/+/16517d951552611e7bd358c48ee1051fd0e57b0c/PATENTS).
[Source](https://go.googlesource.com/tools/+/18332fec72972efbb8ab9881984fec2d8cfc2b58).
[Source](https://go.googlesource.com/tools/+/16517d951552611e7bd358c48ee1051fd0e57b0c).

View File

@@ -161,8 +161,8 @@ 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 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).
ownership model. The [CLI reference](../cli.md#reporting) describes the
implemented structured-report behavior.
For that shared report handoff, core owns format selection, serialization,
template execution, and delivery. Applications and integrations select logical
@@ -187,7 +187,7 @@ 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 [CLI reporting contract](../cli.md#presentation-failures).
and cause, applying the [CLI reporting contract](../cli.md#output-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

View File

@@ -2,7 +2,7 @@
**Base Policy Version:** 1.6
**Last Updated**: 2026-10-11
**Last Updated**: 2026-11-08
**Upstream Source:** [release.md](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/docs/policy/release.md)
@@ -25,7 +25,7 @@ additional release requirements.
CommandKit independently versions three source-only Go modules: the root core,
`integrations/ckconfig`, and `integrations/ckprompt`. Standard CLI behavior is
exposed by consuming applications; CommandKit does not declare binary
deliverables or a cross-platform build matrix. ReleaseKit v0.9.0 is selected as
deliverables or a cross-platform build matrix. ReleaseKit v0.10.0 is selected as
the maintainer publication tool. Maintainers may separately deliver page-only
Gitea releases from tagged source; delivery has its own outcome and URL. The
[release procedure](../release.md) owns the selected-module workflow, release
@@ -96,6 +96,22 @@ Additional compatibility promises and deliberate exceptions belong in the
adopted policy or canonical contract documentation. Release notes explain
changes; they do not redefine current compatibility contracts.
### CommandKit downstream dependency alignment
Each new core or integration release requires dependency updates and new releases
of all downstream CommandKit-owned integration modules, following direct and
transitive dependencies. Each affected integration advances at least its minor
version to incorporate the dependency updates, even when the initiating release
is a patch. Use a major release where the compatibility rules above require it.
Versions remain independent and need not match across modules.
A module with no downstream CommandKit integrations may release independently;
its release does not require new versions of its dependencies. This policy does
not require releases of external consuming applications. The
[runbook](../release.md#scope-and-release-order) owns dependency-order sequencing.
Downstream releases are required follow-up work, not additional completion gates
for an already published source release.
## Consumer Minimum And Release Toolchain
Distinguish the minimum toolchain supported for consumers from the toolchain

View File

@@ -9,11 +9,28 @@ Gitea release page; there are no binaries,
checksums, or other delivery assets. CI, module proxy availability, and consumer
installation are not completion gates.
Publish in dependency order: core, then `ckconfig`, then `ckprompt`. The
integration modules require the preceding CommandKit releases, so prepare and
publish each module only after its CommandKit dependencies are available. A root
release runs only the root module's default suite; it need not run suites for
independently released integrations.
Plan the initiating release and all downstream integration releases required by
the [dependency-alignment policy](policy/release.md#commandkit-downstream-dependency-alignment).
That policy sets the minimum version bump for affected integrations; select
each module's version independently according to its compatibility impact.
| Initiating release | Required downstream releases, in order |
| --- | --- |
| Core | `ckconfig`, then `ckprompt` |
| `ckconfig` | `ckprompt` |
| `ckprompt` | None with the current dependency graph |
As integrations are added, follow their actual dependencies to include every
affected downstream integration. Publish dependencies before their consumers.
Prepare each integration after its updated CommandKit dependencies are published,
incorporating all of those versions in one candidate. For a core update, release
`ckprompt` once after both core and `ckconfig`; it does not need separate releases
for each dependency bump. Unaffected dependencies do not need new releases.
Track any remaining downstream releases as pending coordination work. Each
successful source-tag push still completes that module's release; a downstream
failure does not undo it or authorize replacing its tag. A root release runs
only the root module's default suite; each downstream release runs its own suite.
Use branch `main`, remote `origin`, and expected effective push endpoint
`ssh://git@forge.maximumdirect.net:22222/base-layer/commandkit.git`. The selected
@@ -22,34 +39,34 @@ module profile enforces the endpoint. The maintainer needs the selected
This procedure follows the [release policy](policy/release.md); release-note
footers follow the [OSS discoverability policy](policy/oss.md#discoverability).
ReleaseKit v0.9.0 (`go.maximumdirect.net/releasekit`) owns candidate validation,
ReleaseKit v0.10.0 (`go.maximumdirect.net/releasekit`) owns candidate validation,
publication guards, tag creation, tag publication, and outcome reporting.
Its pinned public contracts are the
[CLI reference](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4/docs/cli.md),
[profile reference](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4/docs/config.md),
the [publication guide](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4/docs/consumers/publish.md),
and the [delivery guide](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4/docs/consumers/delivery.md).
[CLI reference](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243/docs/cli.md),
[profile reference](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243/docs/config.md),
the [publication guide](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243/docs/consumers/publish.md),
and the [delivery guide](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243/docs/consumers/delivery.md).
The repository selects one default module suite per invocation. The launcher
uses the root module’s registered tool with native host settings and read-only
module metadata.
## Release toolchain
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
The selected release toolchain is **Go 1.27.4**. All three modules declare a
consumer minimum of **Go 1.27.0**. Maintainers use Go 1.27.4 for dependency
preparation, candidate validation, and ReleaseKit
execution. The
[consumer guide](consumers/guide.md#go-compatibility) and
[release policy](policy/release.md#consumer-minimum-and-release-toolchain)
describe these selections.
Select Go 1.27.0 on `PATH`; the launcher uses `GOTOOLCHAIN=local`. If needed,
Select Go 1.27.4 on `PATH`; the launcher uses `GOTOOLCHAIN=local`. If needed,
install it with the standard Go tools:
```sh
GOWORK=off GOTOOLCHAIN=local go install golang.org/dl/go1.27.0@latest
go1.27.0 download
export PATH="$(go1.27.0 env GOROOT)/bin:$PATH"
GOWORK=off GOTOOLCHAIN=local go install golang.org/dl/go1.27.4@latest
go1.27.4 download
export PATH="$(go1.27.4 env GOROOT)/bin:$PATH"
hash -r
GOWORK=off GOTOOLCHAIN=local go version
```
@@ -79,7 +96,7 @@ integration directory. Future tag URLs need not resolve before publication.
All three release profiles explicitly select the repository-root `COPYRIGHT`,
`LICENSE`, and `docs/oss/attribution.md` through `validation.shared_files`.
ReleaseKit requires these committed files to exist in the candidate. The list
does not expand Go validation scope; see the pinned [profile reference](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4/docs/config.md).
does not expand Go validation scope; see the pinned [profile reference](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243/docs/config.md).
Each integration also distributes its own `COPYRIGHT`, `LICENSE`, and
`docs/oss/attribution.md`. These module-local materials are separate from the
@@ -98,12 +115,38 @@ standard offline suite and ReleaseKit’s candidate/note and publication guards.
## Prepare and publish one candidate
Prepare dependencies in the selected module before the candidate is finalized.
Do this after the preceding CommandKit module has been published and before the
selected candidate suite is run. For `core`, run the command at the repository
root; for integrations, run it from that module directory. Commit any resulting
`go.mod` or `go.sum` changes with the release candidate. The sum files must
reflect dependencies actually downloaded for that module; do not fabricate
future sums.
Do this after any CommandKit dependency releases required by the coordinated
update have been published and before the selected candidate suite is run.
For `core`, run the command at the repository root; for integrations, run it
from that module directory.
Before downloading dependencies, update each integration to the newly published
CommandKit versions. `go mod download` downloads the versions already selected;
it does not upgrade requirements. Replace the version placeholders below with
the actual published versions, which may differ between modules. When a
dependency is not being released in this update, use its current selected
release; a `ckconfig`-initiated update does not require a new core release:
```sh
# After publishing core, prepare ckconfig from its module directory.
GOWORK=off GOTOOLCHAIN=local go get go.maximumdirect.net/commandkit@vCORE_VERSION
# After publishing ckconfig, prepare ckprompt from its module directory.
GOWORK=off GOTOOLCHAIN=local go get \
go.maximumdirect.net/commandkit@vCORE_VERSION \
go.maximumdirect.net/ckconfig@vCKCONFIG_VERSION
```
Run only the command for the integration being prepared. ckprompt needs a
ckconfig release containing `AdaptDiagnostics`; v0.5.0 contains it, while v0.4.0
does not. Validate the integration with the workspace disabled against its
updated requirements, using the selected module's release validation below.
An aligned workspace can hide an outdated dependency.
Review and commit the resulting `go.mod` and `go.sum` changes with the release
candidate, and make its release note agree with the selected versions. The sum
files must reflect dependencies actually downloaded for that module; do not
fabricate future sums.
Then commit the selected module's release note and all intended candidate
changes on `main`, and publish the candidate commit to `origin`. Set one
@@ -157,9 +200,9 @@ Reconciliation observes the recorded endpoint, full tag, and tag object without
rerunning candidate validation or changing tags. It distinguishes confirmed
publication, current absence, conflict, and an unresolved observation. Current
absence does not prove that a version was never published. The pinned
[CLI reference](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4/docs/cli.md#recover-a-saved-publication-attempt-or-discover-local-attempts)
[CLI reference](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243/docs/cli.md#recover-a-saved-publication-attempt-or-discover-local-attempts)
owns recovery statuses and structured output; the
[publication guide](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4/docs/consumers/publish.md#retain-and-reconcile-publication-evidence)
[publication guide](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243/docs/consumers/publish.md#retain-and-reconcile-publication-evidence)
describes record storage and recovery entry points.
If no usable record was saved, use the exact endpoint, full tag, and annotated
@@ -189,7 +232,7 @@ worktree and index, then deliver the selected module's page:
The profile derives the full module-specific tag from the version. Delivery
uses the checked-in release note as a page-only body and reports its own outcome
and URL separately from source publication. Retry later from the same original
tagged source. The pinned [delivery guide](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4/docs/consumers/delivery.md)
tagged source. The pinned [delivery guide](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243/docs/consumers/delivery.md)
owns delivery and retry behavior.
A nonblank `RELEASEKIT_GITEA_TOKEN` takes precedence over the repository-relative

43
docs/releases/v0.5.0.md Normal file
View File

@@ -0,0 +1,43 @@
# CommandKit v0.5.0
CommandKit v0.5.0 fixes lost deferred messages and preserves YAML value types
more accurately. It also reduces repeated work when installing commands and
showing alias help, and refreshes documentation and help text.
## Changes
- Deferred messages accepted before finalization are retained for final reporting;
they can no longer be silently lost when a handler finishes. Later submissions return
`ErrReporterClosed`.
- Finished invocations release their direct references to output and diagnostic
writers while keeping delivery results available. Applications still own the
writers.
- `DecodeYAMLReport` preserves numeric-looking strings as strings. YAML report
output also preserves explicitly tagged numbers beyond the YAML resolver's
ordinary numeric range.
- Command installation, alias help, and typed input handling avoid repeated
work. Parsing and completion share flag handling while retaining their
different treatment of errors and unfinished input.
- The reporting example now works when its optional scenario is omitted, and
the interactive completion fixture no longer conflicts with `--format`.
`FlagMeta` documents existing naming and reserved-spelling rules.
- READMEs, CLI instructions, examples, and generated help use clearer language
and explain common tasks before implementation details.
## Compatibility and upgrade
The public core Go API, CLI grammar, and Go 1.26.0 consumer minimum are unchanged.
The maintainer release toolchain remains Go 1.27.0.
Applications using background producers should coordinate deferred submissions
before the handler returns and handle `ErrReporterClosed` once finalization
begins. See the [invocation reporting guide](../consumers/guide.md#invocation-reporting).
Callers supplying YAML with numbers beyond the resolver's ordinary range should
use explicit `!!int` or `!!float` tags when numeric meaning is intended. Untagged
values resolved as strings now retain that type. See
[`DecodeYAMLReport`](../../report_value.go) for the conversion contract.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.5.0/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.5.0/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.5.0/docs/oss/attribution.md)

25
docs/releases/v0.6.0.md Normal file
View File

@@ -0,0 +1,25 @@
# CommandKit v0.6.0
CommandKit v0.6.0 lets applications bind the shared debug option to typed
input and inspect the selected reporting mode during and after an invocation.
## Changes
- A `BoolFlag` named `debug` attaches to the existing reporting option. Its
application default, requiredness, short spelling, and completion hints are
retained; help describes the combined option.
- `Invocation.ReportingMode` returns the resolved visibility selection, which
can differ from the bound debug value when other mode flags are supplied.
## Compatibility and upgrade
Other reporting flag names remain reserved. Applications choosing a required
debug binding require an explicit value; an explicit false satisfies it. A
true application default does not enable debug reporting. See the
[consumer guide](../consumers/guide.md#invocation-reporting) and
[CLI reference](../cli.md#reporting). The core consumer minimum remains Go
1.26.0 and the maintainer release toolchain remains Go 1.27.0.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.6.0/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.6.0/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.6.0/docs/oss/attribution.md)

29
docs/releases/v0.7.0.md Normal file
View File

@@ -0,0 +1,29 @@
# CommandKit v0.7.0
CommandKit v0.7.0 refreshes the CLI, YAML, and maintainer-tool dependencies.
## Dependency updates
- Cobra v1.10.1 → v1.10.2 and pflag v1.0.9 → v1.1.0 update CLI parsing,
help, and diagnostics. Cobra also selects the maintained YAML v3 module path.
- go-yaml v4.0.0 replaces v4.0.0-rc.6 for report decoding and encoding.
- ReleaseKit v0.10.0 updates maintainer tooling and selects Goldmark v2.1.16
and Go Modules v0.43.0.
## Compatibility and upgrade
The core consumer minimum increases from Go 1.26.0 to Go 1.27.0 because the
registered ReleaseKit tool now requires Go 1.27.0. Upgrade the Go toolchain
before selecting this release. Maintainer validation uses Go 1.27.4.
Applications continue to use the existing CommandKit APIs and standard command
grammar. Review scripts that depend on exact backend diagnostic or help text
when adopting the parser updates. The current CLI and reporting contracts are
documented in the [CLI reference](../cli.md), and the
[consumer guide](../consumers/guide.md#module-selection) records module pairing.
Coordinated ckconfig and ckprompt releases follow this core release under the
[dependency-alignment policy](../policy/release.md#commandkit-downstream-dependency-alignment).
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.7.0/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.7.0/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.7.0/docs/oss/attribution.md)

46
docs/releases/v0.8.0.md Normal file
View File

@@ -0,0 +1,46 @@
# CommandKit v0.8.0
CommandKit v0.8.0 adds captured invocation features for application-wide flags,
context decoration, and final diagnostic reports. Optional integrations can
install this behavior through normal command assembly without applications
wrapping `App.Execute` or adding bookkeeping to each handler.
## Invocation features
`NewInvocationFeature` captures an `InvocationFeatureSpec`, and
`WithInvocationFeature` attaches its reusable handle to a command declaration.
Installation validates the capability against the complete registry atomically,
including local flags and aliases in either registration order. Reusing one
handle installs it once per application.
Features start after input construction and successful `CommandSpec.CheckInput`,
before `Run`. Their report producers run after deferred messages and before
terminal failure explanations, including after returned failures or cancellation.
Reports use text on diagnostics independently of the main result's `--format`.
Quiet suppresses delivery while retaining rendering-error handling.
`CommandSpec.CheckInput` may return `ErrHelpRequested` for a help-only preflight
result. Core displays help without starting features or requiring their
execution-only flags. Generated help, version, completion, and input failures
also skip feature startup. Applications continue to own their execution context,
work lifetimes, outcomes, and process exit.
Flag occurrence preparation now partitions input owners once; installation
shares invocation-flag lookup across command contexts. These changes avoid
repeated indexing and duplicated global spelling maps as capabilities grow.
## Compatibility and upgrade
The Go consumer minimum remains 1.27.0; maintainer validation uses Go 1.27.4.
Existing command factory signatures and reporting controls remain available.
New invocation flags participate in ordinary long/short spelling and alias
collision checks; resolve conflicts when installing a capability.
Coordinated ckconfig v0.11.0 and ckprompt v0.12.0 releases follow core under the
[dependency-alignment policy](../policy/release.md#commandkit-downstream-dependency-alignment).
See the [consumer guide](../consumers/guide.md) and [CLI reference](../cli.md)
for current assembly and operator contracts.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.8.0/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.8.0/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.8.0/docs/oss/attribution.md)

View File

@@ -1,76 +1,93 @@
# Future work
Status: pending release and integration work, plus future capability proposals.
Status — pending release coordination, optional verification, and future capability proposals.
No delivery dates are selected here.
## Pending release coordination
[Core v0.8.0](../releases/v0.8.0.md) and
[ckconfig v0.11.0](../../integrations/ckconfig/docs/releases/v0.11.0.md) are published
with hosted release pages. Automatic usage reporting and R1–R4 remediation are
implemented.
[ckprompt v0.12.0](../../integrations/ckprompt/docs/releases/v0.12.0.md) is prepared
with both published CommandKit dependencies. Publish it and deliver its hosted
page under the [release procedure](../release.md#scope-and-release-order).
Publication runs its independent suite against those released dependencies.
## Open proposal
The [selected-format accessor proposal](scriptorium-feature-request.md) remains
optional and unselected; it is not a prerequisite for the completed usage feature
or for the coordinated releases.
## Purpose and authority
Completed roadmaps, implementation plans, and review findings have been retired.
Earlier completed roadmaps, implementation plans, and review findings have been retired.
The completed automatic usage roadmap, implementation plan, and R1–R4 review
records remain available in their
[retirement snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/33f98db4f78f0b45ea89b0618203b1d947a89374/docs/roadmap).
This document preserves unfinished work and unselected ideas under the
[release policy](../policy/release.md#release-documentation-and-preparation).
The completed shared debug binding and reporting-mode implementation is recorded
in its [retirement snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/56e3b013f9f83c9c9494f11602e802ce5ed8814e/docs/roadmap).
The completed [documentation refresh](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/5c960532552037d38119941389e558f78bf73aad/docs/roadmap/documentation-refresh.md) remains available in Git history.
The completed audits, consolidated remediation, implementation plan, and
declaration-path follow-up remain available in the
[audit remediation retirement snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/aac0e11ae67c78a35745ed9a25688aa51c15e793/docs/roadmap).
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 PromptKit v0.20.0 and shared reporting implementation is recorded
in its [retirement snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/2f43f78f76439f5d11ef313cd379bec036543504/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).
[Earlier retired records](https://gitea.maximumdirect.net/eric/CommandKit/src/commit/6bc37e7ba64ca0920b4d0cc77039a18d4006b24e/docs/roadmap)
also remain in Git history. Completed records are not assignments to restart work.
The completed configuration-outcome implementation and remediation are preserved
in the [v0.8.0 retirement snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/6c7d7c90de4deea8be38b2a447b5c957d748d1b0/docs/roadmap).
The completed PromptKit v0.23.1 adoption, companion-YAML report, and
verification evidence are preserved in the [adoption snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/b1e7c1ee09bf4fb7845b3b5222ccb448ac7fb468/docs/roadmap).
The completed adoption review and upgrade-guidance remediation are preserved
in the [remediation snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/5905399ef3b23ee405bb31a50e534b139cef2e05/docs/roadmap/remediation.md).
Accepted [ADRs](../adr/) and the [architecture policy](../policy/architecture.md)
govern any future implementation. The [CLI reference](../cli.md), public GoDoc,
and [consumer guide](../consumers/guide.md) own implemented behavior. Retaining
an idea here does not select its syntax, API, priority, or delivery date.
## Pending release and integration work
The completed ConfigKit v1.4.0 and PromptKit v0.24.0 adoption, audit remediation,
and coordinated integration releases are preserved in the
[release snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/54e951e38a404b4338c7967ac39c6c01159bf76d/docs/roadmap).
ckconfig v0.10.0 and ckprompt v0.11.0 were published with hosted release pages;
ckprompt passed its independent suite against released ckconfig v0.10.0.
### ckprompt release
## Optional verification
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.
### Optional shell completion validation
### PromptKit v0.20.0 adoption
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.
Zsh and Fish interactive completion checks remain unverified because those
executables were unavailable during remediation. Script generation for Bash,
Zsh and Fish and the Bash interactive checks passed. Run the existing opt-in
backend and consumer checks when those prerequisites are available, following
the [developer guide](../development.md#shell-completion-validation).
## Future capability targets
### Comparison extensions
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
This is separate from clearing configuration lists through transient
overrides and does not reinstate comparison inheritance. No clearing grammar
or public helper API is selected.
### Configuration inspection extensions
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.
Persistent configuration editing remains deferred.
Discovery, import defaults, collection identities, and field-level resolution
recording remain available through application loaders. Discovery tracing,
@@ -81,28 +98,8 @@ 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.
General-purpose helpers for application-internal PromptKit use remain outside
CommandKit's ownership boundary. The following CLI extensions are deferred.
- **Output-contract override flags.** Deferred from the current adoption. A
possible future operator task is validating or previewing one prompt with a
@@ -124,11 +121,6 @@ released upstream identity requirement; it does not change prompt dependencies.
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
The delivered [shell completion feature](../cli.md#shell-completion) provides
@@ -145,15 +137,8 @@ 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.
XML is outside current consideration; Markdown and other renderers remain
unselected.
Error-conversion helpers such as `WarnError` remain deferred pending demonstrated
value; applications can already use `report.Warn(err.Error())`. Terminal redraw
@@ -162,6 +147,16 @@ remain unselected. Whole-run buffering to make failed runs show only errors
was also outside that scope. Any later extension needs a deliberate API and
presentation decision rather than assuming those behaviors are already provided.
### Usage reporting extensions
Machine-readable invocation usage output remains deferred pending a concrete
consumer need. Select its destination, framing, and format explicitly when that
work is undertaken; the current main result stream remains application-owned.
A separate usage-only installation API for applications without a nonempty
ckprompt suite, per-model breakdowns, event traces, and persistent usage history
also remain future proposals. None is required for the delivered aggregate usage
summary through normal installation.
### Release workflow extensions
Historical hosted-page backfilling and automated CI delivery remain separate
@@ -183,9 +178,8 @@ operator or consumer need and an appropriate ownership/behavior decision:
and output-file management or reloadable export.
- Shell completion extensions, including alias discovery described above and
dynamic discovery of configured or remote values.
- 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).
- Persistent configuration mutation. Transient CLI overrides and field metadata
inspection are available through the standard configuration suite.
- Credential diagnostics beyond PromptKit's native smoke checks and additional
live provider probes.
- Additional component identity registration and domain artifact catalogs.
@@ -194,10 +188,7 @@ 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, 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.
Execution, serving, and session operations remain application-owned.
The [architecture policy](../policy/architecture.md#command-and-application-ownership)
recommends shared vocabulary; the [CLI reference](../cli.md#registered-command-syntax)
owns implemented grammar.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,60 @@
# Selected Report Format Access: Optional Proposal
## Status
Consumer proposal from Scriptorium, prepared and revised 2026-11-19.
**This is no longer a prerequisite for Scriptorium's CommandKit migration.**
It remains an optional API proposal for independent upstream consideration,
not an accepted CommandKit contract or required release.
The reviewed baseline is CommandKit v0.7.0, with public guidance at revision
`d330d7637f2e7507eca931a899397222c82bc892`.
## Revised Consumer Direction
Scriptorium will submit PromptKit's native `RunResult` through the invocation
reporter. Its text template emits the artifact; JSON and YAML use native
structured rendering. The main result goes to stdout, and callers save it
through shell redirection or their subprocess API. Scriptorium will not add
`--output`; callers wanting the main result omit `--quiet`, including when
stdout is redirected. Diagnostics remain on stderr.
The optional `--report PATH` flag additionally writes the native result as fixed
JSON using the existing `RenderReport(writer, report, FormatJSON)` API. That
application-owned effect still occurs in quiet mode when a result exists.
This design needs no access to the selected main format outside the invocation
reporter. It can use the existing public APIs without a second parser, custom
serializer, or change to quiet semantics. Scriptorium owns only the separate
report file; callers own main-output redirection and its file lifecycle.
## Optional Public Capability
The original request proposed a read-only selected-format accessor usable by an
application handler with `RenderReport(writer, report, format)`. It addressed
application-owned main files whose format followed `--format` and whose writes
continued in quiet mode. Scriptorium has removed that requirement.
If other consumer needs justify this capability, the proposal is to expose the
selection already interpreted by CommandKit:
- Preserve automatic selection when `--format` is omitted, allowing the report's
text template or native fallback to determine presentation at rendering time.
- Preserve explicit text, JSON, and YAML selections and native repeated-flag,
alias, and argument-placement behavior.
- Leave reporting mode, destinations, diagnostics, and presentation state
unchanged when reading the selection.
The exported name and design remain upstream choices. Such an accessor would
add no standard output-file flag, file lifecycle management, or automatic
tracking of application writer failures. The
[reporting contract](../cli.md#reporting) and
[consumer guide](../consumers/guide.md#invocation-reporting) retain ownership of
native rendering and outcomes.
## Adoption Impact
Scriptorium no longer has accessor-specific acceptance scenarios or a release
dependency on this proposal. The earlier `--output` scenarios are superseded by
stdout reporting and caller-controlled redirection. Neither ckconfig nor
ckprompt needs a change for this revised delivery model.

View File

@@ -1,38 +1,70 @@
# Core example
Run the example from the repository root:
This example shows typed flags, command shortcuts, shared reporting, and shell
completion. It needs no external service. See the [consumer guide](../../docs/consumers/guide.md#go-compatibility)
for Go requirements; maintainers use the toolchain in the
[developer guide](../../docs/development.md#documentation-validation).
Run from the repository root, with that Go toolchain on `PATH`:
```sh
export GOWORK=off GOTOOLCHAIN=local
go run ./examples/core workspace greet --count=2
```
The result shows the selected count and whether it was supplied. It also shows
the entered command path and the original command path, which differ when you
use a shortcut.
## Try shortcuts and explicit values
```sh
# The hello shortcut runs workspace greet; --times means --count.
go run ./examples/core hello --times=0 --tag=first
# ws is a shortcut for the workspace group.
go run ./examples/core ws greet --count=2
# Inspect the group or use the example's global help alias.
go run ./examples/core ws --help
go run ./examples/core hello --hlep
```
An explicit zero remains a supplied value. The handler prints both
`Invocation.EnteredPath()` and `Invocation.CanonicalPath()` so you can see how
shortcuts resolve.
## Try reporting
```sh
go run ./examples/core report
go run ./examples/core report --verbose
go run ./examples/core report --quiet
```
The default scenario succeeds and writes its result. Verbose mode also shows
warnings and information; quiet mode hides the result. The
[CLI reference](../../docs/cli.md#reporting) defines the shared visibility rules.
## Try shell completion
```sh
go build -o core-example ./examples/core
./core-example completion bash
```
The example installs a canonical `workspace greet` command together with a
command shortcut, a group shortcut, a scoped flag alias, and a global help
alias. Its declaration slice mixes the canonical group and routing rules as
`[]commandkit.Declaration`. The handler prints `Invocation.EnteredPath()` and
`Invocation.CanonicalPath()` so the alternate route and its canonical target
are visible in the output.
This prints the Bash completion script. Initialize `bash-completion`, then load
the script as described in the [CLI reference](../../docs/cli.md#shell-completion).
Use the executable basename `core-example` and try completing
`core-example report d` or `core-example ws gr`. Other supported shells are
listed in the reference.
The example also installs `Completion("core-example")` and gives the `report`
scenario argument static choices. Initialize `bash-completion` first if using
Bash. Build it with the basename shown above, load
the script for your shell using the [CLI reference](../../docs/cli.md#shell-completion),
and try completing `core-example report d` or `core-example ws gr`.
## How it is wired
Compatible integration factories also return `commandkit.Command` and can be
passed directly to `New` beside `commandkit.Alias` or flag-alias declarations.
The matched ckconfig and ckprompt releases use the new core identity. For a
command-only `[]commandkit.Command`, convert its elements into a
`[]commandkit.Declaration` before appending routing rules; Go cannot expand the
command slice as `...commandkit.Declaration`. The
The example installs `workspace greet` alongside command and flag aliases in a
`[]commandkit.Declaration`. It also installs `Completion("core-example")` and
provides static choices for the reporting scenario argument. The
[consumer guide](../../docs/consumers/guide.md#application-owned-aliases)
shows both forms, and the [composed consumer](../../integrations/ckprompt/examples/composed)
is the maintained integration example.
explains declaration composition; the [composed example](../../integrations/ckprompt/examples/composed)
adds integration commands.
These aliases require core v0.3.0. Repository contributors can run its test with
`go test ./examples/core` from the root.
Run `GOWORK=off GOTOOLCHAIN=local go test ./examples/core` from the repository
root to check this example.

View File

@@ -74,7 +74,11 @@ func newApp() (*commandkit.App, error) {
commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "scenario", Usage: "demo, recover, warn, warn-error, fail, or partial.", Completion: commandkit.CompleteChoices(
commandkit.CompletionChoice{Value: "demo"}, commandkit.CompletionChoice{Value: "recover"}, commandkit.CompletionChoice{Value: "warn"},
commandkit.CompletionChoice{Value: "warn-error"}, commandkit.CompletionChoice{Value: "fail"}, commandkit.CompletionChoice{Value: "partial"})}, false, func(value string) (string, error) { return value, nil },
func(input *reportInput, value commandkit.Supplied[string]) { input.Scenario = value.Value }),
func(input *reportInput, value commandkit.Supplied[string]) {
if value.Set {
input.Scenario = value.Value
}
}),
},
CheckInput: func(input reportInput) error {
switch input.Scenario {

View File

@@ -43,8 +43,13 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco
var outcome Outcome
path := parsed.Path
handlerRan := false
payload := routedSnapshot.runners[parsed.Key]
featureRequired := !parsed.HelpRequested && current.route.kind == routeCanonical &&
payload != nil && payload.hasRun() && !routedSnapshot.builtins[parsed.Key]
if parsed.Failure != nil {
outcome = Usage(parsed.Failure.Message)
} else if err := current.prepareFeatures(&parsed, featureRequired); err != nil {
outcome = classifyInputError(err)
} else if current.route.kind == routeDiscovery {
if parsed.HelpRequested {
outcome = current.renderHelp(parsed.Path)
@@ -70,6 +75,7 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco
outcome = classifyInputError(err)
} else {
handlerRan = true
current.featureEnabled = !routedSnapshot.builtins[parsed.Key]
outcome = run(current)
}
}
@@ -77,18 +83,75 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco
return current.finalize(outcome, path, handlerRan)
}
func (current *execution) prepareFeatures(parsed *commandmeta.Result, required bool) error {
if current.snapshot == nil {
return nil
}
// Partition the canonical occurrence stream once. Positions within each owner
// remain dense and preserve alias/interleaved binding order.
owners := make(map[string]int, len(current.snapshot.featureFlags))
counts := make([]int, len(current.snapshot.features))
for i, feature := range current.snapshot.features {
flags := feature.payload.bridgeFlags()
counts[i] = len(flags)
for _, flag := range flags {
owners[flag.Name] = i + 1
}
}
occurrences := make([][]commandmeta.FlagOccurrence, len(counts)+1)
for _, occurrence := range parsed.FlagOccurrences {
owner := owners[occurrence.Name]
occurrences[owner] = append(occurrences[owner], occurrence)
}
parsed.FlagOccurrences = occurrences[0]
offset := 0
for i, feature := range current.snapshot.features {
count := counts[i]
if offset+count > len(parsed.InvocationFlagValues) || offset+count > len(parsed.InvocationFlagSpellings) {
return fmt.Errorf("missing invocation feature flag values")
}
start, err := feature.payload.prepare(parsed.InvocationFlagValues[offset:offset+count], parsed.InvocationFlagSpellings[offset:offset+count], occurrences[i+1], false)
if err != nil {
return err
}
if required && current.featureRequiredError == nil {
current.featureRequiredError = feature.payload.requiredError(parsed.InvocationFlagValues[offset : offset+count])
}
current.featureStarts = append(current.featureStarts, start)
offset += count
}
return nil
}
type execution struct {
app *App
ctx context.Context
streams Streams
reporter *Reporter
featureStarts []func(Invocation) (context.Context, func() Report)
featureRequiredError error
featureEnabled bool
featureReports []func() Report
debugEvents []string
options commandmeta.ParseOptions
snapshot *routingSnapshot
session *internalcobra.Session
route routeResult
}
func (current *execution) startFeatures() {
if !current.featureEnabled {
return
}
for _, start := range current.featureStarts {
ctx, report := start(current.invocation())
if ctx != nil {
current.ctx = ctx
}
if report != nil {
current.featureReports = append(current.featureReports, report)
}
}
}
type commandExecution struct {
invocation Invocation
renderHelpTargetsFunc func([]string) Outcome
@@ -116,13 +179,10 @@ func (current commandExecution) renderHelpTargets(targets []string) Outcome {
}
func newExecution(app *App, ctx context.Context, streams Streams) *execution {
streams = normalizeStreams(streams)
current := &execution{
app: app,
ctx: ctx,
streams: streams,
reporter: newReporter(streams),
options: commandmeta.ParseOptions{Context: ctx, Out: streams.Out, Err: streams.Err},
}
if app != nil {
current.snapshot = app.routeSnapshot()
@@ -147,7 +207,7 @@ func (current *execution) prepareSession() {
if current.snapshot == nil {
current.snapshot = current.app.routeSnapshot()
}
options := current.options
options := commandmeta.ParseOptions{}
if current.snapshot != nil {
switch current.route.kind {
case routeCanonical:
@@ -201,11 +261,11 @@ func (current *execution) renderHelpTargets(targets []string) Outcome {
// Explicit help targets are paths, not command invocations with operands.
// Discovery routes have no canonical path and retain only trailing options.
if route.kind == routeUnknown || len(route.args) != len(route.canonicalPath) {
session := internalcobra.Prepare(snapshot.metadata, current.options)
session := internalcobra.Prepare(snapshot.metadata, commandmeta.ParseOptions{})
view := commandmeta.HelpView{EnteredPath: targets, CanonicalPath: targets}
return current.app.renderHelpViewOutcomeWithSession(view, current.reporter, session)
}
options := current.options
options := commandmeta.ParseOptions{}
switch route.kind {
case routeCanonical:
options.FlagAliases = snapshot.flagAliases[route.canonicalPath.Key()].neutralRecords()
@@ -345,7 +405,7 @@ func (current *execution) finalize(outcome Outcome, path []string, handlerRan bo
_ = reporter.Debug(fmt.Sprintf("handler completed for %q with %s outcome and status %d", path, kind, outcome.Status))
}
}
return current.reporter.finalize(outcome, completion)
return current.reporter.finalize(outcome, completion, current.featureReports...)
}
func (current *execution) usageText(path []string) string {

View File

@@ -26,6 +26,7 @@ type flagAliasMapping struct {
type flagAliasContext struct {
path commandpath.Path
canonical map[string]capturedFlagSpelling
invocation map[string]capturedFlagSpelling
discovery bool
}
@@ -64,9 +65,28 @@ func (spelling capturedFlagSpelling) token() string {
return "--" + spelling.name
}
func (context flagAliasContext) canonicalSpelling(key string) (capturedFlagSpelling, bool) {
if value, ok := context.canonical[key]; ok {
return value, true
}
value, ok := context.invocation[key]
return value, ok
}
func invocationFlagSpellings(flags []commandmeta.Flag) map[string]capturedFlagSpelling {
result := make(map[string]capturedFlagSpelling, len(flags))
for _, flag := range flags {
for _, spelling := range featureSpellings(flag) {
result[flagSpellingKey(spelling)] = spelling
}
}
return result
}
func compileFlagAliases(rules []RoutingRule, roots map[string]*canonicalNode, aliases interface {
Resolve(commandpath.Path) commandpath.Path
}) (map[string]resolvedFlagAliases, map[string]resolvedFlagAliases, error) {
ProperSourcePrefixes() []commandpath.Path
}, features []commandmeta.Flag) (map[string]resolvedFlagAliases, map[string]resolvedFlagAliases, error) {
canonicalNodes := indexCanonicalNodes(roots)
global := make(map[string]flagAliasMapping)
scoped := make(map[string]map[string]flagAliasMapping)
@@ -96,6 +116,13 @@ func compileFlagAliases(rules []RoutingRule, roots map[string]*canonicalNode, al
canonicalContexts[key] = flagAliasContext{path: node.path.Clone(), canonical: canonicalFlagSpellings(node.command)}
}
discoveryContexts := discoverFlagContexts(rules, roots, aliases, canonicalNodes)
shared := invocationFlagSpellings(features)
for _, contexts := range []map[string]flagAliasContext{canonicalContexts, discoveryContexts} {
for key, context := range contexts {
context.invocation = shared
contexts[key] = context
}
}
canonicalKeys := sortedContextKeys(canonicalContexts)
resolvedCanonical := make(map[string]resolvedFlagAliases, len(canonicalContexts))
@@ -170,6 +197,7 @@ func canonicalFlagSpellings(command Command) map[string]capturedFlagSpelling {
func discoverFlagContexts(rules []RoutingRule, roots map[string]*canonicalNode, aliases interface {
Resolve(commandpath.Path) commandpath.Path
ProperSourcePrefixes() []commandpath.Path
}, canonicalNodes map[string]*canonicalNode) map[string]flagAliasContext {
commandSources := make(map[string]struct{})
prefixes := make(map[string]commandpath.Path)
@@ -178,12 +206,7 @@ func discoverFlagContexts(rules []RoutingRule, roots map[string]*canonicalNode,
commandSources[rule.record.sourcePath.Key()] = struct{}{}
}
}
for _, rule := range rules {
if rule.record.kind != commandAliasRule {
continue
}
for length := 1; length < len(rule.record.sourcePath); length++ {
prefix := rule.record.sourcePath[:length].Clone()
for _, prefix := range aliases.ProperSourcePrefixes() {
key := prefix.Key()
if canonicalNodes[key] != nil {
continue
@@ -198,7 +221,6 @@ func discoverFlagContexts(rules []RoutingRule, roots map[string]*canonicalNode,
}
prefixes[key] = prefix
}
}
contexts := make(map[string]flagAliasContext, len(prefixes))
for key, path := range prefixes {
contexts[key] = flagAliasContext{path: path, canonical: helpFlagSpellings(), discovery: true}
@@ -230,54 +252,67 @@ func resolveFlagAliases(context flagAliasContext, mappings map[string]flagAliasM
sources = append(sources, source)
}
sort.Strings(sources)
type terminal struct {
spelling capturedFlagSpelling
active bool
}
resolved := make(map[string]terminal)
visiting := make(map[string]int)
var stack []capturedFlagSpelling
var resolve func(capturedFlagSpelling) (terminal, error)
resolve = func(current capturedFlagSpelling) (terminal, error) {
key := flagSpellingKey(current)
if endpoint, exists := context.canonicalSpelling(key); exists {
return terminal{spelling: endpoint, active: true}, nil
}
if result, exists := resolved[key]; exists {
return result, nil
}
if start, exists := visiting[key]; exists {
cycle := append(append([]capturedFlagSpelling(nil), stack[start:]...), current)
spellings := make([]string, 0, len(cycle))
for _, spelling := range cycle {
spellings = append(spellings, spelling.token())
}
return terminal{}, fmt.Errorf("flag alias cycle: %s", strings.Join(spellings, " → "))
}
mapping, exists := mappings[key]
if !exists {
resolved[key] = terminal{}
return terminal{}, nil
}
visiting[key] = len(stack)
stack = append(stack, current)
result, err := resolve(mapping.target)
stack = stack[:len(stack)-1]
delete(visiting, key)
if err != nil {
return terminal{}, err
}
resolved[key] = result
return result, nil
}
for _, sourceKey := range sources {
mapping := mappings[sourceKey]
source := spellingFromKey(sourceKey)
target, active, err := resolveFlagTarget(source, mapping.target, mappings, context.canonical)
terminal, err := resolve(mapping.target)
if err != nil {
return resolvedFlagAliases{}, fmt.Errorf("%s: %w", flagContextDescription(context), err)
}
if !active {
if !terminal.active {
if mapping.scoped {
return resolvedFlagAliases{}, fmt.Errorf("scoped flag alias %s has no canonical destination in %s", source.token(), flagContextDescription(context))
}
continue
}
if _, collision := context.canonical[sourceKey]; collision {
if _, collision := context.canonicalSpelling(sourceKey); collision {
return resolvedFlagAliases{}, fmt.Errorf("flag alias %s conflicts with a canonical spelling in %s", source.token(), flagContextDescription(context))
}
result.bySpelling[sourceKey] = resolvedFlagAlias{source: source, target: target}
result.bySpelling[sourceKey] = resolvedFlagAlias{source: source, target: terminal.spelling}
}
return result, nil
}
func resolveFlagTarget(source, target capturedFlagSpelling, mappings map[string]flagAliasMapping, canonical map[string]capturedFlagSpelling) (capturedFlagSpelling, bool, error) {
visited := map[string]int{flagSpellingKey(source): 0}
chain := []capturedFlagSpelling{source}
current := target
for {
key := flagSpellingKey(current)
if endpoint, exists := canonical[key]; exists {
return endpoint, true, nil
}
if start, exists := visited[key]; exists {
cycle := append(append([]capturedFlagSpelling(nil), chain[start:]...), current)
spellings := make([]string, 0, len(cycle))
for _, spelling := range cycle {
spellings = append(spellings, spelling.token())
}
return capturedFlagSpelling{}, false, fmt.Errorf("flag alias cycle: %s", strings.Join(spellings, " → "))
}
visited[key] = len(chain)
chain = append(chain, current)
next, exists := mappings[key]
if !exists {
return capturedFlagSpelling{}, false, nil
}
current = next.target
}
}
func spellingFromKey(key string) capturedFlagSpelling {
if strings.HasPrefix(key, "short:") {
return capturedFlagSpelling{name: strings.TrimPrefix(key, "short:"), short: true}

View File

@@ -1,6 +1,7 @@
package commandkit
import (
"strconv"
"strings"
"testing"
@@ -295,3 +296,45 @@ func capturedSpelling(token string) capturedFlagSpelling {
issues := []error(nil)
return captureFlagSpelling("test", token, &issues)
}
func TestFlagAliasSharedSuffixAndUnavailableDestination(t *testing.T) {
app, err := New(Identity{Name: "Example"}, flagAliasCommand("active", stringFlag("color", "")), flagAliasCommand("inactive"),
FlagAlias("--first", "--common"), FlagAlias("--second", "--common"), FlagAlias("--common", "--color"))
if err != nil {
t.Fatal(err)
}
for _, name := range []string{"first", "second", "common"} {
key := flagSpellingKey(capturedFlagSpelling{name: name})
active := app.flagAliases[commandpath.Path{"active"}.Key()].bySpelling
if alias, ok := active[key]; !ok || alias.target.token() != "--color" {
t.Fatalf("active %s = %#v", name, alias)
}
if _, ok := app.flagAliases[commandpath.Path{"inactive"}.Key()].bySpelling[key]; ok {
t.Fatalf("inactive %s was installed", name)
}
}
}
func TestSharedDebugDeclarationValidation(t *testing.T) {
valid := BoolFlag(FlagMeta{Name: "debug", Short: "d"}, true, func(*struct{}, Supplied[bool]) {})
if _, err := New(Identity{Name: "Example"}, flagAliasCommand("run", valid)); err != nil {
t.Fatalf("valid debug: %v", err)
}
for _, flags := range [][]Flag[struct{}]{
{valid, valid},
{BoolFlag[struct{}](FlagMeta{Name: "debug"}, false, nil)},
{BoolFlag(FlagMeta{Name: "debug", Short: "h"}, false, func(*struct{}, Supplied[bool]) {})},
{ValueFlag(FlagMeta{Name: "debug"}, (*bool)(nil), strconv.ParseBool, func(*struct{}, Supplied[bool]) {})},
{OccurrenceFlag(FlagMeta{Name: "debug"}, strconv.ParseBool, func(*struct{}, Supplied[bool]) {})},
} {
if _, err := New(Identity{Name: "Example"}, flagAliasCommand("bad", flags...)); err == nil {
t.Fatalf("invalid binding accepted: %#v", flags)
}
}
for _, name := range []string{"quiet", "verbose", "progress", "format"} {
flag := BoolFlag(FlagMeta{Name: name}, false, func(*struct{}, Supplied[bool]) {})
if _, err := New(Identity{Name: "Example"}, flagAliasCommand("bad", flag)); err == nil {
t.Errorf("reserved boolean --%s was accepted", name)
}
}
}

View File

@@ -1,9 +1,9 @@
package commandkit
import (
"container/heap"
"errors"
"fmt"
"sort"
)
// ErrFlagInput identifies a missing required captured flag selected for an input.
@@ -24,6 +24,8 @@ type FlagValues[I any] struct {
// each adapted flag stores its prepared value in target, associated with the
// original inner binding identity. Copies of an original handle remain
// selectable; an independently constructed lookalike does not.
// A captured debug BoolFlag shares reporting input as described by [BoolFlag];
// its requiredness is checked when selected for application.
func CaptureFlags[Outer, I any](flags []Flag[I], target func(*Outer) *FlagValues[I]) []Flag[Outer] {
captured := make([]Flag[Outer], len(flags))
for index, original := range flags {
@@ -108,22 +110,72 @@ func (values FlagValues[I]) applyTo(target *I, suppliedOnly bool, selected ...Fl
}
preparedValues = append(preparedValues, prepared)
}
var ordered []preparedOccurrence[I]
for _, prepared := range preparedValues {
var ordered occurrenceHeap[I]
for index, prepared := range preparedValues {
if prepared.apply != nil {
prepared.apply(target)
}
for _, occurrence := range prepared.ordered {
if occurrence.apply != nil {
ordered = append(ordered, occurrence)
stream := occurrenceStream[I]{events: prepared.ordered, order: index}
stream.skipUnapplied()
if len(stream.events) > 0 {
ordered = append(ordered, stream)
}
}
// One selected stream already has the required order.
if len(ordered) == 1 {
for _, event := range ordered[0].events {
if event.apply != nil {
event.apply(target)
}
sort.SliceStable(ordered, func(i, j int) bool { return *ordered[i].ordinal < *ordered[j].ordinal })
for _, occurrence := range ordered {
occurrence.apply(target)
}
return nil
}
heap.Init(&ordered)
for len(ordered) > 0 {
stream := &ordered[0]
stream.events[0].apply(target)
stream.events = stream.events[1:]
stream.skipUnapplied()
if len(stream.events) == 0 {
heap.Pop(&ordered)
} else {
heap.Fix(&ordered, 0)
}
}
return nil
}
// Each binding supplies a monotone stream. The selection index breaks ordinal
// ties in the same order as concatenation followed by a stable sort.
type occurrenceStream[I any] struct {
events []preparedOccurrence[I]
order int
}
func (stream *occurrenceStream[I]) skipUnapplied() {
for len(stream.events) > 0 && stream.events[0].apply == nil {
stream.events = stream.events[1:]
}
}
type occurrenceHeap[I any] []occurrenceStream[I]
func (h occurrenceHeap[I]) Len() int { return len(h) }
func (h occurrenceHeap[I]) Less(i, j int) bool {
left, right := *h[i].events[0].ordinal, *h[j].events[0].ordinal
if left == right {
return h[i].order < h[j].order
}
return left < right
}
func (h occurrenceHeap[I]) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *occurrenceHeap[I]) Push(value any) { *h = append(*h, value.(occurrenceStream[I])) }
func (h *occurrenceHeap[I]) Pop() any {
last := len(*h) - 1
value := (*h)[last]
(*h)[last] = occurrenceStream[I]{}
*h = (*h)[:last]
return value
}
func classifyInputError(err error) Outcome {

14
go.mod
View File

@@ -1,18 +1,18 @@
module go.maximumdirect.net/commandkit
go 1.26.0
go 1.27.0
require (
github.com/spf13/cobra v1.10.1
github.com/spf13/pflag v1.0.9
go.yaml.in/yaml/v4 v4.0.0-rc.6
github.com/spf13/cobra v1.10.2
github.com/spf13/pflag v1.1.0
go.yaml.in/yaml/v4 v4.0.0
)
require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/yuin/goldmark/v2 v2.1.6 // indirect
go.maximumdirect.net/releasekit v0.9.0 // indirect
golang.org/x/mod v0.40.0 // indirect
github.com/yuin/goldmark/v2 v2.1.16 // indirect
go.maximumdirect.net/releasekit v0.10.0 // indirect
golang.org/x/mod v0.43.0 // indirect
)
tool go.maximumdirect.net/releasekit/cmd/releasekit

25
go.sum
View File

@@ -2,17 +2,18 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.10.1 h1:lJeBwCfmrnXthfAupyUTzJ/J4Nc1RsHC/mSRU2dll/s=
github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/yuin/goldmark/v2 v2.1.6 h1:igy0q9JcqovoFXFx/XjtU8sHVhcUHavPj2sA3EoKJUE=
github.com/yuin/goldmark/v2 v2.1.6/go.mod h1:G6M4/qOFtfn01/o14BU1UR2Lo5N3S9Qo7xCuz/sHjGQ=
go.maximumdirect.net/releasekit v0.9.0 h1:sK+Aoj6gS6ATU/1reocjwBekp4YETYENwkcX5ti6mrE=
go.maximumdirect.net/releasekit v0.9.0/go.mod h1:QE4BLrAhVJTzi+/YTcVl21K/qZp9ojRLg5kuoy3Zb44=
go.yaml.in/yaml/v4 v4.0.0-rc.6 h1:1h7H1ohdUh93/FyE4YaDa1Zh64K6VVbjF4K6WUxMtH4=
go.yaml.in/yaml/v4 v4.0.0-rc.6/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag=
github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/yuin/goldmark/v2 v2.1.16 h1:MXvCVo+Cb2SVJ5cwJUzXetDjI7HECRJCkcqylEQtcJo=
github.com/yuin/goldmark/v2 v2.1.16/go.mod h1:G6M4/qOFtfn01/o14BU1UR2Lo5N3S9Qo7xCuz/sHjGQ=
go.maximumdirect.net/releasekit v0.10.0 h1:3GOgaIigXTkvYaRkntWZASE//2NTR1+IhkoKmt64aJo=
go.maximumdirect.net/releasekit v0.10.0/go.mod h1:cT5NZNEcf7SKDx4MPG40YNK9V4bNyIxcLLFuNlbGQ90=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
go.yaml.in/yaml/v4 v4.0.0 h1:/LG1pNO84Z4l603j/xMn69CcS5OYhMQ/f7l2LoQUGuw=
go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -17,6 +17,7 @@ func (a *App) helpView(route routeResult, snapshot *routingSnapshot) commandmeta
if snapshot == nil {
return view
}
view.CoreFlags = append(append([]commandmeta.Flag(nil), snapshot.featureFlags...), view.CoreFlags...)
view.CommandAliases = routeHelpAliases(snapshot, route)
if view.Discovery {
view.FlagAliases = snapshot.discoveryFlags[route.discoveryPath.Key()].neutralRecords()
@@ -36,11 +37,8 @@ func routeHelpAliases(snapshot *routingSnapshot, route routeResult) []commandmet
}
bySource := make(map[string]commandmeta.CommandAlias)
for _, prefix := range snapshot.aliases.ResolutionPaths(route.enteredPath) {
for _, alias := range snapshot.commandAliases {
source := commandpath.FromTokens(alias.Source)
if len(source) <= len(prefix) || !source.HasPrefix(prefix) {
continue
}
for _, alias := range snapshot.aliases.Descendants(prefix) {
source := alias.Source
suffix := source[len(prefix):]
entered := append(route.enteredPath.Clone(), suffix...)
target := snapshot.aliases.Resolve(entered)

View File

@@ -59,6 +59,21 @@ type Invocation struct {
// manually constructed Invocation has no reporter.
func (inv Invocation) Reporter() *Reporter { return inv.reporter }
// ReportingMode returns the selected reporting mode, independently of delivery
// success. The selection is stable during the handler and remains available
// after finalization. A zero Invocation returns ReportingModeOrdinary. Reads
// are safe alongside concurrent reporting; reporting callbacks must not reenter
// the same reporter.
func (inv Invocation) ReportingMode() ReportingMode {
if inv.reporter == nil || inv.reporter.state == nil {
return ReportingModeOrdinary
}
state := inv.reporter.state
state.mu.Lock()
defer state.mu.Unlock()
return state.mode
}
// 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 {

View File

@@ -1,36 +1,30 @@
# CommandKit ckconfig
`ckconfig` is the optional ConfigKit integration for CommandKit. It adapts
ConfigKit loaders and scopes into reusable `commandkit.Command` declarations;
installing the integration is explicit and does not modify an application by
itself.
`ckconfig` adds configuration inspection commands to Go applications that use
CommandKit and ConfigKit. Operators can view settings, validate configuration,
find where values came from, and compare two configurations.
The application chooses which commands to install. Importing the package alone
does not install commands.
## Module
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.
The module path is `go.maximumdirect.net/ckconfig`. It does not import PromptKit.
See the [consumer guide](https://forge.maximumdirect.net/base-layer/commandkit/src/branch/main/docs/consumers/guide.md#module-selection)
for compatible releases and Go requirements.
## Example
For one application configuration scope, install the convenience declaration:
To inspect one application configuration, pass your loader to `AppCommand`:
```go
app, err := commandkit.New(identity, ckconfig.AppCommand(loadAppConfig))
```
Use `ckconfig.Command(ckconfig.Suite[Input, State]{...})` to define named
scopes, selectors, input checks, and state shared by the selected acquisitions
or comparison in a config invocation. `ckconfig.FromConfigKit` adapts a typed
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 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.
For multiple named configurations or application-specific flags, use
`ckconfig.Command` with a `ckconfig.Suite`. The
[integration guide](https://forge.maximumdirect.net/base-layer/commandkit/src/branch/main/docs/consumers/guide.md#configkit-scopes)
explains loader setup, inputs, and shared state.
The maintained [simple example](examples/simple) shows a complete consumer.
The [CommandKit CLI reference](https://gitea.maximumdirect.net/eric/CommandKit/src/branch/main/docs/cli.md#configuration-scopes)

View File

@@ -0,0 +1,119 @@
package ckconfig
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"testing"
"go.maximumdirect.net/commandkit"
"go.maximumdirect.net/configkit"
)
func TestNativeConfigurationInputOutcomes(t *testing.T) {
_, loadErr := configkit.Load[map[string]any](configkit.Bytes("malformed-input", []byte("broken: [")))
var native *configkit.LoadError
if !errors.As(loadErr, &native) || len(native.Diagnostics()) == 0 {
t.Fatalf("fixture: %v", loadErr)
}
wrapped := fmt.Errorf("application loader: %w", loadErr)
app := newConfigTestApp(t, AppCommand(func(context.Context, Selection) (*configkit.Result[map[string]any], error) { return nil, wrapped }))
cases := []struct {
name string
args []string
report string
}{
{"show", []string{"config", "show"}, ""},
{"sources", []string{"config", "sources", "--format=json"}, `"sources"`},
{"validation", []string{"config", "validate", "--details", "--format=json"}, `"code": "yaml.invalid"`},
{"filtered validation", []string{"config", "validate", "--details", "--code=not-selected", "--format=json"}, `"state": "filtered"`},
{"discovery", []string{"config", "explain", "--list"}, ""},
{"diff", []string{"config", "diff"}, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var out, diag bytes.Buffer
result := app.Execute(context.Background(), tc.args, commandkit.Streams{Out: &out, Err: &diag})
var got *configkit.LoadError
if result.Kind != commandkit.OutcomeUsage || result.Status != 2 || !errors.Is(result.Cause, loadErr) || !errors.As(result.Cause, &got) || got != native {
t.Fatalf("outcome: %#v", result)
}
if !strings.Contains(diag.String(), native.Diagnostics()[0].Message) || !strings.Contains(diag.String(), "malformed-input") {
t.Fatalf("diagnostics: %q", diag.String())
}
if tc.report != "" && !strings.Contains(out.String(), tc.report) {
t.Fatalf("report: %q", out.String())
}
})
}
}
func TestNativeConfigurationComparisonFailureSides(t *testing.T) {
_, loadErr := configkit.Load[map[string]any](configkit.Bytes("bad-side", []byte("broken: [")))
for _, bad := range []string{"left", "right"} {
t.Run(bad, func(t *testing.T) {
app := newConfigTestApp(t, AppCommand(func(_ context.Context, selection Selection) (*configkit.Result[map[string]any], error) {
if selection.Config.Value == bad {
return nil, fmt.Errorf("wrapped: %w", loadErr)
}
return configkit.Load[map[string]any](configkit.Bytes("good-side", []byte("ok: true")))
}))
var diag bytes.Buffer
result := app.Execute(context.Background(), []string{"config", "diff", "--config=left", "--against-config=right"}, commandkit.Streams{Out: io.Discard, Err: &diag})
if result.Kind != commandkit.OutcomeUsage || result.Status != 2 || !errors.Is(result.Cause, loadErr) || !strings.Contains(diag.String(), "bad-side") || !strings.Contains(diag.String(), bad) {
t.Fatalf("outcome=%#v diagnostics=%q", result, diag.String())
}
})
}
}
func TestConfigurationFailureCancellationAndDelivery(t *testing.T) {
_, loadErr := configkit.Load[map[string]any](configkit.Bytes("bad-input", []byte("broken: [")))
for _, args := range [][]string{{"config", "show"}, {"config", "sources"}, {"config", "validate"}, {"config", "explain", "--list"}, {"config", "diff"}} {
t.Run(strings.Join(args, "_"), func(t *testing.T) {
calls := 0
app := newConfigTestApp(t, AppCommand(func(context.Context, Selection) (*configkit.Result[map[string]any], error) {
calls++
return nil, loadErr
}))
ctx, cancel := context.WithCancel(context.Background())
cancel()
var out bytes.Buffer
result := app.Execute(ctx, args, commandkit.Streams{Out: &out, Err: io.Discard})
if result.Status != 1 || !errors.Is(result.Cause, context.Canceled) || calls != 0 || out.Len() != 0 {
t.Fatalf("outcome=%#v calls=%d output=%q", result, calls, out.String())
}
ctx, cancel = context.WithCancel(context.Background())
defer cancel()
app = newConfigTestApp(t, AppCommand(func(context.Context, Selection) (*configkit.Result[map[string]any], error) {
cancel()
return nil, loadErr
}))
result = app.Execute(ctx, args, commandkit.Streams{Out: io.Discard, Err: io.Discard})
if result.Status != 1 || !errors.Is(result.Cause, context.Canceled) || !errors.Is(result.Cause, loadErr) {
t.Fatalf("joined outcome=%#v", result)
}
})
}
app := newConfigTestApp(t, AppCommand(func(context.Context, Selection) (*configkit.Result[map[string]any], error) { return nil, loadErr }))
for _, args := range [][]string{{"config", "sources"}, {"config", "validate"}} {
result := app.Execute(context.Background(), args, commandkit.Streams{Out: shortWriter{}, Err: io.Discard})
if result.Kind != commandkit.OutcomeOperational || result.Status != 1 || !errors.Is(result.Cause, loadErr) || result.Presentation.Output.State != commandkit.DeliveryIncomplete {
t.Fatalf("delivery %v: %#v", args, result)
}
}
}
func TestConfigurationOperationalFailures(t *testing.T) {
_, loadErr := configkit.Load[map[string]any](configkit.File("/nonexistent-commandkit-outcome-test"))
for _, failure := range []error{errors.New("unavailable"), loadErr} {
app := newConfigTestApp(t, AppCommand(func(context.Context, Selection) (*configkit.Result[map[string]any], error) { return nil, failure }))
result := app.Execute(context.Background(), []string{"config", "show"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
if result.Status != 1 || !errors.Is(result.Cause, failure) {
t.Fatalf("outcome=%#v", result)
}
}
}

View File

@@ -33,7 +33,98 @@ 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)
result, acquired, err := acquireConfigKit(ctx, name, load, request.Selection, input, state)
if err != nil {
return acquired, err
}
metadata := result.Metadata()
acquired.Value.Effective, acquired.Value.Explanation, acquired.Value.Metadata, acquired.Value.Paths = result, result, &metadata, &metadata
return acquired, nil
}
scope.Compare = func(ctx context.Context, request ComparisonRequest[I], state S) (commandkit.Acquired[[]configkit.Difference], error) {
left, right, acquired, err := loadComparisonPair(ctx, name, load, request, state)
if err != nil {
return acquired, err
}
acquired.Value, err = configkit.Diff(left, right)
if err != nil {
return acquired, fmt.Errorf("ConfigKit scope %q native diff: %w", name, err)
}
return acquired, nil
}
return scope
}
// FromConfigKitSubtree adapts an application-owned typed loader to the same
// operations as FromConfigKit, using native inspection at path. Loading and
// validation cover the whole result; sources and findings retain that context.
// Discovery and rendering use the focused inspection, while explicit paths and
// comparison retain ConfigKit's native semantics. Construction and help do not
// load configuration, and a nil loader is recorded as a construction issue.
// The loader receives each operation's selection, input, and shared state.
// A valid absent subtree can be acquired, but rendering its effective value
// reports the native unavailable-value error. An unavailable inspection returns
// an operational error with any whole-load evidence already acquired.
func FromConfigKitSubtree[I, S, T any](
name, summary string,
path configkit.Path,
load func(context.Context, Selection, I, S) (*configkit.Result[T], error),
) Scope[I, S] {
scope := Scope[I, S]{
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))
}
scope.Acquire = func(ctx context.Context, request Request, input I, state S) (commandkit.Acquired[View], error) {
result, acquired, err := acquireConfigKit(ctx, name, load, request.Selection, input, state)
if err != nil {
return acquired, err
}
inspection, ok := result.InspectSubtree(path)
if !ok {
return acquired, fmt.Errorf("ConfigKit scope %q inspection at %q is unavailable", name, path.String())
}
metadata := inspection.Metadata()
acquired.Value.Effective = inspection
acquired.Value.Explanation = inspection
acquired.Value.Paths = inspection
acquired.Value.Metadata = &metadata
acquired.Value.Sources = inspection
return acquired, nil
}
scope.Compare = func(ctx context.Context, request ComparisonRequest[I], state S) (commandkit.Acquired[[]configkit.Difference], error) {
left, right, acquired, err := loadComparisonPair(ctx, name, load, request, state)
if err != nil {
return acquired, err
}
leftView, ok := left.InspectSubtree(path)
if !ok {
return acquired, fmt.Errorf("ConfigKit scope %q left inspection at %q is unavailable", name, path.String())
}
rightView, ok := right.InspectSubtree(path)
if !ok {
return acquired, fmt.Errorf("ConfigKit scope %q right inspection at %q is unavailable", name, path.String())
}
if err := ctx.Err(); err != nil {
return acquired, fmt.Errorf("ConfigKit scope %q comparison before native diff: %w", name, err)
}
acquired.Value, err = leftView.Diff(rightView)
if err != nil {
return acquired, fmt.Errorf("ConfigKit scope %q native diff: %w", name, err)
}
return acquired, nil
}
return scope
}
func acquireConfigKit[I, S, T any](ctx context.Context, name string,
load func(context.Context, Selection, I, S) (*configkit.Result[T], error),
selection Selection, input I, state S,
) (*configkit.Result[T], commandkit.Acquired[View], error) {
result, err := load(ctx, selection, input, state)
acquired := commandkit.Acquired[View]{}
if err != nil {
var loadError *configkit.LoadError
@@ -43,54 +134,49 @@ func FromConfigKit[I, S, T any](
acquired.Value.Sources = loadError
acquired.Value.Findings = &Findings{Records: records, Messages: messages}
acquired.Explanation = explanation
return result, acquired, err
}
return acquired, err
}
if result == nil {
return commandkit.Acquired[View]{}, fmt.Errorf("ConfigKit scope %q returned a nil result", name)
if err != nil {
return nil, acquired, err
}
return nil, acquired, 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.Value = View{Sources: result, 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) {
if err := ctx.Err(); err != nil {
return commandkit.Acquired[[]configkit.Difference]{}, fmt.Errorf("ConfigKit scope %q comparison before left load: %w", name, err)
}
return result, acquired, err
}
func loadComparisonPair[I, S, T any](ctx context.Context, name string,
load func(context.Context, Selection, I, S) (*configkit.Result[T], error),
request ComparisonRequest[I], state S,
) (*configkit.Result[T], *configkit.Result[T], commandkit.Acquired[[]configkit.Difference], error) {
acquired := commandkit.Acquired[[]configkit.Difference]{}
left, leftDiagnostics, leftExplanation, err := loadComparisonSide(ctx, name, "left", load, request.Left, state)
acquired.Diagnostics = append(acquired.Diagnostics, leftDiagnostics...)
acquired.Explanation = appendConfigKitExplanation(acquired.Explanation, leftExplanation)
if err != nil {
return acquired, err
}
if err := ctx.Err(); err != nil {
return acquired, fmt.Errorf("ConfigKit scope %q comparison after left load: %w", name, err)
return nil, nil, acquired, fmt.Errorf("ConfigKit scope %q comparison before left load: %w", name, err)
}
right, rightDiagnostics, rightExplanation, err := loadComparisonSide(ctx, name, "right", load, request.Right, state)
acquired.Diagnostics = append(acquired.Diagnostics, rightDiagnostics...)
acquired.Explanation = appendConfigKitExplanation(acquired.Explanation, rightExplanation)
left, diagnostics, explanation, err := loadComparisonSide(ctx, name, "left", load, request.Left, state)
acquired.Diagnostics = append(acquired.Diagnostics, diagnostics...)
acquired.Explanation = appendConfigKitExplanation(acquired.Explanation, explanation)
if err != nil {
return acquired, err
return nil, nil, acquired, err
}
if err := ctx.Err(); err != nil {
return acquired, fmt.Errorf("ConfigKit scope %q comparison before native diff: %w", name, err)
return nil, nil, acquired, fmt.Errorf("ConfigKit scope %q comparison after left load: %w", name, err)
}
acquired.Value, err = configkit.Diff(left, right)
right, diagnostics, explanation, err := loadComparisonSide(ctx, name, "right", load, request.Right, state)
acquired.Diagnostics = append(acquired.Diagnostics, diagnostics...)
acquired.Explanation = appendConfigKitExplanation(acquired.Explanation, explanation)
if err != nil {
return acquired, fmt.Errorf("ConfigKit scope %q native diff: %w", name, err)
return nil, nil, acquired, err
}
return acquired, nil
if err := ctx.Err(); err != nil {
return nil, nil, acquired, fmt.Errorf("ConfigKit scope %q comparison before native diff: %w", name, err)
}
return scope
return left, right, acquired, nil
}
func loadComparisonSide[I, S, T any](
@@ -120,14 +206,17 @@ func loadComparisonSide[I, S, T any](
}
func configKitDiagnostics(scope string, sources []configkit.SourceInfo, records []configkit.Diagnostic) ([]commandkit.Diagnostic, commandkit.Explanation) {
return configKitDiagnosticsWithHeading("Configuration scope "+strconv.Quote(scope)+":\n", sources, records)
return AdaptDiagnostics("Configuration scope "+strconv.Quote(scope)+":\n", sources, records)
}
func configKitComparisonDiagnostics(scope, side string, sources []configkit.SourceInfo, records []configkit.Diagnostic) ([]commandkit.Diagnostic, commandkit.Explanation) {
return configKitDiagnosticsWithHeading("Configuration scope "+strconv.Quote(scope)+" "+side+":\n", sources, records)
return AdaptDiagnostics("Configuration scope "+strconv.Quote(scope)+" "+side+":\n", sources, records)
}
func configKitDiagnosticsWithHeading(heading string, sources []configkit.SourceInfo, records []configkit.Diagnostic) ([]commandkit.Diagnostic, commandkit.Explanation) {
// AdaptDiagnostics captures ConfigKit diagnostics as CLI presentation evidence.
// It does not print, acquire configuration, determine outcomes, or schedule messages.
// The heading is used as supplied when the captured evidence is rendered.
func AdaptDiagnostics(heading string, sources []configkit.SourceInfo, records []configkit.Diagnostic) ([]commandkit.Diagnostic, commandkit.Explanation) {
if len(records) == 0 {
return nil, commandkit.Explanation{}
}

View File

@@ -63,7 +63,9 @@ type ComparisonRequest[I any] struct {
Right ComparisonSide[I]
}
// EffectiveWriter writes a configuration's native effective representation.
// EffectiveWriter writes one safe YAML document for conversion by
// commandkit.DecodeYAMLReport. Its formatting, comments, and framing are not
// passed through to the resulting report.
type EffectiveWriter interface {
WriteEffective(io.Writer) error
}
@@ -73,18 +75,24 @@ type SourceReader interface {
Sources() []configkit.SourceInfo
}
// ExplanationReader reads and writes a configuration's native path explanation.
// ExplanationReader acquires a configuration's native path explanation.
type ExplanationReader interface {
Explain(configkit.Path) (configkit.Explanation, bool)
WriteExplanation(io.Writer, configkit.Path) error
}
// View exposes native configuration facets without reconstructing their
// reports.
// PathReader supplies native candidates for configuration path discovery.
type PathReader interface {
HistoricalPaths() []configkit.Path
}
// View exposes native configuration evidence used to build reports.
type View struct {
Effective EffectiveWriter
Sources SourceReader
Explanation ExplanationReader
// Paths supplies discovery candidates. When nil, discovery uses Metadata.
// A nonnil reader may return an empty list without triggering that fallback.
Paths PathReader
// Metadata supplies native configuration path metadata when available.
Metadata *configkit.Metadata
// Findings supplies native diagnostics and their ordinary presentations.
@@ -102,7 +110,8 @@ type Findings struct {
// ScopeFeatures describes optional modes within configuration operations.
type ScopeFeatures struct {
// PathDiscovery indicates support for metadata-backed path discovery.
// PathDiscovery indicates support for path discovery using Paths or, when
// absent, Metadata. Metadata is required to describe and filter candidates.
PathDiscovery bool
// PathShow indicates support for displaying a selected effective path.
PathShow bool

View File

@@ -117,13 +117,6 @@ func TestFromConfigKitPassesInvocationValuesAndNativeFacets(t *testing.T) {
if _, ok := acquired.Value.Explanation.Explain(path); !ok {
t.Fatal("native explanation facet did not resolve /name")
}
var explanation bytes.Buffer
if err := acquired.Value.Explanation.WriteExplanation(&explanation, path); err != nil {
t.Fatal(err)
}
if explanation.Len() == 0 {
t.Fatal("native explanation writer produced no output")
}
}
func TestFromConfigKitRetainsLoadErrorAndDiagnostics(t *testing.T) {
@@ -140,8 +133,12 @@ func TestFromConfigKitRetainsLoadErrorAndDiagnostics(t *testing.T) {
if loadErr == nil {
t.Fatal("fixture did not produce a ConfigKit load error")
}
partial, err := configkit.Load[struct{}](configkit.Mapping("unrelated result", map[string]any{}))
if err != nil {
t.Fatal(err)
}
scope := FromConfigKit[struct{}, struct{}, struct{}]("app", "", func(context.Context, Selection, struct{}, struct{}) (*configkit.Result[struct{}], error) {
return nil, loadErr
return partial, loadErr
})
acquired, gotErr := scope.Acquire(context.Background(), Request{}, struct{}{}, struct{}{})
if gotErr != loadErr {
@@ -157,6 +154,9 @@ func TestFromConfigKitRetainsLoadErrorAndDiagnostics(t *testing.T) {
if acquired.Explanation.Message != "" || len(acquired.Explanation.Details) != 1 {
t.Fatalf("failure explanation = %#v", acquired.Explanation)
}
if !reflect.DeepEqual(acquired.Value.Sources.Sources(), typed.Sources()) || !reflect.DeepEqual(acquired.Value.Findings.Records, typed.Diagnostics()) {
t.Fatal("LoadError snapshot was replaced or duplicated")
}
var warning, terminal bytes.Buffer
if err := acquired.Value.Findings.Messages[0].Write(&warning); err != nil {
t.Fatal(err)
@@ -175,43 +175,83 @@ func TestFromConfigKitRetainsLoadErrorAndDiagnostics(t *testing.T) {
}
}
func TestFromConfigKitDoesNotExposeResultFromFailedLoad(t *testing.T) {
func TestFromConfigKitRetainsResultEvidenceWithApplicationFailure(t *testing.T) {
result, err := adapterSettingsLoad(configkit.Mapping("partial source", map[string]any{"greeting": "Hello"}))
if err != nil {
t.Fatal(err)
}
loadErr := errors.New("loader returned a value with an error")
scope := FromConfigKit[struct{}, struct{}, adapterSettings]("app", "", func(context.Context, Selection, struct{}, struct{}) (*configkit.Result[adapterSettings], error) {
return result, loadErr
for _, cause := range []error{errors.New("post-load check failed"), context.Canceled} {
t.Run(cause.Error(), func(t *testing.T) {
scope := FromConfigKit("app", "", func(context.Context, Selection, struct{}, struct{}) (*configkit.Result[adapterSettings], error) {
return result, cause
})
acquired, gotErr := scope.Acquire(context.Background(), Request{}, struct{}{}, struct{}{})
if gotErr != loadErr {
t.Fatalf("load error identity = %v, want %v", gotErr, loadErr)
if gotErr != cause || acquired.Value.Effective != nil || acquired.Value.Metadata != nil || acquired.Value.Explanation != nil || acquired.Value.Sources == nil || acquired.Value.Findings == nil {
t.Fatalf("failed acquisition = %#v, %v", acquired, gotErr)
}
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 !reflect.DeepEqual(acquired.Value.Sources.Sources(), result.Sources()) || !reflect.DeepEqual(acquired.Value.Findings.Records, result.Diagnostics()) || len(acquired.Value.Findings.Messages) != 1 || len(acquired.Explanation.Details) != 0 {
t.Fatalf("lost or duplicated result evidence: %#v", acquired)
}
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
for _, args := range [][]string{{"config", "sources", "--format=json"}, {"config", "validate", "--details", "--format=json"}, {"config", "validate", "--verbose"}} {
var out, diag bytes.Buffer
got := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diag})
if !errors.Is(got.Cause, cause) {
t.Fatalf("lost cause: %#v", got)
}
if args[1] == "sources" {
if !strings.Contains(out.String(), "partial source") {
t.Fatalf("lost sources: %s", out.String())
}
} else if strings.Contains(strings.Join(args, " "), "--details") {
if !strings.Contains(out.String(), result.Diagnostics()[0].Message) || strings.Contains(diag.String(), result.Diagnostics()[0].Message) {
t.Fatalf("detailed evidence: output=%s diag=%s", out.String(), diag.String())
}
} else if !strings.Contains(diag.String(), result.Diagnostics()[0].Message) {
t.Fatalf("lost ordinary warning: %s", diag.String())
}
}
writeErr := errors.New("output failed")
got := app.Execute(context.Background(), []string{"config", "validate", "--details"}, commandkit.Streams{Out: failingOutput{err: writeErr}, Err: io.Discard})
if !errors.Is(got.Cause, cause) || !errors.Is(got.Presentation.Output.WriteError, writeErr) {
t.Fatalf("lost operation/presentation cause: %#v", got)
}
})
}
empty, err := configkit.Load[map[string]any](configkit.Mapping("empty", map[string]any{}))
if err != nil {
t.Fatal(err)
}
for _, result := range []*configkit.Result[map[string]any]{nil, empty} {
cause := errors.New("application failure")
scope := FromConfigKit("app", "", func(context.Context, Selection, struct{}, struct{}) (*configkit.Result[map[string]any], error) {
return result, cause
})
got, err := scope.Acquire(context.Background(), Request{}, struct{}{}, struct{}{})
if err != cause || (got.Value.Findings == nil) != (result == nil) {
t.Fatalf("unavailable/empty evidence: %#v %v", got, err)
}
if len(acquired.Explanation.Details) != 0 {
t.Fatalf("warning-only result acquired terminal context: %#v", acquired.Explanation)
}
}
func TestConfigKitDiagnosticsMapSeverityAndPropagateWriterFailures(t *testing.T) {
warning, noExplanation := configKitDiagnostics("app", nil, []configkit.Diagnostic{{Severity: configkit.SeverityWarning, Message: "safe warning"}})
warning, noExplanation := AdaptDiagnostics("scope:\n", nil, []configkit.Diagnostic{{Severity: configkit.SeverityWarning, Message: "safe warning"}})
if len(warning) != 1 || warning[0].Severity != commandkit.SeverityWarning {
t.Fatalf("warning diagnostics = %#v", warning)
}
if noExplanation.Message != "" || len(noExplanation.Details) != 0 {
t.Fatalf("warning-only explanation = %#v", noExplanation)
}
withWarning, withExplanation := configKitDiagnostics("app", nil, []configkit.Diagnostic{
withWarning, withExplanation := AdaptDiagnostics("scope:\n", nil, []configkit.Diagnostic{
{Severity: configkit.SeverityWarning, Message: "safe warning"},
{Severity: configkit.SeverityError, Message: "safe error"},
})
if len(withWarning) != 1 || withWarning[0].Severity != commandkit.SeverityWarning || len(withExplanation.Details) != 1 {
t.Fatalf("mixed diagnostics = %#v, explanation = %#v", withWarning, withExplanation)
}
if empty, explanation := AdaptDiagnostics("unused", nil, nil); len(empty) != 0 || len(explanation.Details) != 0 {
t.Fatalf("empty evidence = %#v, %#v", empty, explanation)
}
if err := withWarning[0].Write(shortWriter{}); !errors.Is(err, io.ErrShortWrite) {
t.Fatalf("short writer error = %v, want %v", err, io.ErrShortWrite)
@@ -243,10 +283,11 @@ func TestConfigKitTerminalContextRetainsRelatedLocationsAndSnapshots(t *testing.
Primary: primary,
Related: related,
}}
_, explanation := configKitDiagnostics("app", sources, records)
_, explanation := AdaptDiagnostics("Configuration scope \"app\":\n", sources, records)
primary.SourceID = "mutated-primary"
related[0].SourceID = "mutated-related"
sources[0].Path = "mutated.yml"
records[0].Message = "mutated message"
if len(explanation.Details) != 1 {
t.Fatalf("explanation = %#v", explanation)
@@ -260,7 +301,7 @@ func TestConfigKitTerminalContextRetainsRelatedLocationsAndSnapshots(t *testing.
t.Errorf("terminal context %q omits %q", output.String(), fragment)
}
}
if strings.Contains(output.String(), "mutated-") || strings.Contains(output.String(), "mutated.yml") {
if strings.Contains(output.String(), "mutated-") || strings.Contains(output.String(), "mutated.yml") || strings.Contains(output.String(), "mutated message") {
t.Fatalf("terminal renderer retained caller mutations: %q", output.String())
}
}

View File

@@ -60,6 +60,44 @@ func TestDetailedValidationFiltersAndRetainsFailureEvidence(t *testing.T) {
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())
}
for _, tc := range []struct {
name string
flags []string
first, second []string
}{
{"any within filters", []string{"--severity=warning", "--severity=error", "--code=chosen", "--code=other", "--code=failed"}, []string{"selected warning", "other warning"}, []string{"failed finding"}},
{"duplicates and unknown", []string{"--severity=warning", "--severity=warning", "--code=chosen", "--code=chosen", "--code=future-code"}, []string{"selected warning"}, nil},
{"both filters", []string{"--severity=error", "--code=chosen", "--code=failed"}, nil, []string{"failed finding"}},
{"no matching code", []string{"--code=future-code"}, nil, nil},
} {
t.Run(tc.name, func(t *testing.T) {
var out bytes.Buffer
args := append([]string{"config", "validate", "--scope=all", "--details", "--format=json"}, tc.flags...)
got := app.Execute(context.Background(), args, 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(got.Cause, cause) || len(report.Scopes) != 2 {
t.Fatalf("outcome=%#v report=%#v", got, report)
}
for index, want := range [][]string{tc.first, tc.second} {
details := report.Scopes[index].Details
if len(details.Findings) != len(want) {
t.Fatalf("findings=%#v want=%v", details.Findings, want)
}
for i, message := range want {
if details.Findings[i].Message != message {
t.Fatalf("finding order=%#v want=%v", details.Findings, want)
}
}
if len(want) == 0 && details.State != "filtered" {
t.Fatalf("state=%q", details.State)
}
}
})
}
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})

View File

@@ -10,25 +10,25 @@ import (
func runConfigDiff[I, S any](invocation commandkit.Invocation, plan *configOperationPlan[I, S], state S) commandkit.Outcome {
if plan.comparison == nil || plan.comparison.scope == nil {
cause := errors.New("configuration comparison was not prepared")
return configFailure("Configuration comparison was not prepared.", commandkit.Explanation{}, cause)
return configFailure(invocation.Context, "Configuration comparison was not prepared.", commandkit.Explanation{}, cause)
}
selected := plan.comparison
if err := invocation.Context.Err(); err != nil {
return configFailure("Configuration comparison was canceled.", commandkit.Explanation{}, err)
return configFailure(invocation.Context, "Configuration comparison was canceled.", commandkit.Explanation{}, err)
}
compare := selected.scope.scope.Compare
if compare == nil {
cause := fmt.Errorf("configuration scope %q has no comparison callback", selected.scope.scope.Name)
return configFailure("Configuration scope does not support comparison.", commandkit.Explanation{}, cause)
return configFailure(invocation.Context, "Configuration scope does not support comparison.", commandkit.Explanation{}, cause)
}
acquired, err := compare(invocation.Context, selected.request, state)
reporter := invocation.Reporter()
queueConfigDiagnostics(reporter, acquired.Diagnostics)
if err != nil {
return configFailure(fmt.Sprintf("Unable to compare configuration scope %q.", selected.scope.scope.Name), acquired.Explanation, err)
return configFailure(invocation.Context, fmt.Sprintf("Unable to compare configuration scope %q.", selected.scope.scope.Name), acquired.Explanation, err)
}
if err := invocation.Context.Err(); err != nil {
return configFailure("Configuration comparison was canceled.", acquired.Explanation, err)
return configFailure(invocation.Context, "Configuration comparison was canceled.", acquired.Explanation, err)
}
outcome := renderPreparedConfigReport(invocation, acquired.Explanation, func() (any, error) {
if plan.details {

View File

@@ -8,39 +8,17 @@ import (
configkit "go.maximumdirect.net/configkit"
)
func decodeJSONPointer(pointer string) ([]string, error) {
func decodeJSONPointer(path configkit.Path) []string {
pointer := path.String()
if pointer == "" {
return nil, nil
return nil
}
if pointer[0] != '/' {
return nil, fmt.Errorf("decode JSON pointer %q: path must start with /", pointer)
}
parts := strings.Split(pointer[1:], "/")
decoder := strings.NewReplacer("~1", "/", "~0", "~")
for index, part := range parts {
var decoded strings.Builder
decoded.Grow(len(part))
for offset := 0; offset < len(part); offset++ {
if part[offset] != '~' {
decoded.WriteByte(part[offset])
continue
parts[index] = decoder.Replace(part)
}
if offset+1 >= len(part) {
return nil, fmt.Errorf("decode JSON pointer %q: incomplete escape in token %d", pointer, index)
}
offset++
switch part[offset] {
case '0':
decoded.WriteByte('~')
case '1':
decoded.WriteByte('/')
default:
return nil, fmt.Errorf("decode JSON pointer %q: invalid escape in token %d", pointer, index)
}
}
parts[index] = decoded.String()
}
return parts, nil
return parts
}
func placeReportValue(root any, path []string, value any) (any, error) {
@@ -135,10 +113,7 @@ func renderDiffReport(differences []configkit.Difference) (any, error) {
if !difference.Right.Present {
continue
}
tokens, err := decodeJSONPointer(path)
if err != nil {
return nil, fmt.Errorf("difference at %q: %w", path, err)
}
tokens := decodeJSONPointer(difference.Path)
value, err := commandkit.DecodeYAMLReport(strings.NewReader(difference.Right.YAML))
if err != nil {
return nil, fmt.Errorf("difference at %q: %w", path, err)

View File

@@ -3,6 +3,8 @@ package ckconfig
import (
"reflect"
"testing"
configkit "go.maximumdirect.net/configkit"
)
func TestDecodeJSONPointerPreservesSemanticTokens(t *testing.T) {
@@ -16,21 +18,18 @@ func TestDecodeJSONPointerPreservesSemanticTokens(t *testing.T) {
{pointer: "/0/../a.b/50%", want: []string{"0", "..", "a.b", "50%"}},
{pointer: "/a~1b/c~0d", want: []string{"a/b", "c~d"}},
{pointer: "/~01", want: []string{"~1"}},
{pointer: "/café", want: []string{"café"}},
}
for _, test := range tests {
got, err := decodeJSONPointer(test.pointer)
path, err := configkit.ParsePath(test.pointer)
if err != nil {
t.Fatalf("decode %q: %v", test.pointer, err)
t.Fatal(err)
}
got := decodeJSONPointer(path)
if !reflect.DeepEqual(got, test.want) {
t.Errorf("decode %q = %#v, want %#v", test.pointer, got, test.want)
}
}
for _, pointer := range []string{"missing-leading-slash", "/bad~", "/bad~2escape"} {
if _, err := decodeJSONPointer(pointer); err == nil {
t.Errorf("decode %q unexpectedly succeeded", pointer)
}
}
}
func TestPlaceReportValue(t *testing.T) {

View File

@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"io"
"reflect"
"strings"
"testing"
@@ -16,7 +17,7 @@ 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})
return configkit.Load(configkit.Mapping("fixture", map[string]any{"a/b": map[string]any{"x": 1}, "a~b": 4, "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}}))
@@ -37,7 +38,11 @@ func TestExplainDiscoveryModesAndMetadata(t *testing.T) {
}
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 {
decode := func(output string) error {
report = pathDiscoveryReport{}
return json.Unmarshal([]byte(output), &report)
}
if result.Kind != commandkit.OutcomeSuccess || decode(out) != nil || len(report.Paths) != 2 {
t.Fatalf("escaped subtree: %#v %q", result, out)
}
seen := map[string]bool{}
@@ -48,11 +53,46 @@ func TestExplainDiscoveryModesAndMetadata(t *testing.T) {
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" {
if result.Kind != commandkit.OutcomeSuccess || decode(out) != nil || len(report.Paths) != 1 || report.Paths[0].Path != "/ab" {
t.Fatalf("token boundary: %#v %q", result, out)
}
for _, tc := range []struct {
prefix string
paths []string
}{
{"/a~1b/x", []string{"/a~1b/x"}},
{"/a~0b", []string{"/a~0b"}},
{"/a", nil},
{"/a~1b/x/unknown", nil},
{"/ab/" + strings.Repeat("too-deep/", 20) + "unknown", nil},
} {
result, out = run("--list", "--under="+tc.prefix, "--format=json")
if result.Status != 0 || decode(out) != nil {
t.Fatalf("prefix %q: %#v %s", tc.prefix, result, out)
}
var paths []string
for _, entry := range report.Paths {
paths = append(paths, entry.Path)
}
if !reflect.DeepEqual(paths, tc.paths) {
t.Fatalf("prefix %q: paths=%v want=%v", tc.prefix, paths, tc.paths)
}
}
result, baseline := run("--list", "--format=json")
if result.Status != 0 {
t.Fatalf("unfiltered discovery=%#v", result)
}
var all pathDiscoveryReport
if err := json.Unmarshal([]byte(baseline), &all); err != nil {
t.Fatal(err)
}
result, out = run("--list", "--under=", "--format=json")
if result.Status != 0 || decode(out) != nil || !reflect.DeepEqual(report, all) {
t.Fatalf("root subtree changed discovery: %#v %s", result, out)
}
result, out = run("--list", "--historical", "--set=/gone=null", "--format=json")
if result.Kind != commandkit.OutcomeSuccess || json.Unmarshal([]byte(out), &report) != nil {
if result.Kind != commandkit.OutcomeSuccess || decode(out) != nil {
t.Fatalf("historical: %#v %q", result, out)
}
removed := false
@@ -64,8 +104,8 @@ func TestExplainDiscoveryModesAndMetadata(t *testing.T) {
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 {
result, out = run("--list", "--under=/gone", "--historical", "--explicit=false", "--set=/gone=null", "--format=json")
if result.Kind != commandkit.OutcomeSuccess || decode(out) != nil {
t.Fatalf("explicit filter: %#v %q", result, out)
}
for _, entry := range report.Paths {
@@ -114,3 +154,68 @@ func TestExplainBareHelpRecordsDeliveryFailure(t *testing.T) {
t.Fatalf("help delivery = %#v, input/state/acquire=%d/%d/%d", result, inputs, states, calls)
}
}
type discoveryPaths []configkit.Path
func (paths discoveryPaths) HistoricalPaths() []configkit.Path { return paths }
func TestExplainDiscoveryUsesSuppliedPaths(t *testing.T) {
scope := FromConfigKit("app", "", func(_ context.Context, selection Selection, _, _ struct{}) (*configkit.Result[map[string]any], error) {
return configkit.Load(configkit.Mapping("fixture", map[string]any{
"focus": map[string]any{"keep": 1, "gone": map[string]any{"child": 2}},
"sibling": 3,
}), configkit.Options[map[string]any]{Overrides: selection.Overrides})
})
scope.Features.Overrides = true
acquire := scope.Acquire
var reader PathReader
scope.Acquire = func(ctx context.Context, request Request, input, state struct{}) (commandkit.Acquired[View], error) {
acquired, err := acquire(ctx, request, input, state)
acquired.Value.Paths = reader
return acquired, err
}
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
run := func(args ...string) pathDiscoveryReport {
t.Helper()
var out bytes.Buffer
arguments := append([]string{"config", "explain", "--list", "--format=json", "--set=/focus/gone=null"}, args...)
outcome := app.Execute(context.Background(), arguments, commandkit.Streams{Out: &out, Err: io.Discard})
var report pathDiscoveryReport
if outcome.Kind != commandkit.OutcomeSuccess {
t.Fatalf("discovery %v: %#v", args, outcome)
}
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
t.Fatal(err)
}
return report
}
reader = discoveryPaths{configkit.Keys("focus", "keep"), configkit.Keys("focus", "gone"), configkit.Keys("focus", "gone", "child")}
check := func(report pathDiscoveryReport, want ...string) {
t.Helper()
var got []string
for _, entry := range report.Paths {
got = append(got, entry.Path)
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("paths = %v, want %v", got, want)
}
}
check(run(), "/focus/keep", "/focus/gone")
check(run("--historical"), "/focus/keep", "/focus/gone", "/focus/gone/child")
check(run("--under=/focus/gone", "--historical"), "/focus/gone", "/focus/gone/child")
check(run("--historical", "--explicit=true"), "/focus/keep", "/focus/gone")
check(run("--historical", "--explicit=false"))
reader = discoveryPaths(nil)
check(run("--historical"))
reader = discoveryPaths{}
check(run("--historical"))
reader = nil
fallback := run()
foundSibling := false
for _, entry := range fallback.Paths {
foundSibling = foundSibling || entry.Path == "/sibling"
}
if !foundSibling {
t.Fatalf("metadata fallback omitted sibling: %#v", fallback.Paths)
}
}

View File

@@ -1,10 +1,17 @@
// Package ckconfig, provided by go.maximumdirect.net/ckconfig, provides
// CommandKit's optional ConfigKit v1.1.0 integration, requiring Go 1.27.0. Its
// canonical Command declaration installs the standard config command family
// through the core commandkit package. Applications can install CommandKit
// RoutingRule declarations alongside it through commandkit.New or
// App.Register. Source reports preserve ConfigKit's destination, placement,
// version, and empty-import evidence. Invocation reporting applies CommandKit's shared
// visibility and delivery policy; provider warnings remain independent of
// failure explanations. Importing ckconfig alone installs no commands.
// Package ckconfig adds commands to view, validate, explain, and compare
// ConfigKit configuration in CommandKit applications.
//
// Use AppCommand for one application configuration loader, or Command with a
// Suite for multiple named configurations and application-specific flags.
// Install the returned command with commandkit.New or App.Register.
//
// FromConfigKitSubtree adapts an ordinary typed loader and native path to a
// focused scope, retaining whole-load sources, findings, and validation.
// View.Paths selects native listing candidates; nil falls back to Metadata.
// Explicit paths and comparison retain upstream semantics.
//
// Importing this package alone installs no commands.
//
// ConfigKit owns configuration loading and interpretation. CommandKit formats
// reports and messages using its shared reporting policy.
package ckconfig

View File

@@ -2,20 +2,20 @@
## ConfigKit
Selected module: `go.maximumdirect.net/configkit` at `v1.1.0`.
Selected module: `go.maximumdirect.net/configkit` at `v1.4.0`.
Copyright (C) 2026 Eric Rakestraw
SPDX-License-Identifier: LGPL-3.0-or-later
License and notices: [LGPL v3.0](../../LICENSE) |
[LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/commit/191015e289d7f2b91abb9fdd9c4f2f5cf75b4de9/LICENSE).
[LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3/LICENSE).
[Source](https://forge.maximumdirect.net/base-layer/configkit/src/commit/191015e289d7f2b91abb9fdd9c4f2f5cf75b4de9).
[Source](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3).
## go-yaml v4
Selected module: `go.yaml.in/yaml/v4` at `v4.0.0-rc.6`.
Selected module: `go.yaml.in/yaml/v4` at `v4.0.0`.
Copyright 2006-2010 Kirill Simonov
@@ -25,25 +25,25 @@ Copyright 2025 The go-yaml Project Contributors
License and notices: [Apache 2.0](licenses/Apache-2.0.txt) |
[MIT](licenses/MIT.txt) |
[LICENSE](https://github.com/yaml/go-yaml/blob/1c17b9cee72bf81ae73a8be50fbd7dd3a9985125/LICENSE) |
[NOTICE](https://github.com/yaml/go-yaml/blob/1c17b9cee72bf81ae73a8be50fbd7dd3a9985125/NOTICE).
[LICENSE](https://github.com/yaml/go-yaml/blob/f2f9563503f11b7a60da0c532175dcc693ce8d5a/LICENSE) |
[NOTICE](https://github.com/yaml/go-yaml/blob/f2f9563503f11b7a60da0c532175dcc693ce8d5a/NOTICE).
[Source](https://github.com/yaml/go-yaml/tree/1c17b9cee72bf81ae73a8be50fbd7dd3a9985125).
[Source](https://github.com/yaml/go-yaml/tree/f2f9563503f11b7a60da0c532175dcc693ce8d5a).
## Cobra
Selected module: `github.com/spf13/cobra` at `v1.10.1`.
Selected module: `github.com/spf13/cobra` at `v1.10.2`.
SPDX-License-Identifier: Apache-2.0
License and notices: [Apache 2.0](licenses/Apache-2.0.txt) |
[LICENSE.txt](https://github.com/spf13/cobra/blob/7da941c3547e93b8c9f70bbd3befca79c6335388/LICENSE.txt).
[LICENSE.txt](https://github.com/spf13/cobra/blob/88b30ab89da2d0d0abb153818746c5a2d30eccec/LICENSE.txt).
[Source](https://github.com/spf13/cobra/tree/7da941c3547e93b8c9f70bbd3befca79c6335388).
[Source](https://github.com/spf13/cobra/tree/88b30ab89da2d0d0abb153818746c5a2d30eccec).
## pflag
Selected module: `github.com/spf13/pflag` at `v1.0.9`.
Selected module: `github.com/spf13/pflag` at `v1.1.0`.
Copyright (c) 2012 Alex Ogier. All rights reserved.
@@ -52,9 +52,9 @@ Copyright (c) 2012 The Go Authors. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) |
[LICENSE](https://github.com/spf13/pflag/blob/10438578954bba2527fe5cae3684d4532b064bbe/LICENSE).
[LICENSE](https://github.com/spf13/pflag/blob/f8a990678a6d44385313e9b19e40737f889f9b14/LICENSE).
[Source](https://github.com/spf13/pflag/tree/10438578954bba2527fe5cae3684d4532b064bbe).
[Source](https://github.com/spf13/pflag/tree/f8a990678a6d44385313e9b19e40737f889f9b14).
## go-md2man
@@ -116,8 +116,9 @@ root): `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
the core module. The release policy uses baseline
`e833faddf120c789a9b45348edaf75720de16348`; the remaining material uses baseline
the core module. The documentation policy uses baseline
`beb5f191470a9daef2383981a6bfd02232490ab4`; the release policy uses
`e833faddf120c789a9b45348edaf75720de16348`; the remaining material uses
`d84a38ebab26f048cafbe59a2246700c35d29843`.
Copyright (C) 2026 Eric Rakestraw
@@ -128,15 +129,19 @@ 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).
## go-yaml v3
Selected module: `gopkg.in/yaml.v3` at `v3.0.1` (transitive dependency).
Selected module: `go.yaml.in/yaml/v3` at `v3.0.4` (transitive dependency).
Copyright (c) 2006-2010 Kirill Simonov
@@ -146,46 +151,47 @@ Copyright 2011-2016 Canonical Ltd.
License and notices: [MIT](licenses/MIT.txt) |
[Apache 2.0](licenses/Apache-2.0.txt) |
[LICENSE](https://github.com/go-yaml/yaml/blob/f6f7691b1fdeb513f56608cd2c32c51f8194bf51/LICENSE) |
[NOTICE](https://github.com/go-yaml/yaml/blob/f6f7691b1fdeb513f56608cd2c32c51f8194bf51/NOTICE).
[LICENSE](https://github.com/yaml/go-yaml/blob/c3552c15f996075a7634df5159d9161c67bf3d76/LICENSE) |
[NOTICE](https://github.com/yaml/go-yaml/blob/c3552c15f996075a7634df5159d9161c67bf3d76/NOTICE).
[Source](https://github.com/go-yaml/yaml/tree/f6f7691b1fdeb513f56608cd2c32c51f8194bf51).
[Source](https://github.com/yaml/go-yaml/tree/c3552c15f996075a7634df5159d9161c67bf3d76).
## ReleaseKit
Selected module: `go.maximumdirect.net/releasekit` at `v0.9.0` (transitive Go tool requirement; not a runtime import).
Selected module: `go.maximumdirect.net/releasekit` at `v0.10.0` (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://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4/LICENSE).
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243/LICENSE).
[Source](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4).
[Source](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243).
## Goldmark
Selected module: `github.com/yuin/goldmark/v2` at `v2.1.6` (ReleaseKit tool dependency).
Selected module: `github.com/yuin/goldmark/v2` at `v2.1.16` (ReleaseKit tool dependency).
Copyright (c) 2019 Yusuke Inuzuka
SPDX-License-Identifier: MIT
License and notices: [MIT](licenses/MIT.txt) |
[LICENSE](https://github.com/yuin/goldmark/blob/a8d4ee5a0bd7d5493fdd1e339b4e75df92f8684c/LICENSE).
[LICENSE](https://github.com/yuin/goldmark/blob/c3f939122ba4dd6f80e05043ad195b82e77fcb41/LICENSE).
[Source](https://github.com/yuin/goldmark/tree/a8d4ee5a0bd7d5493fdd1e339b4e75df92f8684c).
[Source](https://github.com/yuin/goldmark/tree/c3f939122ba4dd6f80e05043ad195b82e77fcb41).
## Go modules
Selected module: `golang.org/x/mod` at `v0.40.0` (ReleaseKit tool dependency).
Selected module: `golang.org/x/mod` at `v0.43.0` (ReleaseKit tool dependency).
Copyright 2009 The Go Authors.
SPDX-License-Identifier: BSD-3-Clause
License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) |
[LICENSE](https://go.googlesource.com/mod/+/d3398d06de5fa5c71083d3d1c26f2cda73508e0f/LICENSE).
[LICENSE](https://go.googlesource.com/mod/+/d4f320b9266480df5ed3d791e0c68e64c58c5dde/LICENSE) |
[PATENTS](https://go.googlesource.com/mod/+/d4f320b9266480df5ed3d791e0c68e64c58c5dde/PATENTS).
[Source](https://go.googlesource.com/mod/+/d3398d06de5fa5c71083d3d1c26f2cda73508e0f).
[Source](https://go.googlesource.com/mod/+/d4f320b9266480df5ed3d791e0c68e64c58c5dde).

View File

@@ -0,0 +1,23 @@
# CommandKit ckconfig v0.10.0
CommandKit ckconfig v0.10.0 adopts ConfigKit v1.4.0 and adds native focused
configuration scopes. It continues to select CommandKit core v0.7.0 and Go
1.27.0 as the consumer minimum.
## Compatibility and upgrade
`FromConfigKitSubtree` adapts an application-owned typed result loader and a
ConfigKit path to the standard scope operations. Loading and validation cover
the whole result; focused output and comparison use native inspection while
sources and diagnostics retain whole-load context. See the
[consumer guide](../../../../docs/consumers/guide.md#configkit-scopes) and
[ConfigKit v1.4.0 notes](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/docs/releases/v1.4.0.md).
`View.Paths` optionally supplies native path-discovery candidates. When it is
nil, existing custom scopes continue to enumerate `View.Metadata`; metadata
still describes and filters candidates. The added exported field can break
positional `View` literals. Convert them to keyed literals before upgrading.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.10.0/integrations/ckconfig/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.10.0/integrations/ckconfig/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.10.0/integrations/ckconfig/docs/oss/attribution.md)

View File

@@ -0,0 +1,25 @@
# CommandKit ckconfig v0.11.0
CommandKit ckconfig v0.11.0 integrates core's help-only preflight signal.
Bare `config explain` continues to display help when neither `--path` nor
`--list` is supplied. It now has the same invocation-feature exemption as
explicit `--help`: no feature startup, usage summary, or execution-only feature
flag requirement. Configuration state factories and loaders remain uninvoked.
Real configuration operations retain their ordinary invocation-feature behavior,
including requested zero-usage summaries when no PromptKit execution occurs.
Invalid supplied values still produce usage errors.
## Compatibility and upgrade
This release selects CommandKit core v0.8.0; ConfigKit remains
v1.4.0 and the Go consumer minimum remains 1.27.0. Existing ckconfig assembly
signatures and scope contracts are unchanged. ckconfig itself adds no token-usage
flag; that capability is installed by a nonempty ckprompt family.
ckprompt v0.12.0 follows this release under the dependency-alignment policy.
See the [consumer guide](../../../../docs/consumers/guide.md#configkit-scopes).
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.11.0/integrations/ckconfig/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.11.0/integrations/ckconfig/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.11.0/integrations/ckconfig/docs/oss/attribution.md)

View File

@@ -0,0 +1,24 @@
# CommandKit ckconfig v0.4.0
CommandKit ckconfig v0.4.0 requires `go.maximumdirect.net/commandkit v0.4.0`,
ConfigKit v1.1.0, and Go 1.27.0. Configuration commands use core's shared
text, YAML, and JSON reporting and universal `--format` flag.
Scopes can expose metadata-backed path discovery and focused values, filtered
source evidence, and detailed validation and comparison reports. Validation
retains available evidence after a failed load and reports reached scopes in
one result. Aggregate configuration display is one scope-keyed mapping.
Applications opt into transient CLI overrides only when their loader forwards
them to ConfigKit; `--set` and `--against-set` select the comparison sides.
Application-declared right-side selectors let each side use independent
inputs. `config diff --check` returns status 3 when native differences exist.
This pre-1.0 minor release changes configuration report formatting and
aggregate framing, and comparison selectors now apply independently to each
side. Update callers and report consumers to the current
[CLI reference](../../../../docs/cli.md#configuration-scopes) and
[consumer guide](../../../../docs/consumers/guide.md#configkit-scopes).
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.4.0/integrations/ckconfig/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.4.0/integrations/ckconfig/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.4.0/integrations/ckconfig/docs/oss/attribution.md)

View File

@@ -0,0 +1,39 @@
# CommandKit ckconfig v0.5.0
CommandKit ckconfig v0.5.0 improves configuration explanations, preserves
available inspection evidence after loader failures, and uses CommandKit core
v0.5.0 for reporting and input handling. ConfigKit remains at v1.1.0, and the
consumer minimum remains Go 1.27.0.
## Changes
- Configuration explanations render the same acquired evidence in text, YAML,
and JSON, including available field metadata, history, and source labels.
- Failed loads retain available ConfigKit result evidence for inspection.
Cancellation during aggregate configuration display remains an operation
failure rather than being reported as a rendering failure.
- The new `AdaptDiagnostics` helper captures native ConfigKit diagnostics for
CLI presentation. Both standard integrations use the same adapter.
- Validation and path discovery avoid rebuilding filter sets and subtree
prefixes repeatedly. Scope setup and operation preparation are simpler,
preserving independent comparison inputs and existing CLI behavior.
## Compatibility and upgrade
Select `go.maximumdirect.net/ckconfig v0.5.0` with CommandKit core v0.5.0.
Custom `ExplanationReader` implementations need only `Explain`; the interface
no longer requires `WriteExplanation`. CommandKit renders the acquired evidence
instead of invoking a provider's text writer. Applications that customized that
writer should review their text output.
Effective configuration writers supply one safe YAML document. Conversion
preserves resolved scalar types rather than formatting or comments. Core
v0.5.0 preserves numeric-looking strings and explicit numeric tags; review
callers that relied on automatic conversion of strings into numbers.
See the [configuration CLI reference](../../../../docs/cli.md#configuration-scopes)
and [consumer guide](../../../../docs/consumers/guide.md#configkit-scopes).
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.5.0/integrations/ckconfig/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.5.0/integrations/ckconfig/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.5.0/integrations/ckconfig/docs/oss/attribution.md)

View File

@@ -0,0 +1,16 @@
# CommandKit ckconfig v0.6.0
CommandKit ckconfig v0.6.0 selects CommandKit core v0.6.0, which supports
shared debug input bindings and access to the selected reporting mode.
ConfigKit remains at v1.1.0.
## Compatibility and upgrade
Select `go.maximumdirect.net/ckconfig v0.6.0` with CommandKit core v0.6.0.
The consumer minimum remains Go 1.27.0. See the
[consumer guide](../../../../docs/consumers/guide.md#invocation-reporting)
for the new core reporting and debug input APIs.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.6.0/integrations/ckconfig/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.6.0/integrations/ckconfig/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.6.0/integrations/ckconfig/docs/oss/attribution.md)

View File

@@ -0,0 +1,20 @@
# CommandKit ckconfig v0.7.0
CommandKit ckconfig v0.7.0 adopts ConfigKit v1.2.0. Application-owned loaders
can select main-relative companion imports and overlay contexts through
ConfigKit's public APIs, then expose the resulting configuration through
ckconfig's existing scope adapter. [ConfigKit v1.2.0 release notes](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.2.0/docs/releases/v1.2.0.md)
## Compatibility and upgrade
Select `go.maximumdirect.net/ckconfig v0.7.0` with CommandKit core v0.6.0.
The consumer minimum is Go 1.27.0.
Application loaders constructing ConfigKit `Input` or `LayeredOptions` must use
field-named struct literals to accommodate the fields added upstream. See the
[consumer guide](../../../../docs/consumers/guide.md#module-selection) for module
selection and loader guidance.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.7.0/integrations/ckconfig/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.7.0/integrations/ckconfig/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.7.0/integrations/ckconfig/docs/oss/attribution.md)

View File

@@ -0,0 +1,19 @@
# CommandKit ckconfig v0.8.0
CommandKit ckconfig v0.8.0 classifies identifiable invalid ConfigKit input as a
usage failure. The new `ClassifyConfigurationError` function exposes the same
CLI classification for callers building their own outcomes.
## Compatibility and upgrade
Select `go.maximumdirect.net/ckconfig v0.8.0` with CommandKit core v0.6.0. The
consumer minimum remains Go 1.27.0. Standard configuration commands now return
status `2` for diagnostic evidence identifying invalid configuration input;
previously these loading failures returned status `1`. Update scripts that
interpret those statuses. Cancellation, operational failures, and ambiguous or
unknown evidence remain status `1`. See the [CLI contract](../../../../docs/cli.md#configuration-failure-classification)
and the [classifier GoDoc](../../errors.go) for details.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.8.0/integrations/ckconfig/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.8.0/integrations/ckconfig/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.8.0/integrations/ckconfig/docs/oss/attribution.md)

View File

@@ -0,0 +1,23 @@
# CommandKit ckconfig v0.9.0
CommandKit ckconfig v0.9.0 aligns with CommandKit core v0.7.0 and adopts
ConfigKit v1.2.1 and stable go-yaml v4.0.0.
## Compatibility and upgrade
Select `go.maximumdirect.net/ckconfig v0.9.0` with CommandKit core v0.7.0.
The consumer minimum remains Go 1.27.0. ConfigKit v1.2.1 includes the loader
adaptation for stable go-yaml. Applications continue to use the existing
configuration scope, loader, and classification APIs. See the
[consumer guide](../../../../docs/consumers/guide.md#configkit-scopes) and
[ConfigKit release notes](https://forge.maximumdirect.net/base-layer/configkit/src/commit/51ef3144158db1a09fabdbd1c7ae59908c84923b/docs/releases/v1.2.1.md).
The selected core updates Cobra to v1.10.2 and pflag to v1.1.0. Review scripts
that depend on exact backend diagnostic or help text. Identifiable invalid
configuration input continues to select status `2`, while operational failures
and cancellation select status `1` under the
[configuration-failure contract](../../../../docs/cli.md#configuration-failure-classification).
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.9.0/integrations/ckconfig/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.9.0/integrations/ckconfig/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.9.0/integrations/ckconfig/docs/oss/attribution.md)

View File

@@ -0,0 +1,102 @@
package ckconfig
import (
"context"
"errors"
"go.maximumdirect.net/commandkit"
"go.maximumdirect.net/configkit"
)
// ClassifyConfigurationError selects a CLI outcome from ConfigKit loading
// diagnostics. A nil error is success. A loading error is usage only when it
// contains at least one error diagnostic and all error diagnostics identify
// invalid configuration input; warnings are ignored. Unknown evidence and
// other errors are operational. Wrappers and joined errors are inspected, and
// any operational branch, cancellation, or deadline takes precedence.
// The caller remains responsible for constructing an outcome and its cause.
func ClassifyConfigurationError(err error) commandkit.OutcomeKind {
if err == nil {
return commandkit.OutcomeSuccess
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return commandkit.OutcomeOperational
}
return classifyConfigurationTree(err)
}
func classifyConfigurationTree(err error) commandkit.OutcomeKind {
if load, ok := err.(*configkit.LoadError); ok {
if load == nil {
return commandkit.OutcomeOperational
}
return classifyConfigurationDiagnostics(load.Diagnostics())
}
switch wrapped := err.(type) {
case interface{ Unwrap() []error }:
found := false
for _, child := range wrapped.Unwrap() {
if child == nil {
continue
}
found = true
if classifyConfigurationTree(child) != commandkit.OutcomeUsage {
return commandkit.OutcomeOperational
}
}
if found {
return commandkit.OutcomeUsage
}
case interface{ Unwrap() error }:
if child := wrapped.Unwrap(); child != nil {
return classifyConfigurationTree(child)
}
}
return commandkit.OutcomeOperational
}
func classifyConfigurationDiagnostics(diagnostics []configkit.Diagnostic) commandkit.OutcomeKind {
found := false
for _, diagnostic := range diagnostics {
switch diagnostic.Severity {
case configkit.SeverityWarning:
continue
case configkit.SeverityError:
found = true
if !configurationInputCode(diagnostic.Code) {
return commandkit.OutcomeOperational
}
default:
return commandkit.OutcomeOperational
}
}
if found {
return commandkit.OutcomeUsage
}
return commandkit.OutcomeOperational
}
func configurationInputCode(code configkit.Code) bool {
switch code {
case configkit.CodeYAMLInvalid, configkit.CodeYAMLEmpty, configkit.CodeYAMLMultipleDocuments,
configkit.CodeYAMLRootType, configkit.CodeYAMLDuplicateKey, configkit.CodeYAMLTag,
configkit.CodeYAMLAnchor, configkit.CodeYAMLAlias, configkit.CodeYAMLMergeKey,
configkit.CodeYAMLScalar, configkit.CodeYAMLDepthLimit, configkit.CodeYAMLNodeLimit,
configkit.CodeDecodeType, configkit.CodeDecodeNull, configkit.CodeDecodeRange,
configkit.CodeDecodeDuration, configkit.CodeDecodeText, configkit.CodeDecodeUnknownField,
configkit.CodeDecodeArrayLength, configkit.CodeSourceLimitExceeded,
configkit.CodeImportDisabled, configkit.CodeImportCycle, configkit.CodeImportRepeated,
configkit.CodeImportVersion, configkit.CodeSequenceInvalid, configkit.CodeSequenceConflict,
configkit.CodeComposeInvalid, configkit.CodeComposeConflict, configkit.CodeUnderlayVersion,
configkit.CodeOverlayVersion, configkit.CodeOverlayRepeated, configkit.CodeOverlayDirective,
configkit.CodeVersionType, configkit.CodeVersionError, configkit.CodeResolveError,
configkit.CodeValidateError, configkit.CodeInheritanceInvalid, configkit.CodeInheritanceMissing,
configkit.CodeInheritanceCycle, configkit.CodeInheritanceVersion, configkit.CodeOverrideInvalidPath,
configkit.CodeOverrideDuplicate, configkit.CodeOverrideOverlap, configkit.CodeOverrideDirective,
configkit.CodeOverrideVersion, configkit.CodeOverrideLimitExceeded, configkit.CodeSecretRequired,
configkit.CodeSecretInvalidName:
return true
default:
return false
}
}

View File

@@ -0,0 +1,93 @@
package ckconfig
import (
"context"
"errors"
"fmt"
"testing"
"go.maximumdirect.net/commandkit"
"go.maximumdirect.net/configkit"
)
func TestConfigurationDiagnosticClassification(t *testing.T) {
usageCodes := []configkit.Code{
configkit.CodeYAMLInvalid, configkit.CodeYAMLEmpty, configkit.CodeYAMLMultipleDocuments, configkit.CodeYAMLRootType, configkit.CodeYAMLDuplicateKey, configkit.CodeYAMLTag, configkit.CodeYAMLAnchor, configkit.CodeYAMLAlias, configkit.CodeYAMLMergeKey, configkit.CodeYAMLScalar, configkit.CodeYAMLDepthLimit, configkit.CodeYAMLNodeLimit,
configkit.CodeDecodeType, configkit.CodeDecodeNull, configkit.CodeDecodeRange, configkit.CodeDecodeDuration, configkit.CodeDecodeText, configkit.CodeDecodeUnknownField, configkit.CodeDecodeArrayLength, configkit.CodeSourceLimitExceeded,
configkit.CodeImportDisabled, configkit.CodeImportCycle, configkit.CodeImportRepeated, configkit.CodeImportVersion, configkit.CodeSequenceInvalid, configkit.CodeSequenceConflict, configkit.CodeComposeInvalid, configkit.CodeComposeConflict, configkit.CodeUnderlayVersion, configkit.CodeOverlayVersion, configkit.CodeOverlayRepeated, configkit.CodeOverlayDirective,
configkit.CodeVersionType, configkit.CodeVersionError, configkit.CodeResolveError, configkit.CodeValidateError, configkit.CodeInheritanceInvalid, configkit.CodeInheritanceMissing, configkit.CodeInheritanceCycle, configkit.CodeInheritanceVersion, configkit.CodeOverrideInvalidPath, configkit.CodeOverrideDuplicate, configkit.CodeOverrideOverlap, configkit.CodeOverrideDirective, configkit.CodeOverrideVersion, configkit.CodeOverrideLimitExceeded, configkit.CodeSecretRequired, configkit.CodeSecretInvalidName,
}
for _, code := range usageCodes {
t.Run(string(code), func(t *testing.T) {
ds := []configkit.Diagnostic{{Severity: configkit.SeverityWarning, Code: configkit.CodeSourceRead}, {Severity: configkit.SeverityError, Code: code}}
if got := classifyConfigurationDiagnostics(ds); got != commandkit.OutcomeUsage {
t.Fatalf("got %s", got)
}
})
}
for _, code := range []configkit.Code{configkit.CodeSourceMissing, configkit.CodeSourcePermission, configkit.CodeImportInvalid, configkit.CodeImportOutsideRoot, configkit.CodeImportLimitExceeded, configkit.CodeOverlayInvalid, configkit.CodeOverlayOutsideRoot, configkit.CodeOverlayLimitExceeded, configkit.CodeSchemaRoot, configkit.CodeOptionsInvalid, configkit.CodeHistoryLimitExceeded, configkit.CodeResolveHookFailed, configkit.CodeValidateMutation, configkit.CodeOverrideInvalidLabel, configkit.CodeOverrideInvalidValue, configkit.CodeSecretUnset, configkit.CodeSecretEmpty, configkit.CodeSecretsMissing, "future.code"} {
t.Run(string(code), func(t *testing.T) {
ds := []configkit.Diagnostic{{Severity: configkit.SeverityError, Code: configkit.CodeYAMLInvalid}, {Severity: configkit.SeverityError, Code: code}}
if got := classifyConfigurationDiagnostics(ds); got != commandkit.OutcomeOperational {
t.Fatalf("got %s", got)
}
})
}
for _, ds := range [][]configkit.Diagnostic{nil, {{Severity: configkit.SeverityWarning, Code: configkit.CodeYAMLInvalid}}, {{Severity: "future", Code: configkit.CodeYAMLInvalid}}, {{Severity: configkit.SeverityError, Code: configkit.CodeYAMLInvalid}, {Severity: "future"}}} {
if got := classifyConfigurationDiagnostics(ds); got != commandkit.OutcomeOperational {
t.Fatalf("%v: got %s", ds, got)
}
}
}
type emptyChildren struct{}
func (emptyChildren) Error() string { return "empty" }
func (emptyChildren) Unwrap() []error { return nil }
func TestClassifyConfigurationError(t *testing.T) {
_, invalid := configkit.Load[map[string]any](configkit.Bytes("invalid", []byte("broken: [")))
_, missing := configkit.Load[map[string]any](configkit.File("/nonexistent-commandkit-classifier-test"))
var load *configkit.LoadError
if !errors.As(invalid, &load) || load == nil {
t.Fatalf("invalid fixture: %v", invalid)
}
if missing == nil {
t.Fatal("missing fixture unexpectedly succeeded")
}
var typedNil *configkit.LoadError
opaque := errors.New("opaque")
cases := []struct {
name string
err error
want commandkit.OutcomeKind
}{
{"nil", nil, commandkit.OutcomeSuccess},
{"invalid", invalid, commandkit.OutcomeUsage},
{"wrapped", fmt.Errorf("wrapped: %w", invalid), commandkit.OutcomeUsage},
{"all input", errors.Join(invalid, fmt.Errorf("wrapped: %w", invalid)), commandkit.OutcomeUsage},
{"mixed first", errors.Join(missing, invalid), commandkit.OutcomeOperational},
{"mixed last", errors.Join(invalid, missing), commandkit.OutcomeOperational},
{"nested", errors.Join(invalid, errors.Join(invalid, opaque)), commandkit.OutcomeOperational},
{"canceled", errors.Join(invalid, context.Canceled), commandkit.OutcomeOperational},
{"deadline", fmt.Errorf("deadline: %w", context.DeadlineExceeded), commandkit.OutcomeOperational},
{"missing", missing, commandkit.OutcomeOperational},
{"opaque", opaque, commandkit.OutcomeOperational},
{"empty load", &configkit.LoadError{}, commandkit.OutcomeOperational},
{"typed nil", typedNil, commandkit.OutcomeOperational},
{"empty children", emptyChildren{}, commandkit.OutcomeOperational},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := ClassifyConfigurationError(tc.err); got != tc.want {
t.Fatalf("got %s, want %s", got, tc.want)
}
if errors.Is(tc.err, invalid) {
var got *configkit.LoadError
if !errors.As(tc.err, &got) || got == nil {
t.Fatal("load identity lost")
}
}
})
}
}

View File

@@ -1,37 +1,90 @@
# Simple consumer
# ConfigKit example
This example imports `go.maximumdirect.net/ckconfig` and
`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.
This example adds configuration inspection and a custom `greet` command to a
small application. It uses local fixtures and in-memory defaults, with no
external services. See [module selection](../../../../docs/consumers/guide.md#module-selection)
for dependencies and Go requirements. Use Go 1.27.0 on `PATH` for this checkout.
Run the maintained example with:
From the repository root:
```sh
cd integrations/ckconfig/examples/simple
export GOWORK=off GOTOOLCHAIN=local
go run . config show
go run . config show --config fixtures/before.yml --verbose
go run . config show --config fixtures/before.yml --quiet
```
The output includes the default greeting, `Hello`, and schema version 2.
This example can run against its declared released dependencies with the
workspace disabled.
## Inspect and override a value
```sh
# Discover configuration paths under schema.
go run . config explain --list --under /schema
# Change the greeting for this invocation and show just that value.
go run . config show --path /greeting --set '/greeting="Hi"'
```
The second command prints `Hi`. It does not edit a file.
## Compare configurations
```sh
go run . config diff --config fixtures/before.yml --against-config fixtures/after.yml
```
The report includes `changes.greeting: Goodbye`.
```sh
# Expected status 3: the overridden greeting differs from the ordinary default.
go run . config diff --set '/greeting="Hi"' --details --check
```
This compares the overridden left side with ordinary configuration on the
right. `go run` prints `exit status 3` and itself exits with status 1; a built
executable returns the application's status 3 directly.
## Inspect warnings and failed loads
```sh
# Schema version 1 produces a warning, visible in verbose mode.
go run . config show --config fixtures/before.yml --verbose
# Quiet mode hides the configuration report and warning.
go run . config show --config fixtures/before.yml --quiet
```
Ordinary mode hides the warning but still displays configuration.
```sh
# Intentional failure: show detailed validation findings for the invalid fixture.
go run . config validate --config fixtures/invalid.yml --details --severity error
# Intentional failure: still show the source recorded before loading failed.
go run . config sources --config fixtures/invalid.yml --source-id source-1
```
Both commands retain the load failure. `source-1` belongs to this fixture's
load; other configurations can have different source IDs. See the
[CLI reference](../../../../docs/cli.md#configuration-scopes) for report and status rules.
## Try a custom command
```sh
go run . greet
go run . greet --count=0 --tag=first --tag second
```
The `config` family comes from one typed ConfigKit scope. The custom `greet`
command uses CommandKit's typed bindings and shows the difference between an
omitted `--count` and an explicitly supplied zero, plus ordered repeated tags.
With no `--config`, application settings use the in-memory default. A supplied
configuration and overlay are passed to ConfigKit unchanged. The comparison
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.
The handler reports its greeting, count, and tags. It distinguishes an omitted
count from an explicitly supplied zero and preserves repeated tag order.
## How it is wired
One ConfigKit scope supplies the standard `config` commands. Without `--config`,
its loader uses an in-memory default. Supplied configuration and overlay values
are passed to ConfigKit unchanged. The scope enables temporary overrides and
passes them into its ordinary ConfigKit load. The
[consumer guide](../../../../docs/consumers/guide.md#configkit-scopes) explains
loader and scope setup.
Run `GOWORK=off GOTOOLCHAIN=local go test ./...` from this example directory to
check it against its declared dependencies.

View File

@@ -176,11 +176,11 @@ func TestSimpleFailedLoadReportsEvidence(t *testing.T) {
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"`) {
if outcome.Kind != commandkit.OutcomeUsage || !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") {
if outcome.Kind != commandkit.OutcomeUsage || !strings.Contains(output, `"id":`) || !strings.Contains(output, "invalid.yml") {
t.Fatalf("source failure = %#v %q", outcome, output)
}
}

View File

@@ -1,7 +1,6 @@
package ckconfig
import (
"bytes"
"fmt"
"strings"
"text/template"
@@ -18,6 +17,7 @@ type explanationReport struct {
History []explanationChangeDTO `json:"history"`
SecretReference *secretReferenceDTO `json:"secret_reference"`
Metadata *explanationMetadata `json:"metadata,omitempty"`
Sources []validationSource `json:"sources,omitempty"`
}
type explanationMetadata struct {
@@ -48,6 +48,29 @@ type pathMetadata struct {
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))
var explanationTemplate = template.Must(commandkit.ParseTextTemplate("explanation", `Scope: {{.Scope}}
Path: {{printf "%q" .Path}}
Effective: {{template "snapshot" .Effective}}
Origin: {{template "origin" .Origin}}
History:
{{range .History}} Before: {{template "snapshot" .Before}}
After: {{template "snapshot" .After}}
Origin: {{template "origin" .Origin}}
Reasons: {{range .Reasons}}{{printf "%q " .}}{{end}}
Dependencies: {{range .Dependencies}}{{printf "%q " .}}{{end}}
{{end}}{{with .SecretReference}}Secret reference: {{.Name}}
{{end}}{{with .Metadata}}{{if .Explicit}}Explicit: {{.Explicit}}
Null: {{.Null}}
{{end}}{{range .History}}Metadata history: {{printf "%q" .Path}}
{{range .Previous}} Previous origin: {{template "origin" .}}
{{end}}{{end}}{{end}}{{with .Sources}}Sources:
{{range .}} {{printf "%q" .ID}}: label={{printf "%q" .Label}} path={{printf "%q" .Path}}
{{end}}{{end}}{{define "snapshot"}}present={{.Present}} redacted={{.Redacted}} yaml={{printf "%q" .YAML}}{{end}}
{{- define "locations"}}{{range .}} {{printf "%q" .SourceID}}:{{.Line}}:{{.Column}}{{end}}{{end}}
{{- define "origin"}}layer={{printf "%q" .Layer}} operation={{printf "%q" .Operation}} locations:{{template "locations" .Locations}}
{{range .Inheritance}} Inheritance: from={{printf "%q" .From}} to={{printf "%q" .To}} reference={{printf "%q" .Reference}} locations:{{template "locations" .Locations}}
{{end}}{{end}}`, nil))
type snapshotDTO struct {
Present bool `json:"present"`
Redacted bool `json:"redacted"`
@@ -85,11 +108,11 @@ func runConfigExplanation[I, S any](invocation commandkit.Invocation, plan *conf
name := selected.scope.scope.Name
reporter := invocation.Reporter()
if err := invocation.Context.Err(); err != nil {
return configFailure("Configuration explanation was canceled.", commandkit.Explanation{}, err)
return configFailure(invocation.Context, "Configuration explanation was canceled.", commandkit.Explanation{}, err)
}
if selected.scope.scope.Acquire == nil {
cause := fmt.Errorf("configuration scope %q has no acquisition callback", name)
return configFailure(fmt.Sprintf("Unable to explain configuration scope %q.", name), commandkit.Explanation{}, cause)
return configFailure(invocation.Context, fmt.Sprintf("Unable to explain configuration scope %q.", name), commandkit.Explanation{}, cause)
}
acquired, acquireErr := selected.scope.scope.Acquire(invocation.Context, Request{
Operation: Explain,
@@ -97,18 +120,27 @@ func runConfigExplanation[I, S any](invocation commandkit.Invocation, plan *conf
}, selected.input, state)
queueConfigAcquisition(reporter, acquired)
if acquireErr != nil {
return configFailure(fmt.Sprintf("Unable to explain configuration scope %q.", name), acquired.Explanation, acquireErr)
return configFailure(invocation.Context, 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)
return configFailure(invocation.Context, "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))
return configFailure(invocation.Context, "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) {
var prefix []string
if plan.under != nil {
prefix = pointerTokens(plan.under.String())
}
paths := acquired.Value.Paths
if paths == nil {
paths = acquired.Value.Metadata
}
for _, path := range paths.HistoricalPaths() {
pointer := path.String()
if plan.under != nil && !pathWithin(pointer, prefix) {
continue
}
info, present := acquired.Value.Metadata.Lookup(path)
@@ -118,7 +150,7 @@ func runConfigExplanation[I, S any](invocation commandkit.Invocation, plan *conf
if present && plan.explicit.Set && info.Explicit != plan.explicit.Value {
continue
}
entry := pathDiscoveryEntry{Path: path.String(), Present: present}
entry := pathDiscoveryEntry{Path: pointer, Present: present}
if present {
entry.Metadata = &pathMetadata{Explicit: info.Explicit}
}
@@ -129,16 +161,16 @@ func runConfigExplanation[I, S any](invocation commandkit.Invocation, plan *conf
}
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)
return configFailure(invocation.Context, "Configuration scope did not provide explanation data.", acquired.Explanation, cause)
}
explanation, found := acquired.Value.Explanation.Explain(plan.path)
if !found {
cause := fmt.Errorf("configuration path %q is not known in scope %q", plan.path.String(), name)
return configFailure("The requested configuration path is not available.", acquired.Explanation, cause)
return configFailure(invocation.Context, "The requested configuration path is not available.", acquired.Explanation, cause)
}
if err := invocation.Context.Err(); err != nil {
return configFailure("Configuration explanation was canceled.", acquired.Explanation, err)
return configFailure(invocation.Context, "Configuration explanation was canceled.", acquired.Explanation, err)
}
report := makeExplanationReport(name, explanation)
if acquired.Value.Metadata != nil {
@@ -157,31 +189,27 @@ func runConfigExplanation[I, S any](invocation commandkit.Invocation, plan *conf
report.Metadata = metadata
}
}
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)
if acquired.Value.Sources != nil {
for _, source := range acquired.Value.Sources.Sources() {
report.Sources = append(report.Sources, validationSource{ID: source.ID, Label: source.Label, Path: source.Path})
}
return output.String(), err
},
}))
renderErr := reporter.Report(commandkit.Report{Value: report, TextTemplate: text})
}
renderErr := reporter.Report(commandkit.Report{Value: report, TextTemplate: explanationTemplate})
if renderErr != nil && invocation.Context.Err() != nil {
return configFailure("Configuration explanation was canceled.", acquired.Explanation, invocation.Context.Err())
return configFailure(invocation.Context, "Configuration explanation was canceled.", acquired.Explanation, invocation.Context.Err())
}
return commandkit.Success()
}
func pathWithin(path, parent configkit.Path) bool {
tokens := func(value string) []string {
func pointerTokens(value string) []string {
if value == "" {
return nil
}
return strings.Split(strings.TrimPrefix(value, "/"), "/")
}
child, prefix := tokens(path.String()), tokens(parent.String())
}
func pathWithin(path string, prefix []string) bool {
child := pointerTokens(path)
if len(prefix) > len(child) {
return false
}

View File

@@ -91,18 +91,16 @@ func captureSuite[I, S any](suite Suite[I, S]) *preparedSuite[I, S] {
byName: make(map[string]*preparedScope[I, S], len(suite.Scopes)),
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 := captureConfigScopes(prepared, suite.Scopes)
selectors, against := captureConfigSelectors(prepared, suite.Selectors, seenNames)
captureOperationBindings(prepared, selectors, against)
captureScopeInventory(prepared)
return prepared
}
seenNames := make(map[string]struct{}, len(suite.Scopes))
for _, original := range suite.Scopes {
func captureConfigScopes[I, S any](prepared *preparedSuite[I, S], scopes []Scope[I, S]) map[string]struct{} {
seenNames := make(map[string]struct{}, len(scopes))
for _, original := range scopes {
scope := original
scope.Operations = normalizeOperations(scope.Operations, &prepared.issues, scope.Name)
scope.issues = append([]error(nil), original.issues...)
@@ -146,6 +144,20 @@ func captureSuite[I, S any](suite Suite[I, S]) *preparedSuite[I, S] {
}
prepared.scopeChoices = joinNames(names)
return seenNames
}
func captureConfigSelectors[I, S any](prepared *preparedSuite[I, S], originals []Selector[I], seenNames map[string]struct{}) ([]Selector[I], []commandkit.Flag[I]) {
selectors := make([]Selector[I], len(originals))
against := make([]commandkit.Flag[I], len(originals))
for index, selector := range originals {
selector.Scopes = append([]string(nil), selector.Scopes...)
selectors[index] = selector
if selector.AgainstName != "" {
against[index] = commandkit.RenameFlag(selector.Binding, selector.AgainstName)
}
}
for index, selector := range selectors {
seen := make(map[string]struct{}, len(selector.Scopes))
uniqueScopes := make([]string, 0, len(selector.Scopes))
@@ -181,6 +193,10 @@ func captureSuite[I, S any](suite Suite[I, S]) *preparedSuite[I, S] {
}
}
return selectors, against
}
func captureOperationBindings[I, S any](prepared *preparedSuite[I, S], selectors []Selector[I], against []commandkit.Flag[I]) {
for _, operation := range []Operation{Validate, Show, Sources, Explain, Diff} {
for _, scope := range prepared.scopes {
if containsOperation(scope.scope.Operations, operation) {
@@ -200,6 +216,9 @@ func captureSuite[I, S any](suite Suite[I, S]) *preparedSuite[I, S] {
}
}
}
}
func captureScopeInventory[I, S any](prepared *preparedSuite[I, S]) {
for _, scope := range prepared.scopes {
prepared.inventory.Scopes = append(prepared.inventory.Scopes, scopeMetadata{
Name: scope.scope.Name,
@@ -207,7 +226,6 @@ func captureSuite[I, S any](suite Suite[I, S]) *preparedSuite[I, S] {
Features: featureNames(scope.scope.Features),
})
}
return prepared
}
func normalizeOperations(operations []Operation, issues *[]error, scope string) []Operation {

View File

@@ -3,10 +3,12 @@ package ckconfig
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"reflect"
"slices"
"strings"
"testing"
@@ -478,18 +480,55 @@ func TestExplainParsesBeforeAcquisitionAndPreservesNativeSafeHistory(t *testing.
}
}
func TestExplainTracksNativeRenderFailureWithoutReplacingOperationCause(t *testing.T) {
renderErr := errors.New("native explanation renderer failed")
reader := &failingNativeExplanation{err: renderErr}
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{{
Name: "app", Operations: []Operation{Explain}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
return commandkit.Acquired[View]{Value: View{Explanation: reader}}, nil
},
}}}))
func TestExplainUsesAcquiredEvidenceAcrossFormats(t *testing.T) {
result, err := configkit.Load(configkit.Mapping("original source", map[string]any{"token": "before"}), configkit.Options[map[string]any]{Overrides: []configkit.Override{{Path: configkit.Keys("token"), Value: "after", Flag: "--fixture-set"}}})
if err != nil {
t.Fatal(err)
}
path := configkit.Keys("token")
explanation, found := result.Explain(path)
if !found {
t.Fatal("missing fixture explanation")
}
metadata := result.Metadata()
reader := &nativeExplanation{value: explanation, found: true}
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{{Name: "tenant", Operations: []Operation{Explain, Show}, Features: ScopeFeatures{PathShow: true}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
return commandkit.Acquired[View]{Value: View{Explanation: reader, Metadata: &metadata, Sources: result}}, nil
}}}}))
var focused bytes.Buffer
show := app.Execute(context.Background(), []string{"config", "show", "--scope=tenant", "--path=/token", "--format=json"}, commandkit.Streams{Out: &focused, Err: io.Discard})
if show.Kind != commandkit.OutcomeSuccess || strings.TrimSpace(focused.String()) != `"after"` {
t.Fatalf("focused show = %#v %q", show, focused.String())
}
for _, format := range []string{"text", "yaml", "json"} {
t.Run(format, func(t *testing.T) {
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.Len() != 0 {
t.Fatalf("native explanation failure outcome/output = %#v / %q", outcome, output.String())
outcome := app.Execute(context.Background(), []string{"config", "explain", "--scope=tenant", "--path=/token", "--format=" + format}, commandkit.Streams{Out: &output, Err: io.Discard})
if outcome.Status != 0 {
t.Fatalf("outcome=%#v output=%s", outcome, output.String())
}
for _, evidence := range []string{"tenant", "/token", "before", "after", "original source", "--fixture-set"} {
if !strings.Contains(output.String(), evidence) {
t.Errorf("missing %q: %s", evidence, output.String())
}
}
if format == "json" {
var report explanationReport
if err := json.Unmarshal(output.Bytes(), &report); err != nil {
t.Fatal(err)
}
if report.Metadata == nil || report.Metadata.Explicit == nil || !*report.Metadata.Explicit || !slices.ContainsFunc(report.Metadata.History, func(record metadataHistoryRecord) bool { return len(record.Previous) > 0 }) {
t.Fatalf("missing metadata: %#v", report.Metadata)
}
} else if format == "text" && (!strings.Contains(output.String(), "Previous origin:") || !strings.Contains(output.String(), "Explicit: true")) {
t.Fatalf("missing text metadata: %s", output.String())
}
writeErr := errors.New("output failed")
outcome = app.Execute(context.Background(), []string{"config", "explain", "--scope=tenant", "--path=/token", "--format=" + format}, commandkit.Streams{Out: failingOutput{err: writeErr}, Err: io.Discard})
if outcome.Status != 1 || outcome.Cause != nil || !errors.Is(outcome.Presentation.Output.WriteError, writeErr) {
t.Fatalf("delivery failure = %#v", outcome)
}
})
}
}
@@ -552,30 +591,11 @@ type nativeExplanation struct {
found bool
}
type failingNativeExplanation struct{ err error }
func (reader *failingNativeExplanation) Explain(configkit.Path) (configkit.Explanation, bool) {
return configkit.Explanation{}, true
}
func (reader *failingNativeExplanation) WriteExplanation(writer io.Writer, _ configkit.Path) error {
if _, err := io.WriteString(writer, "partial native explanation\n"); err != nil {
return err
}
return reader.err
}
func (reader *nativeExplanation) Explain(path configkit.Path) (configkit.Explanation, bool) {
reader.path = path
return reader.value, reader.found
}
func (reader *nativeExplanation) WriteExplanation(writer io.Writer, path configkit.Path) error {
reader.path = path
_, err := fmt.Fprintf(writer, "Explanation for %q\n", path.String())
return err
}
type failingOutput struct{ err error }
func (writer failingOutput) Write(value []byte) (int, error) {

View File

@@ -3,13 +3,13 @@ module go.maximumdirect.net/ckconfig
go 1.27.0
require (
go.maximumdirect.net/commandkit v0.3.0
go.maximumdirect.net/configkit v1.1.0
go.yaml.in/yaml/v4 v4.0.0-rc.6
go.maximumdirect.net/commandkit v0.8.0
go.maximumdirect.net/configkit v1.4.0
go.yaml.in/yaml/v4 v4.0.0
)
require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/cobra v1.10.1 // indirect
github.com/spf13/pflag v1.0.9 // indirect
github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.1.0 // indirect
)

View File

@@ -2,15 +2,18 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.10.1 h1:lJeBwCfmrnXthfAupyUTzJ/J4Nc1RsHC/mSRU2dll/s=
github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
go.maximumdirect.net/commandkit v0.3.0 h1:RCmg2GS8uzlLSJCIqarpn1uFDec0W3ylNNRRPT6kUFE=
go.maximumdirect.net/commandkit v0.3.0/go.mod h1:ZS98DewKNVBygKVDoh5MFD09CnPlP37dS9pVsID5Eoc=
go.maximumdirect.net/configkit v1.1.0 h1:UzXN2ZMnEkcL0O4YSLqD9qd9M1gb/NWCHQR/H8AaQzA=
go.maximumdirect.net/configkit v1.1.0/go.mod h1:s1zLJ9GGB/1Q4a+aOHMLISonJxWFgNWpA6SpPlOafeA=
go.yaml.in/yaml/v4 v4.0.0-rc.6 h1:1h7H1ohdUh93/FyE4YaDa1Zh64K6VVbjF4K6WUxMtH4=
go.yaml.in/yaml/v4 v4.0.0-rc.6/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag=
github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
go.maximumdirect.net/commandkit v0.7.0 h1:toLDGhHoVe6gBX5HWuzQ/Joz0cBqEhJXolW21m3axBk=
go.maximumdirect.net/commandkit v0.7.0/go.mod h1:sVp3JXKpm2YrP4Ie8Q3nWmQgwBdPN8uO+wQU72erDns=
go.maximumdirect.net/commandkit v0.8.0 h1:EBDjr7SvfgvVDsA2S95hkOhgZe7oGZdDvURDJxHyX48=
go.maximumdirect.net/commandkit v0.8.0/go.mod h1:sVp3JXKpm2YrP4Ie8Q3nWmQgwBdPN8uO+wQU72erDns=
go.maximumdirect.net/configkit v1.4.0 h1:TfOupZbQ23/ZMs+xt5lmyukCF11ekqKep8KbmFQD63o=
go.maximumdirect.net/configkit v1.4.0/go.mod h1:ewu6blSokUDCMovy8JBXAdXRikGmlHXAQpFghnPWRfs=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
go.yaml.in/yaml/v4 v4.0.0 h1:/LG1pNO84Z4l603j/xMn69CcS5OYhMQ/f7l2LoQUGuw=
go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -0,0 +1,52 @@
package ckconfig_test
import (
"bytes"
"context"
"errors"
"go.maximumdirect.net/ckconfig"
ck "go.maximumdirect.net/commandkit"
"go.maximumdirect.net/configkit"
"strings"
"testing"
)
func TestExplainHelpExemptsInvocationFeatures(t *testing.T) {
starts, inputs, loads := 0, 0, 0
feature := ck.NewInvocationFeature(ck.InvocationFeatureSpec[struct{}]{
NewInput: func() struct{} { inputs++; return struct{}{} },
Flags: []ck.Flag[struct{}]{ck.BoolFlag(ck.FlagMeta{Name: "observe", Required: true}, false, func(*struct{}, ck.Supplied[bool]) {})},
Start: func(ck.Invocation, struct{}) (context.Context, func() ck.Report) {
starts++
return nil, func() ck.Report { return ck.Report{Value: "summary"} }
},
})
config := ckconfig.AppCommand(func(context.Context, ckconfig.Selection) (*configkit.Result[struct{}], error) {
loads++
return nil, errors.New("load failed")
})
app, err := ck.New(ck.Identity{Name: "test"}, config, ck.WithInvocationFeature(ck.Group("feature", ""), feature), ck.Alias("why", "config explain"), ck.NewCommand(ck.CommandSpec[struct{}]{Name: "run", Run: func(ck.Invocation, struct{}) ck.Outcome { return ck.Success() }}))
if err != nil {
t.Fatal(err)
}
for _, args := range [][]string{{"config", "explain"}, {"config", "explain", "--help"}, {"why", "--observe"}} {
var out, diag bytes.Buffer
result := app.Execute(context.Background(), args, ck.Streams{Out: &out, Err: &diag})
if result.Status != 0 || !strings.Contains(out.String(), "Usage:") || diag.Len() != 0 || starts != 0 || inputs != 0 || loads != 0 {
t.Fatalf("%v: %#v %q %q starts=%d inputs=%d loads=%d", args, result, out.String(), diag.String(), starts, inputs, loads)
}
}
for _, args := range [][]string{{"config", "explain", "--path=/"}, {"run"}, {"config", "explain", "--observe=bad"}} {
if r := app.Execute(context.Background(), args, ck.Streams{}); r.Kind != ck.OutcomeUsage {
t.Fatalf("%v: %#v", args, r)
}
}
var diag bytes.Buffer
if r := app.Execute(context.Background(), []string{"run", "--observe"}, ck.Streams{Err: &diag}); r.Status != 0 || starts != 1 || !strings.Contains(diag.String(), "summary") {
t.Fatalf("%#v %q", r, diag.String())
}
app.Execute(context.Background(), []string{"config", "explain", "--path=/", "--observe"}, ck.Streams{})
if starts != 2 || loads != 1 {
t.Fatalf("starts=%d loads=%d", starts, loads)
}
}

View File

@@ -73,38 +73,27 @@ func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operatio
scopeChoices = append(scopeChoices, commandkit.CompletionChoice{Value: "all"})
}
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,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "scope", Usage: "Select a named configuration, 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: "config", Usage: "Configuration source.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseConfigString,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "config", Usage: "Select the configuration source.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseConfigString,
func(input **configCommandInput[I, S], value commandkit.Supplied[string]) {
(*input).selection.Config = value
}),
commandkit.ValueFlag(commandkit.FlagMeta{Name: "overlay", Usage: "Overlay source.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseConfigString,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "overlay", Usage: "Select the configuration overlay.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseConfigString,
func(input **configCommandInput[I, S], value commandkit.Supplied[string]) {
(*input).selection.Overlay = value
}),
}
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
}),
commandkit.ValueFlag(commandkit.FlagMeta{Name: "against-overlay", Usage: "Overlay source for the right side.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseConfigString,
func(input **configCommandInput[I, S], value commandkit.Supplied[string]) {
(*input).against.Overlay = value
}),
)
flags = append(flags, comparisonOperationFlags[I, S]()...)
}
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.BoolFlag(commandkit.FlagMeta{Name: "details", Usage: "Show detailed 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]) {
commandkit.RepeatFlag(commandkit.FlagMeta{Name: "code", Usage: "Filter detailed findings by exact diagnostic code."}, []string(nil), parseConfigString, func(input **configCommandInput[I, S], value commandkit.Supplied[[]string]) {
(*input).codes = value.Value
}),
)
@@ -125,16 +114,16 @@ func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operatio
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.BoolFlag(commandkit.FlagMeta{Name: "historical", Usage: "Include paths that exist only in configuration history."}, 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 }),
commandkit.BoolFlag(commandkit.FlagMeta{Name: "explicit", Usage: "Filter current paths by whether ConfigKit marks them explicit."}, 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.ValueFlag(commandkit.FlagMeta{Name: "source-id", Usage: "Show one source ID from this configuration load."}, (*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 {
@@ -161,7 +150,13 @@ func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operatio
if input == nil {
return fmt.Errorf("configuration input must not be nil")
}
return prepareConfigOperation(prepared, operation, input)
if err := prepareConfigOperation(prepared, operation, input); err != nil {
return err
}
if input.plan.help {
return commandkit.ErrHelpRequested
}
return nil
},
Run: func(invocation commandkit.Invocation, input *configCommandInput[I, S]) commandkit.Outcome {
return runConfigOperation(invocation, operation, input)
@@ -169,6 +164,21 @@ func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operatio
})
}
func comparisonOperationFlags[I, S any]() []commandkit.Flag[*configCommandInput[I, S]] {
return []commandkit.Flag[*configCommandInput[I, S]]{
commandkit.BoolFlag(commandkit.FlagMeta{Name: "details", Usage: "Show before and after values with presence and redaction details."}, 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
}),
commandkit.ValueFlag(commandkit.FlagMeta{Name: "against-overlay", Usage: "Overlay source for the right side.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseConfigString,
func(input **configCommandInput[I, S], value commandkit.Supplied[string]) {
(*input).against.Overlay = value
}),
}
}
func operationDescription(operation Operation) string {
if operation == Explain {
return "Use --list to discover paths or --path POINTER to explain one path."
@@ -187,41 +197,44 @@ func operationDeclaration(operation Operation) (string, string) {
case Explain:
return "explain", "Explain a configuration path."
case Diff:
return "diff", "Compare two configuration selections."
return "diff", "Compare two configurations."
default:
return string(operation), "Inspect configuration."
}
}
func prepareConfigOperation[I, S any](prepared *preparedSuite[I, S], operation Operation, input *configCommandInput[I, S]) error {
func checkConfigOperationOptions[I, S any](operation Operation, input *configCommandInput[I, S]) (bool, error) {
if operation == Validate && !input.details.Value && (len(input.severities) > 0 || len(input.codes) > 0) {
return fmt.Errorf("--severity and --code require --details")
return false, fmt.Errorf("--severity and --code require --details")
}
if operation == Explain {
if input.list.Value && input.path.Set {
return fmt.Errorf("--list and --path cannot be combined")
return false, 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")
return false, 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
return true, nil
}
}
return false, nil
}
func selectConfigScopes[I, S any](prepared *preparedSuite[I, S], operation Operation, input *configCommandInput[I, S]) (string, []*preparedScope[I, S], error) {
scopeName := "app"
if input.scope.Set {
scopeName = input.scope.Value
}
if scopeName == "" {
return fmt.Errorf("configuration scope must not be empty")
return "", nil, fmt.Errorf("configuration scope must not be empty")
}
if scopeName == "all" && operation != Validate && operation != Show {
return fmt.Errorf("scope all is supported only for validate and show")
return "", nil, 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")
return "", nil, fmt.Errorf("path-selected show requires one scope")
}
var selected []*preparedScope[I, S]
@@ -230,24 +243,62 @@ func prepareConfigOperation[I, S any](prepared *preparedSuite[I, S], operation O
} else if scope, exists := prepared.byName[scopeName]; exists {
selected = []*preparedScope[I, S]{scope}
} else {
return fmt.Errorf("unknown configuration scope %q (available: %s)", scopeName, prepared.scopeChoices)
return "", nil, fmt.Errorf("unknown configuration scope %q (available: %s)", scopeName, prepared.scopeChoices)
}
for _, scope := range selected {
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))
return "", nil, 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)
return "", nil, 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)
return "", nil, 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)
return "", nil, fmt.Errorf("configuration scope %q does not support path-selected show", scope.scope.Name)
}
}
return scopeName, selected, nil
}
func prepareComparisonInputs[I, S any](prepared *preparedSuite[I, S], input *configCommandInput[I, S], scope *preparedScope[I, S], plan *configOperationPlan[I, S]) error {
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.againstValues, scope, scope.againstBindings, input.against, true)
if err != nil {
return fmt.Errorf("configuration scope %q right input: %w", scope.scope.Name, err)
}
plan.comparison = &preparedComparison[I, S]{
scope: scope,
request: ComparisonRequest[I]{
Left: ComparisonSide[I]{Selection: input.selection, Input: left},
Right: ComparisonSide[I]{Selection: input.against, Input: right},
},
}
return nil
}
func prepareConfigOperation[I, S any](prepared *preparedSuite[I, S], operation Operation, input *configCommandInput[I, S]) error {
help, err := checkConfigOperationOptions(operation, input)
if err != nil {
return err
}
if help {
input.plan = &configOperationPlan[I, S]{prepared: prepared, operation: operation, help: true}
return nil
}
scopeName, selected, err := selectConfigScopes(prepared, operation, input)
if err != nil {
return err
}
var path configkit.Path
if (operation == Explain || operation == Show) && input.path.Set {
parsed, err := configkit.ParsePath(input.path.Value)
@@ -283,23 +334,8 @@ func prepareConfigOperation[I, S any](prepared *preparedSuite[I, S], operation O
scopes: make([]selectedScopeInput[I, S], 0, len(selected)),
}
if operation == Diff {
scope := selected[0]
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.againstValues, scope, scope.againstBindings, input.against, true)
if err != nil {
return fmt.Errorf("configuration scope %q right input: %w", scope.scope.Name, err)
}
plan.comparison = &preparedComparison[I, S]{
scope: scope,
request: ComparisonRequest[I]{
Left: ComparisonSide[I]{Selection: input.selection, Input: left},
Right: ComparisonSide[I]{Selection: input.against, Input: right},
},
if err := prepareComparisonInputs(prepared, input, selected[0], plan); err != nil {
return err
}
input.plan = plan
return nil

View File

@@ -1,6 +1,8 @@
package ckconfig
import (
"context"
"errors"
"fmt"
"io"
@@ -15,7 +17,7 @@ func runConfigOperation[I, S any](invocation commandkit.Invocation, operation Op
return invocation.Help()
}
if err := invocation.Context.Err(); err != nil {
return configFailure("Configuration operation was canceled.", commandkit.Explanation{}, err)
return configFailure(invocation.Context, "Configuration operation was canceled.", commandkit.Explanation{}, err)
}
plan := input.plan
var state S
@@ -64,11 +66,23 @@ func queueConfigAcquisition(reporter *commandkit.Reporter, acquired commandkit.A
}
}
func configFailure(message string, explanation commandkit.Explanation, cause error) commandkit.Outcome {
func configFailure(ctx context.Context, message string, explanation commandkit.Explanation, cause error) commandkit.Outcome {
if explanation.Message != "" || len(explanation.Details) > 0 {
message = explanation.Message
}
if ctx != nil {
if canceled := ctx.Err(); canceled != nil {
if cause == nil {
cause = canceled
} else if !errors.Is(cause, canceled) {
cause = errors.Join(cause, canceled)
}
}
}
outcome := commandkit.Failure(message, explanation.Details...)
if cause != nil && ClassifyConfigurationError(cause) == commandkit.OutcomeUsage {
outcome = commandkit.Usage(message, explanation.Details...)
}
if cause != nil {
outcome = outcome.WithCause(cause)
}
@@ -76,6 +90,7 @@ func configFailure(message string, explanation commandkit.Explanation, cause err
}
func configAcquisitionFailure(
ctx context.Context,
reporter *commandkit.Reporter,
operation, scope string,
acquired commandkit.Acquired[View],
@@ -83,7 +98,7 @@ func configAcquisitionFailure(
) commandkit.Outcome {
queueConfigAcquisition(reporter, acquired)
message := fmt.Sprintf("Unable to %s configuration scope %q.", operation, scope)
return configFailure(message, acquired.Explanation, cause)
return configFailure(ctx, message, acquired.Explanation, cause)
}
// Preserve the preparation/delivery cancellation checkpoint for buffered reports.
@@ -105,7 +120,7 @@ func renderPreparedConfigReport(invocation commandkit.Invocation, explanation co
canceled = invocation.Context.Err()
}
if canceled != nil {
return configFailure("Configuration report preparation was canceled.", explanation, canceled)
return configFailure(invocation.Context, "Configuration report preparation was canceled.", explanation, canceled)
}
if renderErr == nil {
_ = invocation.Reporter().Report(commandkit.Report{Value: value})

View File

@@ -88,7 +88,7 @@ func TestOverrideNativeLoadErrorAndProvenance(t *testing.T) {
}
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) {
if result.Kind != commandkit.OutcomeUsage || !errors.As(result.Cause, &loadErr) {
t.Fatalf("native invalid root override: %#v", result)
}
}

View File

@@ -1,6 +1,7 @@
package ckconfig
import (
"bytes"
"context"
"errors"
"io"
@@ -67,3 +68,39 @@ func TestBufferedReportDoesNotRejectCancellationAfterDeliveryStarts(t *testing.T
t.Fatalf("post-delivery cancellation changed the operation outcome: %#v", got)
}
}
type effectiveWriterFunc func(io.Writer) error
func (write effectiveWriterFunc) WriteEffective(w io.Writer) error { return write(w) }
func TestShowCancellationDuringBufferedPreparation(t *testing.T) {
renderErr := errors.New("native rendering failed")
for _, tc := range []struct {
name string
renderErr error
}{{name: "cancellation"}, {name: "cancellation and rendering failure", renderErr: renderErr}} {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
acquired, secondWrites := 0, 0
scope := func(name string, writer EffectiveWriter) Scope[struct{}, struct{}] {
return Scope[struct{}, struct{}]{Name: name, Operations: []Operation{Show}, Acquire: func(context.Context, Request, struct{}, struct{}) (commandkit.Acquired[View], error) {
acquired++
return commandkit.Acquired[View]{Value: View{Effective: writer}}, nil
}}
}
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{
scope("app", effectiveWriterFunc(func(w io.Writer) error { _, _ = io.WriteString(w, "name: app\n"); cancel(); return tc.renderErr })),
scope("promptkit", effectiveWriterFunc(func(w io.Writer) error { secondWrites++; _, err := io.WriteString(w, "name: promptkit\n"); return err })),
}}))
var output bytes.Buffer
got := app.Execute(ctx, []string{"config", "show", "--scope=all"}, commandkit.Streams{Out: &output, Err: io.Discard})
if acquired != 2 || secondWrites != 0 || output.Len() != 0 || !errors.Is(got.Cause, context.Canceled) || got.Presentation.Output.WriteError != nil {
t.Fatalf("acquired=%d second=%d output=%q outcome=%#v", acquired, secondWrites, output.String(), got)
}
if tc.renderErr == nil && got.Presentation.Output.RenderError != nil || tc.renderErr != nil && !errors.Is(got.Presentation.Output.RenderError, tc.renderErr) {
t.Fatalf("render evidence = %#v", got.Presentation.Output)
}
})
}
}

View File

@@ -19,29 +19,29 @@ func runConfigShow[I, S any](invocation commandkit.Invocation, plan *configOpera
reporter := invocation.Reporter()
for _, selected := range plan.scopes {
if err := invocation.Context.Err(); err != nil {
return configFailure("Configuration show was canceled.", commandkit.Explanation{}, err)
return configFailure(invocation.Context, "Configuration show was canceled.", commandkit.Explanation{}, err)
}
if selected.scope.scope.Acquire == nil {
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: selected.selection}, selected.input, state)
if acquireErr != nil {
return configAcquisitionFailure(reporter, "show", selected.scope.scope.Name, acquired, acquireErr)
return configAcquisitionFailure(invocation.Context, reporter, "show", selected.scope.scope.Name, acquired, acquireErr)
}
queueConfigAcquisition(reporter, acquired)
if err := invocation.Context.Err(); err != nil {
return configFailure("Configuration show was canceled.", acquired.Explanation, err)
return configFailure(invocation.Context, "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))
return configFailure(invocation.Context, "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))
return configFailure(invocation.Context, "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)
return configFailure(invocation.Context, "Configuration show was canceled.", acquired.Explanation, err)
}
var value any
err := reporter.RenderOutput(func(io.Writer) error {
@@ -51,7 +51,7 @@ func runConfigShow[I, S any](invocation commandkit.Invocation, plan *configOpera
})
if err == nil {
if canceled := invocation.Context.Err(); canceled != nil {
return configFailure("Configuration show was canceled.", acquired.Explanation, canceled)
return configFailure(invocation.Context, "Configuration show was canceled.", acquired.Explanation, canceled)
}
_ = reporter.Report(commandkit.Report{Value: value})
}
@@ -63,14 +63,16 @@ func runConfigShow[I, S any](invocation commandkit.Invocation, plan *configOpera
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)
return configFailure(invocation.Context, "Configuration show was canceled.", commandkit.Explanation{}, err)
}
var value any
var canceled error
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
canceled = err
return nil
}
var native bytes.Buffer
if err := document.view.Effective.WriteEffective(&native); err != nil {
@@ -89,14 +91,17 @@ func runConfigShow[I, S any](invocation commandkit.Invocation, plan *configOpera
}
return nil
})
if canceled != nil {
return configFailure(invocation.Context, "Configuration show was canceled.", commandkit.Explanation{}, canceled)
}
if err != nil {
if canceled := invocation.Context.Err(); canceled != nil {
return configFailure("Configuration show was canceled.", commandkit.Explanation{}, canceled)
return configFailure(invocation.Context, "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)
return configFailure(invocation.Context, "Configuration show was canceled.", commandkit.Explanation{}, err)
}
_ = reporter.Report(commandkit.Report{Value: value})
return commandkit.Success()

View File

@@ -59,11 +59,11 @@ func runConfigSources[I, S any](invocation commandkit.Invocation, plan *configOp
name := selected.scope.scope.Name
reporter := invocation.Reporter()
if err := invocation.Context.Err(); err != nil {
return configFailure("Configuration source listing was canceled.", commandkit.Explanation{}, err)
return configFailure(invocation.Context, "Configuration source listing was canceled.", commandkit.Explanation{}, err)
}
if selected.scope.scope.Acquire == nil {
cause := fmt.Errorf("configuration scope %q has no acquisition callback", name)
return configFailure(fmt.Sprintf("Unable to list sources for configuration scope %q.", name), commandkit.Explanation{}, cause)
return configFailure(invocation.Context, fmt.Sprintf("Unable to list sources for configuration scope %q.", name), commandkit.Explanation{}, cause)
}
acquired, acquireErr := selected.scope.scope.Acquire(invocation.Context, Request{
Operation: Sources,
@@ -72,15 +72,15 @@ func runConfigSources[I, S any](invocation commandkit.Invocation, plan *configOp
queueConfigAcquisition(reporter, acquired)
if acquireErr == nil && invocation.Context.Err() != nil {
err := invocation.Context.Err()
return configFailure("Configuration source listing was canceled.", acquired.Explanation, err)
return configFailure(invocation.Context, "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)
return configFailure(invocation.Context, 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)
return configFailure(invocation.Context, "Configuration scope did not provide source information.", acquired.Explanation, cause)
}
sources := acquired.Value.Sources.Sources()
@@ -134,17 +134,17 @@ func runConfigSources[I, S any](invocation commandkit.Invocation, plan *configOp
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(invocation.Context, 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))
return configFailure(invocation.Context, 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 configFailure(invocation.Context, "Configuration source listing was canceled.", acquired.Explanation, err)
}
_ = 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 configFailure(invocation.Context, fmt.Sprintf("Unable to list sources for configuration scope %q.", name), acquired.Explanation, acquireErr)
}
return commandkit.Success()
}

View File

@@ -0,0 +1,182 @@
package ckconfig
import (
"bytes"
"context"
"errors"
"io"
"reflect"
"strings"
"testing"
commandkit "go.maximumdirect.net/commandkit"
configkit "go.maximumdirect.net/configkit"
)
func TestSubtreeScopeUsesNativeInspection(t *testing.T) {
definition := configkit.Definition[map[string]any]{Validate: func(_ *map[string]any, validation *configkit.Validation) {
validation.Warning(configkit.Keys("sibling"), "sibling warning")
}}
makeResult := func(value any) *configkit.Result[map[string]any] {
t.Helper()
result, err := configkit.Load(configkit.Mapping("application", map[string]any{"storage": value, "sibling": "outside"}), configkit.Options[map[string]any]{Definition: definition})
if err != nil {
t.Fatal(err)
}
return result
}
left, right := makeResult(map[string]any{"name": "before"}), makeResult(map[string]any{"name": "after"})
calls := 0
scope := FromConfigKitSubtree("storage", "", configkit.Keys("storage"), func(_ context.Context, selection Selection, _, _ struct{}) (*configkit.Result[map[string]any], error) {
calls++
if selection.Config.Value == "after" {
return right, nil
}
return left, nil
})
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
if calls != 0 {
t.Fatal("construction acquired configuration")
}
run := func(args ...string) (commandkit.Outcome, string, string) {
t.Helper()
var out, diagnostics bytes.Buffer
outcome := app.Execute(context.Background(), append(append([]string{"config"}, args...), "--scope=storage"), commandkit.Streams{Out: &out, Err: &diagnostics})
return outcome, out.String(), diagnostics.String()
}
for _, tc := range []struct {
args []string
contains, excludes string
}{
{[]string{"show"}, "before", "outside"},
{[]string{"explain", "--list"}, "/storage/name", "/sibling"},
{[]string{"explain", "--path=/sibling"}, "/sibling", ""},
{[]string{"sources"}, "application", ""},
{[]string{"diff", "--config=before", "--against-config=after"}, "after", ""},
} {
outcome, output, diagnostics := run(tc.args...)
if outcome.Kind != commandkit.OutcomeSuccess || !strings.Contains(output, tc.contains) || (tc.excludes != "" && strings.Contains(output, tc.excludes)) {
t.Errorf("%v: outcome=%#v output=%q diagnostics=%q", tc.args, outcome, output, diagnostics)
}
}
lv, _ := left.InspectSubtree(configkit.Keys("storage"))
rv, _ := right.InspectSubtree(configkit.Keys("storage"))
want, err := lv.Diff(rv)
if err != nil {
t.Fatal(err)
}
got, err := scope.Compare(context.Background(), ComparisonRequest[struct{}]{Left: ComparisonSide[struct{}]{Selection: Selection{Config: commandkit.Supplied[string]{Value: "before", Set: true}}}, Right: ComparisonSide[struct{}]{Selection: Selection{Config: commandkit.Supplied[string]{Value: "after", Set: true}}}}, struct{}{})
if err != nil || !reflect.DeepEqual(got.Value, want) || len(got.Diagnostics) != 2 {
t.Fatalf("comparison = %#v, %v; want %#v", got, err, want)
}
}
func TestSubtreeScopeAbsenceAndErrors(t *testing.T) {
load := func(value map[string]any) *configkit.Result[map[string]any] {
t.Helper()
result, err := configkit.Load[map[string]any](configkit.Mapping("application", value))
if err != nil {
t.Fatal(err)
}
return result
}
for _, tc := range []struct {
name string
result *configkit.Result[map[string]any]
wantWriteError bool
}{
{"absent", load(map[string]any{"sibling": 1}), true}, {"null", load(map[string]any{"storage": nil}), false},
} {
t.Run(tc.name, func(t *testing.T) {
scope := FromConfigKitSubtree("storage", "", configkit.Keys("storage"), func(context.Context, Selection, struct{}, struct{}) (*configkit.Result[map[string]any], error) {
return tc.result, nil
})
acquired, err := scope.Acquire(context.Background(), Request{}, struct{}{}, struct{}{})
if err != nil {
t.Fatal(err)
}
var output bytes.Buffer
err = acquired.Value.Effective.WriteEffective(&output)
if (err != nil) != tc.wantWriteError || (!tc.wantWriteError && !strings.Contains(output.String(), "null")) {
t.Fatalf("write = %q, %v", output.String(), err)
}
})
}
cause := errors.New("application load failed")
result := load(map[string]any{"sibling": 1})
scope := FromConfigKitSubtree("storage", "", configkit.Keys("storage"), func(context.Context, Selection, struct{}, struct{}) (*configkit.Result[map[string]any], error) {
return result, cause
})
acquired, err := scope.Acquire(context.Background(), Request{}, struct{}{}, struct{}{})
if !errors.Is(err, cause) || acquired.Value.Sources == nil || acquired.Value.Findings == nil {
t.Fatalf("load failure = %#v, %v", acquired, err)
}
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
outcome := app.Execute(context.Background(), []string{"config", "show", "--scope=storage"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
if outcome.Kind != commandkit.OutcomeOperational || !errors.Is(outcome.Cause, cause) {
t.Fatalf("outcome = %#v", outcome)
}
unavailable := FromConfigKitSubtree("storage", "", configkit.Keys("storage"), func(context.Context, Selection, struct{}, struct{}) (*configkit.Result[map[string]any], error) {
return &configkit.Result[map[string]any]{}, nil
})
acquired, err = unavailable.Acquire(context.Background(), Request{}, struct{}{}, struct{}{})
if err == nil || acquired.Value.Findings == nil || acquired.Value.Sources == nil {
t.Fatalf("unavailable = %#v, %v", acquired, err)
}
nilScope := FromConfigKitSubtree[struct{}, struct{}, map[string]any]("storage", "", configkit.Keys("storage"), nil)
if len(nilScope.issues) == 0 {
t.Fatal("nil loader not retained")
}
}
func TestSubtreeScopeRetainsWholeLoadFailure(t *testing.T) {
path := configkit.Keys("sibling")
_, loadErr := configkit.Load(configkit.Bytes("bad application", []byte("{}\n")), configkit.Options[struct{}]{Definition: configkit.Definition[struct{}]{Version: &configkit.VersionRule{
Path: path, Check: func(_ configkit.Version, validation *configkit.Validation) error {
validation.Warning(path, "outside warning")
return errors.New("invalid outside")
},
}}})
if loadErr == nil {
t.Fatal("fixture did not fail")
}
scope := FromConfigKitSubtree("storage", "", configkit.Keys("storage"), func(context.Context, Selection, struct{}, struct{}) (*configkit.Result[struct{}], error) {
return nil, loadErr
})
acquired, err := scope.Acquire(context.Background(), Request{}, struct{}{}, struct{}{})
var native *configkit.LoadError
if !errors.As(err, &native) || !errors.Is(err, loadErr) || acquired.Value.Sources == nil || acquired.Value.Findings == nil || !reflect.DeepEqual(acquired.Value.Findings.Records, native.Diagnostics()) || len(acquired.Explanation.Details) == 0 {
t.Fatalf("failure evidence = %#v, %v", acquired, err)
}
app := newConfigTestApp(t, Command(Suite[struct{}, struct{}]{Scopes: []Scope[struct{}, struct{}]{scope}}))
outcome := app.Execute(context.Background(), []string{"config", "validate", "--scope=storage"}, commandkit.Streams{Out: io.Discard, Err: io.Discard})
if !errors.Is(outcome.Cause, loadErr) {
t.Fatalf("validation outcome = %#v", outcome)
}
}
func TestSubtreeComparisonRetainsNativeAncestor(t *testing.T) {
makeResult := func(item string) *configkit.Result[map[string]any] {
t.Helper()
result, err := configkit.Load[map[string]any](configkit.Mapping(item, map[string]any{"items": []any{item}}))
if err != nil {
t.Fatal(err)
}
return result
}
left, right := makeResult("before"), makeResult("after")
path := configkit.Keys("items", "0")
scope := FromConfigKitSubtree("item", "", path, func(_ context.Context, selection Selection, _, _ struct{}) (*configkit.Result[map[string]any], error) {
if selection.Config.Value == "right" {
return right, nil
}
return left, nil
})
got, err := scope.Compare(context.Background(), ComparisonRequest[struct{}]{Right: ComparisonSide[struct{}]{Selection: Selection{Config: commandkit.Supplied[string]{Value: "right", Set: true}}}}, struct{}{})
lv, _ := left.InspectSubtree(path)
rv, _ := right.InspectSubtree(path)
want, nativeErr := lv.Diff(rv)
if err != nil || nativeErr != nil || !reflect.DeepEqual(got.Value, want) || len(want) != 1 || want[0].Path.String() != "/items" {
t.Fatalf("comparison = %#v, %v; native = %#v, %v", got.Value, err, want, nativeErr)
}
}

View File

@@ -3,7 +3,6 @@ package ckconfig
import (
"errors"
"fmt"
"slices"
"text/template"
commandkit "go.maximumdirect.net/commandkit"
@@ -62,16 +61,24 @@ func runConfigValidation[I, S any](invocation commandkit.Invocation, plan *confi
reporter := invocation.Reporter()
report := validationReport{Scopes: make([]validationScope, 0, len(plan.scopes))}
outcome := commandkit.Success()
severities := make(map[configkit.Severity]bool, len(plan.severities))
for _, severity := range plan.severities {
severities[severity] = true
}
codes := make(map[string]bool, len(plan.codes))
for _, code := range plan.codes {
codes[code] = true
}
for _, selected := range plan.scopes {
if err := invocation.Context.Err(); err != nil {
outcome = configFailure("Configuration validation was canceled.", commandkit.Explanation{}, err)
outcome = configFailure(invocation.Context, "Configuration validation was canceled.", commandkit.Explanation{}, err)
break
}
name := selected.scope.scope.Name
if selected.scope.scope.Acquire == nil {
entry := validationScope{Scope: name, Outcome: "failed"}
if plan.details {
entry.Details = projectValidationDetails(View{}, plan.severities, plan.codes)
entry.Details = projectValidationDetails(View{}, severities, codes)
}
report.Scopes = append(report.Scopes, entry)
outcome = commandkit.Failure(fmt.Sprintf("Configuration scope %q has no acquisition callback.", name))
@@ -84,7 +91,7 @@ func runConfigValidation[I, S any](invocation commandkit.Invocation, plan *confi
}
entry := validationScope{Scope: name, Outcome: "valid"}
if plan.details {
entry.Details = projectValidationDetails(acquired.Value, plan.severities, plan.codes)
entry.Details = projectValidationDetails(acquired.Value, severities, codes)
}
if canceled := invocation.Context.Err(); canceled != nil {
entry.Outcome = "canceled"
@@ -102,7 +109,7 @@ func runConfigValidation[I, S any](invocation commandkit.Invocation, plan *confi
if entry.Outcome == "canceled" {
message = "Configuration validation was canceled."
}
outcome = configFailure(message, acquired.Explanation, err)
outcome = configFailure(invocation.Context, message, acquired.Explanation, err)
break
}
}
@@ -114,7 +121,7 @@ func runConfigValidation[I, S any](invocation commandkit.Invocation, plan *confi
return outcome
}
func projectValidationDetails(view View, severities []configkit.Severity, codes []string) *validationDetails {
func projectValidationDetails(view View, severities map[configkit.Severity]bool, codes map[string]bool) *validationDetails {
details := &validationDetails{State: "unavailable", Findings: []validationFinding{}, Sources: []validationSource{}}
if view.Findings == nil {
return details
@@ -126,10 +133,10 @@ func projectValidationDetails(view View, severities []configkit.Severity, codes
details.State = "filtered"
references := make(map[string]bool)
for _, record := range view.Findings.Records {
if len(severities) > 0 && !slices.Contains(severities, record.Severity) {
if len(severities) > 0 && !severities[record.Severity] {
continue
}
if len(codes) > 0 && !slices.Contains(codes, string(record.Code)) {
if len(codes) > 0 && !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)}

View File

@@ -1,39 +1,39 @@
# CommandKit ckprompt
`ckprompt` is the optional PromptKit integration for CommandKit. It adapts
PromptKit engine configuration, native comparison, five catalogs, named
inspection, requirements discovery and validation, and native smoke tests.
Importing it does not install either command family.
`ckprompt` adds PromptKit inspection and testing commands to Go applications
that use CommandKit. Operators can list prompts, profiles, and backends, inspect
their settings, discover required inputs, validate and preview requests, and
run smoke tests.
The application chooses which commands to install. Importing the package alone
does not install commands.
## Module
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.
The module path is `go.maximumdirect.net/ckprompt`. See the
[consumer guide](https://forge.maximumdirect.net/base-layer/commandkit/src/branch/main/docs/consumers/guide.md#module-selection)
for compatible releases and Go requirements.
## Example
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 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, 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
application retains ownership of client and configuration choices. See the
[CLI reference](https://gitea.maximumdirect.net/eric/CommandKit/src/branch/main/docs/cli.md#promptkit-smoke-testing)
for operator commands and report semantics. The maintained
[composed example](examples/composed) shows complete application wiring.
Pass your engine loader to `FromEngine` to add resource listings, inspection,
and requirements discovery:
```go
app, err := commandkit.New(identity, ckprompt.Command(ckprompt.FromEngine(loadEngine)))
```
Add request validation, preview, and smoke tests with `WithRequestValidation`,
`WithRequestPreparation`, and `WithSmokeTesting`. To expose engine configuration
under `config`, add `ckprompt.ConfigScope(loadEngine)` to a `ckconfig.Suite`.
The [integration guide](https://forge.maximumdirect.net/base-layer/commandkit/src/branch/main/docs/consumers/guide.md#promptkit-configuration-definitions-and-requirements)
explains these choices; the [composed example](examples/composed) shows them together.
Inspection commands do not call the model. Smoke tests can use the application's
configured client or network probes. Applications own engine setup, credentials,
and any effects of their loaders and callbacks. See the
[CLI reference](https://forge.maximumdirect.net/base-layer/commandkit/src/branch/main/docs/cli.md#promptkit-smoke-testing)
for commands and results.
## License and attribution
@@ -41,3 +41,10 @@ This module is licensed under the [GNU Lesser General Public License v3.0 or
later](COPYRIGHT). The accompanying [LICENSE](LICENSE) contains the full LGPL
v3 and GPL v3 texts. See [third-party attribution](docs/oss/attribution.md)
for incorporated and dependency notices.
Smoke-test reports default to text; use `--format yaml` or `--format json` for
structured output. Reports preserve native reasoning-token and cache-hit evidence.
Backend provider conventions are selected explicitly in PromptKit configuration;
for example, application-defined OpenRouter backends need `provider: openrouter`.
See the [PromptKit backend format](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/formats.md#backend-definitions)
for provider and zero-cost settings.

View File

@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"io"
"strconv"
"go.maximumdirect.net/ckconfig"
@@ -197,7 +196,8 @@ func WithRequestValidation[I, S any](
if build != nil {
built, err := build(ctx, request, input, state)
if err != nil {
return commandkit.Acquired[struct{}]{}, err
messages := promptKitLoadErrorDiagnostics(err, "")
return commandkit.Acquired[struct{}]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, err
}
concreteRequest = built
}
@@ -281,6 +281,9 @@ func ConfigScope[I, S any](load func(context.Context, ckconfig.Selection, I, S)
if errors.As(err, &loadError) && loadError != nil {
acquired.Value.Sources = loadError
acquired.Value.Findings = &ckconfig.Findings{Records: loadError.Diagnostics(), Messages: messages.diagnostics}
} else if inspection != nil {
acquired.Value.Sources = *inspection
acquired.Value.Findings = &ckconfig.Findings{Records: inspection.Diagnostics(), Messages: messages.diagnostics}
} else {
acquired.Diagnostics = messages.diagnostics
}
@@ -289,9 +292,10 @@ func ConfigScope[I, S any](load func(context.Context, ckconfig.Selection, I, S)
metadata := inspection.Metadata()
return commandkit.Acquired[ckconfig.View]{
Value: ckconfig.View{
Effective: inspection,
Sources: inspection,
Explanation: inspection,
Effective: *inspection,
Sources: *inspection,
Explanation: *inspection,
Paths: *inspection,
Metadata: &metadata,
Findings: &ckconfig.Findings{Records: inspection.Diagnostics(), Messages: messages.diagnostics},
},
@@ -322,7 +326,7 @@ func ConfigScope[I, S any](load func(context.Context, ckconfig.Selection, I, S)
return commandkit.Acquired[[]configkit.Difference]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, fmt.Errorf("PromptKit scope %q comparison before native diff: %w", scope.Name, err)
}
differences, err := leftInspection.Diff(rightInspection)
differences, err := leftInspection.Diff(*rightInspection)
messages = messages.withOperationError(err)
if err != nil {
return commandkit.Acquired[[]configkit.Difference]{Diagnostics: messages.diagnostics, Explanation: messages.explanation}, fmt.Errorf("PromptKit scope %q native configuration diff: %w", scope.Name, err)
@@ -471,31 +475,26 @@ func loadPromptKitEngine[I, S any](
state S,
side string,
load engineLoader[I, S],
) (*promptkit.Engine, promptkit.ConfigurationInspection, promptKitAcquisition, error) {
) (*promptkit.Engine, *promptkit.ConfigurationInspection, promptKitAcquisition, error) {
engine, err := load(ctx, selection, input, state)
if err != nil {
var loadErr *configkit.LoadError
if errors.As(err, &loadErr) {
messages := promptKitDiagnostics("promptkit", side, loadErr.Sources(), loadErr.Diagnostics())
return nil, promptkit.ConfigurationInspection{}, messages, err
}
return nil, promptkit.ConfigurationInspection{}, promptKitAcquisition{}, err
return nil, nil, promptKitLoadErrorDiagnostics(err, side), err
}
if engine == nil {
return nil, promptkit.ConfigurationInspection{}, promptKitAcquisition{}, errors.New("PromptKit configuration loader returned a nil engine")
return nil, nil, promptKitAcquisition{}, errors.New("PromptKit configuration loader returned a nil engine")
}
inspection, err := engine.InspectConfiguration()
messages := promptKitDiagnostics("promptkit", side, inspection.Sources(), inspection.Diagnostics())
messages = messages.withOperationError(err)
if err != nil {
return nil, inspection, messages, err
return nil, nil, messages, err
}
if ctx != nil {
if err := ctx.Err(); err != nil {
return nil, promptkit.ConfigurationInspection{}, messages, err
return nil, &inspection, messages, err
}
}
return engine, inspection, messages, nil
return engine, &inspection, messages, nil
}
func appendPromptKitAcquisition(left, right promptKitAcquisition) promptKitAcquisition {
@@ -507,62 +506,19 @@ func appendPromptKitAcquisition(left, right promptKitAcquisition) promptKitAcqui
return left
}
func promptKitDiagnostics(scope, side string, sources []configkit.SourceInfo, records []configkit.Diagnostic) promptKitAcquisition {
if len(records) == 0 {
func promptKitLoadErrorDiagnostics(err error, side string) promptKitAcquisition {
var loadErr *configkit.LoadError
if errors.As(err, &loadErr) && loadErr != nil {
return promptKitDiagnostics("promptkit", side, loadErr.Sources(), loadErr.Diagnostics())
}
return promptKitAcquisition{}
}
// Snapshot provider-owned slices before deferring their report to invocation.
sources = append([]configkit.SourceInfo(nil), sources...)
records = append([]configkit.Diagnostic(nil), records...)
for index := range records {
if records[index].Primary != nil {
primary := *records[index].Primary
records[index].Primary = &primary
}
records[index].Related = append([]configkit.Location(nil), records[index].Related...)
}
var warnings, failures []configkit.Diagnostic
for _, record := range records {
if record.Severity == configkit.SeverityError {
failures = append(failures, record)
} else {
warnings = append(warnings, record)
}
}
messages := promptKitAcquisition{}
if len(warnings) > 0 {
messages.diagnostics = []commandkit.Diagnostic{{
Severity: commandkit.SeverityWarning,
Write: func(writer io.Writer) error {
return writePromptKitDiagnostics(writer, scope, side, sources, warnings)
},
}}
}
if len(failures) > 0 {
messages.explanation = commandkit.Explanation{Details: []commandkit.Detail{func(writer io.Writer) error {
return writePromptKitDiagnostics(writer, scope, side, sources, failures)
}}}
}
return messages
}
func writePromptKitDiagnostics(writer io.Writer, scope, side string, sources []configkit.SourceInfo, records []configkit.Diagnostic) error {
func promptKitDiagnostics(scope, side string, sources []configkit.SourceInfo, records []configkit.Diagnostic) promptKitAcquisition {
heading := "Configuration scope " + strconv.Quote(scope)
if side != "" {
heading += " (" + side + ")"
}
if _, err := fmt.Fprintf(writer, "%s:\n", heading); err != nil {
return err
}
if len(sources) > 0 {
if _, err := io.WriteString(writer, "Source IDs:\n"); err != nil {
return err
}
for _, source := range sources {
if _, err := fmt.Fprintf(writer, " %s: label=%s, path=%s\n", strconv.Quote(source.ID), strconv.Quote(source.Label), strconv.Quote(source.Path)); err != nil {
return err
}
}
}
return configkit.WriteDiagnostics(writer, records)
diagnostics, explanation := ckconfig.AdaptDiagnostics(heading+":\n", sources, records)
return promptKitAcquisition{diagnostics: diagnostics, explanation: explanation}
}

View File

@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"errors"
"fmt"
"io"
"reflect"
"slices"
@@ -97,6 +98,9 @@ func adapterEngineFrom(t *testing.T, label, configuration string, options ...pro
if err != nil {
t.Fatal(err)
}
for index := range inputs {
inputs[index].Destination = configkit.Keys("promptkit")
}
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{
Underlays: []configkit.Underlay{{Inputs: inputs}},
}}, append([]promptkit.Option{promptkit.WithBundledOpenRouter(false)}, options...)...)
@@ -858,18 +862,79 @@ func TestFromEngineRetainsConfigKitLoadExplanation(t *testing.T) {
}
}
func TestConfigScopeHonorsCancellationAfterLoad(t *testing.T) {
func TestConfigScopeRetainsCapturedEvidenceAfterCancellation(t *testing.T) {
engine := adapterEngine(t)
native, err := engine.InspectConfiguration()
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
engine := adapterEngine(t)
scope := ConfigScope(func(context.Context, ckconfig.Selection, int, int) (*promptkit.Engine, error) {
scope := ConfigScope(func(context.Context, ckconfig.Selection, struct{}, struct{}) (*promptkit.Engine, error) {
cancel()
return engine, nil
})
acquired, err := scope.Acquire(ctx, ckconfig.Request{Operation: ckconfig.Show}, 0, 0)
if !errors.Is(err, context.Canceled) || acquired.Value.Effective != nil {
t.Fatalf("cancelled scope acquisition = (%#v, %v), want cancellation and no value", acquired, err)
acquired, err := scope.Acquire(ctx, ckconfig.Request{}, struct{}{}, struct{}{})
if !errors.Is(err, context.Canceled) || acquired.Value.Effective != nil || acquired.Value.Metadata != nil || acquired.Value.Explanation != nil || acquired.Value.Sources == nil || acquired.Value.Findings == nil {
t.Fatalf("canceled acquisition = %#v, %v", acquired, err)
}
if !reflect.DeepEqual(acquired.Value.Sources.Sources(), native.Sources()) || !reflect.DeepEqual(acquired.Value.Findings.Records, native.Diagnostics()) {
t.Fatalf("lost captured evidence: %#v", acquired.Value)
}
for _, operation := range []string{"sources", "validate"} {
for _, failOutput := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/failOutput=%t", operation, failOutput), func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
scope := ConfigScope(func(context.Context, ckconfig.Selection, struct{}, struct{}) (*promptkit.Engine, error) {
cancel()
return engine, nil
})
unvisited := 0
app, err := commandkit.New(commandkit.Identity{Name: "fixture"}, ckconfig.Command(ckconfig.Suite[struct{}, struct{}]{Scopes: []ckconfig.Scope[struct{}, struct{}]{
{Name: "app", Operations: []ckconfig.Operation{ckconfig.Validate}, Acquire: func(context.Context, ckconfig.Request, struct{}, struct{}) (commandkit.Acquired[ckconfig.View], error) {
return commandkit.Acquired[ckconfig.View]{}, nil
}},
scope,
{Name: "zeta", Operations: []ckconfig.Operation{ckconfig.Validate}, Acquire: func(context.Context, ckconfig.Request, struct{}, struct{}) (commandkit.Acquired[ckconfig.View], error) {
unvisited++
return commandkit.Acquired[ckconfig.View]{}, nil
}},
}}))
if err != nil {
t.Fatal(err)
}
args := []string{"config", operation, "--scope=promptkit", "--format=json"}
if operation == "validate" {
args = []string{"config", "validate", "--scope=all", "--details", "--format=json"}
}
var out bytes.Buffer
var writer io.Writer = &out
writeErr := errors.New("output failed")
if failOutput {
writer = failingDiagnosticWriter{err: writeErr}
}
got := app.Execute(ctx, args, commandkit.Streams{Out: writer, Err: io.Discard})
if !errors.Is(got.Cause, context.Canceled) || unvisited != 0 {
t.Fatalf("outcome=%#v unvisited=%d", got, unvisited)
}
if failOutput {
if !errors.Is(got.Presentation.Output.WriteError, writeErr) {
t.Fatalf("lost presentation failure: %#v", got)
}
} else {
if operation == "sources" {
for _, source := range native.Sources() {
if !strings.Contains(out.String(), source.ID) {
t.Fatalf("missing acquired source: %s", out.String())
}
}
} else if !strings.Contains(out.String(), `"state": "empty"`) || !strings.Contains(out.String(), `"scope": "app"`) || strings.Contains(out.String(), `"scope": "zeta"`) {
t.Fatalf("reached-scope evidence: %s", out.String())
}
}
})
}
}
}

View File

@@ -91,7 +91,7 @@ func buildCommand[I, S any](suite Suite[I, S], aliases *[]commandkit.Declaration
showCommands = append(showCommands, newPreparationCommand(suite, aliases))
}
if len(showCommands) != 0 {
rootCommands = append(rootCommands, commandkit.Group("show", "Show a named PromptKit definition.", showCommands...))
rootCommands = append(rootCommands, commandkit.Group("show", "Show PromptKit definitions or preview a prepared request.", showCommands...))
}
listCommands := make([]commandkit.Command, 0, 5)
if suite.ListPrompts != nil {
@@ -110,7 +110,7 @@ func buildCommand[I, S any](suite Suite[I, S], aliases *[]commandkit.Declaration
listCommands = append(listCommands, newCatalogListCommand(suite, "collections"))
}
if len(listCommands) != 0 {
rootCommands = append(rootCommands, commandkit.Group("list", "List PromptKit catalogs.", listCommands...))
rootCommands = append(rootCommands, commandkit.Group("list", "List available PromptKit resources.", listCommands...))
}
requirementsCommands := make([]commandkit.Command, 0, 2)
if suite.InspectRequirements != nil {
@@ -125,11 +125,11 @@ func buildCommand[I, S any](suite Suite[I, S], aliases *[]commandkit.Declaration
if suite.SmokeTest != nil {
rootCommands = append(rootCommands, newSmokeTestCommand(suite, aliases))
}
command := commandkit.RootGroup("promptkit", "Inspect, list, validate requests, and run PromptKit smoke tests.", rootCommands...)
command := commandkit.RootGroup("promptkit", "Inspect PromptKit resources, check requests, and run smoke tests.", rootCommands...)
for _, issue := range suite.issues {
command = commandkit.WithError(command, issue)
}
return command
return commandkit.WithInvocationFeature(command, usageFeature())
}
func newCatalogListCommand[I, S any](suite Suite[I, S], name string) commandkit.Command {
@@ -140,16 +140,16 @@ func newCatalogListCommand[I, S any](suite Suite[I, S], name string) commandkit.
return &(*input).captured
})
flags = append(flags,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "config", Usage: "Configuration input path.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseDefinitionString,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "config", Usage: "Select the configuration input path.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseDefinitionString,
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,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "overlay", Usage: "Select the configuration overlay path.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseDefinitionString,
func(input **catalogInput[I], value commandkit.Supplied[string]) { (*input).selection.Overlay = value }),
)
if name == "prompts" || name == "profiles" || name == "backends" {
flags = append(flags,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "namespace", Usage: "Select one native namespace."}, (*string)(nil), parseDefinitionString,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "namespace", Usage: "List resources in one namespace."}, (*string)(nil), parseDefinitionString,
func(input **catalogInput[I], value commandkit.Supplied[string]) { (*input).namespace = value }),
commandkit.BoolFlag(commandkit.FlagMeta{Name: "all-namespaces", Usage: "Select identities from every namespace."}, false,
commandkit.BoolFlag(commandkit.FlagMeta{Name: "all-namespaces", Usage: "List resources from every namespace."}, false,
func(input **catalogInput[I], value commandkit.Supplied[bool]) { (*input).allNamespaces = value }),
)
}
@@ -202,7 +202,7 @@ func newCatalogListCommand[I, S any](suite Suite[I, S], name string) commandkit.
}
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))
return definitionFailure(invocation.Context, "Unable to list the selected PromptKit catalog.", commandkit.Explanation{}, fmt.Errorf("unknown PromptKit catalog %q", name))
}
},
})
@@ -243,9 +243,9 @@ func newDefinitionCommand[I, S any](suite Suite[I, S], name string, aliases *[]c
return &(*input).captured
})
flags = append(flags,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "config", Usage: "Configuration input path.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseDefinitionString,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "config", Usage: "Select the configuration input path.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseDefinitionString,
func(input **definitionInput[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,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "overlay", Usage: "Select the configuration overlay path.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseDefinitionString,
func(input **definitionInput[I], value commandkit.Supplied[string]) {
(*input).selection.Overlay = value
}),
@@ -288,11 +288,11 @@ func newRequirementsCommand[I, S any](suite Suite[I, S], aliases *[]commandkit.D
return &(*input).captured
})
flags = append(flags,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "config", Usage: "Configuration input path.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseDefinitionString,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "config", Usage: "Select the configuration input path.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseDefinitionString,
func(input **requirementsInput[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,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "overlay", Usage: "Select the configuration overlay path.", Completion: commandkit.CompleteFiles()}, (*string)(nil), parseDefinitionString,
func(input **requirementsInput[I], value commandkit.Supplied[string]) {
(*input).selection.Overlay = value
}),
@@ -308,8 +308,8 @@ func newRequirementsCommand[I, S any](suite Suite[I, S], aliases *[]commandkit.D
spec := commandkit.CommandSpec[*requirementsInput[I]]{
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.",
Summary: "Discover the inputs and variables a prompt needs.",
Description: "List required inputs without running the prompt. Choosing a profile changes the reported profile ID, not the requirements. A profile namespace applies to a short profile ID supplied here; it does not change the prompt’s stored default reference.",
NewInput: func() *requirementsInput[I] {
return &requirementsInput[I]{}
},
@@ -368,7 +368,7 @@ func runCatalogList[T any, I, S any](
) commandkit.Outcome {
if invocation.Context != nil {
if err := invocation.Context.Err(); err != nil {
return definitionFailure("PromptKit catalog listing was canceled.", commandkit.Explanation{}, err)
return definitionFailure(invocation.Context, "PromptKit catalog listing was canceled.", commandkit.Explanation{}, err)
}
}
var state S
@@ -377,18 +377,18 @@ func runCatalogList[T any, I, S any](
}
if invocation.Context != nil {
if err := invocation.Context.Err(); err != nil {
return definitionFailure("PromptKit catalog listing was canceled.", commandkit.Explanation{}, err)
return definitionFailure(invocation.Context, "PromptKit catalog listing was canceled.", commandkit.Explanation{}, err)
}
}
acquired, err := list(invocation.Context, CatalogRequest{Selection: input.selection, Filter: input.filter}, input.selected, state)
queuePromptDiagnostics(invocation.Reporter(), acquired.Diagnostics)
if err != nil {
return definitionFailure(fmt.Sprintf("Unable to list PromptKit %s.", catalog), acquired.Explanation, err)
return definitionFailure(invocation.Context, fmt.Sprintf("Unable to list PromptKit %s.", catalog), acquired.Explanation, err)
}
if invocation.Context != nil {
if err := invocation.Context.Err(); err != nil {
return definitionFailure("PromptKit catalog listing was canceled.", acquired.Explanation, err)
return definitionFailure(invocation.Context, "PromptKit catalog listing was canceled.", acquired.Explanation, err)
}
}
_ = invocation.Reporter().Report(commandkit.Report{Value: project(acquired.Value)})
@@ -397,14 +397,14 @@ func runCatalogList[T any, I, S any](
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)
return definitionFailure(invocation.Context, "PromptKit inspection was canceled.", commandkit.Explanation{}, err)
}
var state S
if suite.NewState != nil {
state = suite.NewState()
}
if err := promptKitContextError(invocation.Context); err != nil {
return definitionFailure("PromptKit inspection was canceled.", commandkit.Explanation{}, err)
return definitionFailure(invocation.Context, "PromptKit inspection was canceled.", commandkit.Explanation{}, err)
}
var value any
var diagnostics []commandkit.Diagnostic
@@ -435,13 +435,13 @@ func runDefinitionInspection[I, S any](invocation commandkit.Invocation, suite S
}
queuePromptDiagnostics(invocation.Reporter(), diagnostics)
if err != nil {
return definitionFailure(fmt.Sprintf("Unable to inspect PromptKit %s %q.", kind, input.id), explanation, err)
return definitionFailure(invocation.Context, fmt.Sprintf("Unable to inspect PromptKit %s %q.", kind, input.id), explanation, err)
}
if value == nil {
return definitionFailure(fmt.Sprintf("PromptKit %s inspection returned no result.", kind), explanation, nil)
return definitionFailure(invocation.Context, fmt.Sprintf("PromptKit %s inspection returned no result.", kind), explanation, nil)
}
if err := promptKitContextError(invocation.Context); err != nil {
return definitionFailure(fmt.Sprintf("Inspection of PromptKit %s %q was canceled.", kind, input.id), explanation, err)
return definitionFailure(invocation.Context, fmt.Sprintf("Inspection of PromptKit %s %q was canceled.", kind, input.id), explanation, err)
}
_ = invocation.Reporter().Report(commandkit.Report{Value: value})
return commandkit.Success()
@@ -520,7 +520,7 @@ func requirementsReportFromInspection(inspection *promptkit.RequirementInspectio
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 {
return definitionFailure("PromptKit requirements inspection was canceled.", commandkit.Explanation{}, err)
return definitionFailure(invocation.Context, "PromptKit requirements inspection was canceled.", commandkit.Explanation{}, err)
}
}
var state S
@@ -529,7 +529,7 @@ func runRequirementsInspection[I, S any](invocation commandkit.Invocation, suite
}
if invocation.Context != nil {
if err := invocation.Context.Err(); err != nil {
return definitionFailure("PromptKit requirements inspection was canceled.", commandkit.Explanation{}, err)
return definitionFailure(invocation.Context, "PromptKit requirements inspection was canceled.", commandkit.Explanation{}, err)
}
}
@@ -537,14 +537,14 @@ func runRequirementsInspection[I, S any](invocation commandkit.Invocation, suite
acquired, err := suite.InspectRequirements(invocation.Context, request, input.selected, state)
queuePromptDiagnostics(invocation.Reporter(), acquired.Diagnostics)
if err != nil {
return definitionFailure(fmt.Sprintf("Unable to inspect requirements for PromptKit prompt %q.", input.inspection.PromptID), acquired.Explanation, err)
return definitionFailure(invocation.Context, fmt.Sprintf("Unable to inspect requirements for PromptKit prompt %q.", input.inspection.PromptID), acquired.Explanation, err)
}
if acquired.Value == nil {
return definitionFailure("PromptKit requirements inspection returned no result.", acquired.Explanation, nil)
return definitionFailure(invocation.Context, "PromptKit requirements inspection returned no result.", acquired.Explanation, nil)
}
if invocation.Context != nil {
if err := invocation.Context.Err(); err != nil {
return definitionFailure(fmt.Sprintf("Requirements inspection for PromptKit prompt %q was canceled.", input.inspection.PromptID), acquired.Explanation, err)
return definitionFailure(invocation.Context, fmt.Sprintf("Requirements inspection for PromptKit prompt %q was canceled.", input.inspection.PromptID), acquired.Explanation, err)
}
}
_ = invocation.Reporter().Report(commandkit.Report{Value: requirementsReportFromInspection(acquired.Value)})
@@ -602,8 +602,20 @@ func queuePromptDiagnostics(reporter *commandkit.Reporter, diagnostics []command
}
}
func definitionFailure(message string, explanation commandkit.Explanation, cause error) commandkit.Outcome {
func definitionFailure(ctx context.Context, message string, explanation commandkit.Explanation, cause error) commandkit.Outcome {
if ctx != nil {
if canceled := ctx.Err(); canceled != nil {
if cause == nil {
cause = canceled
} else if !errors.Is(cause, canceled) {
cause = errors.Join(cause, canceled)
}
}
}
outcome := commandkit.Failure(message)
if cause != nil && ckconfig.ClassifyConfigurationError(cause) == commandkit.OutcomeUsage {
outcome = commandkit.Usage(message)
}
if explanation.Message != "" || len(explanation.Details) > 0 {
outcome = outcome.WithExplanation(explanation.Message, explanation.Details...)
}

View File

@@ -154,7 +154,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", "--against-campaign", "spring"}, commandkit.Streams{Out: io.Discard, Err: &diagnostics})
if failure.Kind != commandkit.OutcomeOperational || !strings.Contains(diagnostics.String(), `Configuration scope "promptkit" (left):`) {
if failure.Kind != commandkit.OutcomeUsage || !strings.Contains(diagnostics.String(), `Configuration scope "promptkit" (left):`) {
t.Fatalf("installed load failure = %#v, diagnostics %q", failure, diagnostics.String())
}
var loadFailure *configkit.LoadError
@@ -247,6 +247,9 @@ profiles:
if err != nil {
t.Fatal(err)
}
for index := range inputs {
inputs[index].Destination = configkit.Keys("promptkit")
}
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)

View File

@@ -163,6 +163,9 @@ profiles:
if err != nil {
t.Fatal(err)
}
for index := range inputs {
inputs[index].Destination = configkit.Keys("promptkit")
}
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)

View File

@@ -0,0 +1,100 @@
package ckprompt
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"testing"
"go.maximumdirect.net/ckconfig"
"go.maximumdirect.net/commandkit"
"go.maximumdirect.net/configkit"
"go.maximumdirect.net/promptkit"
)
func TestComposedConfigurationInputOutcomes(t *testing.T) {
_, loadErr := configkit.Load[map[string]any](configkit.Bytes("prompt-invalid", []byte("broken: [")))
engine := adapterEngine(t)
calls := 0
scope := ConfigScope(func(_ context.Context, selection ckconfig.Selection, _, _ struct{}) (*promptkit.Engine, error) {
calls++
if selection.Config.Value == "good" {
return engine, nil
}
return nil, fmt.Errorf("wrapped: %w", loadErr)
})
app := newPromptTestApp(t, ckconfig.Command(ckconfig.Suite[struct{}, struct{}]{Scopes: []ckconfig.Scope[struct{}, struct{}]{scope}}))
cases := []struct {
args []string
report string
side string
}{
{[]string{"config", "show"}, "", ""},
{[]string{"config", "sources", "--format=json"}, `"sources"`, ""},
{[]string{"config", "validate", "--details", "--format=json"}, `"code": "yaml.invalid"`, ""},
{[]string{"config", "explain", "--list"}, "", ""},
{[]string{"config", "diff"}, "", "left"},
{[]string{"config", "diff", "--config=good", "--against-config=bad"}, "", "right"},
}
for _, tc := range cases {
t.Run(strings.Join(tc.args, "_"), func(t *testing.T) {
var out, diag bytes.Buffer
args := append(append([]string{}, tc.args...), "--scope=promptkit")
result := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diag})
var native *configkit.LoadError
if result.Status != 2 || !errors.Is(result.Cause, loadErr) || !errors.As(result.Cause, &native) || !strings.Contains(diag.String(), "prompt-invalid") || (tc.report != "" && !strings.Contains(out.String(), tc.report)) || (tc.side != "" && !strings.Contains(diag.String(), "("+tc.side+")")) {
t.Fatalf("result=%#v output=%q diagnostics=%q", result, out.String(), diag.String())
}
})
}
for _, tc := range cases {
ctx, cancel := context.WithCancel(context.Background())
cancel()
before := calls
var out bytes.Buffer
args := append(append([]string{}, tc.args...), "--scope=promptkit")
result := app.Execute(ctx, args, commandkit.Streams{Out: &out, Err: io.Discard})
if result.Status != 1 || !errors.Is(result.Cause, context.Canceled) || calls != before || out.Len() != 0 {
t.Fatalf("canceled %v: %#v output=%q", tc.args, result, out.String())
}
}
}
func TestSmokeConfigurationFailureOutcomes(t *testing.T) {
_, first := configkit.Load[map[string]any](configkit.Bytes("first", []byte("broken: [")))
_, second := configkit.Load[map[string]any](configkit.Bytes("second", []byte("other: [")))
operational := errors.New("provider failure")
for _, tc := range []struct {
name, command string
failures []error
cancel bool
want int
}{
{"single", "reachability", []error{first}, false, 2},
{"all input", "all", []error{first, second, first, second}, false, 2},
{"mixed", "all", []error{first, operational, second, first}, false, 1},
{"cancellation", "all", []error{first}, true, 1},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
calls := 0
app := newPromptTestApp(t, Command(Suite[struct{}, struct{}]{SmokeTest: func(_ context.Context, req SmokeRequest, _, _ struct{}) (commandkit.Acquired[*promptkit.SmokeTestReport], error) {
err := tc.failures[calls]
calls++
if tc.cancel {
cancel()
}
return commandkit.Acquired[*promptkit.SmokeTestReport]{Value: &promptkit.SmokeTestReport{Kind: req.Request.Kind}, Explanation: commandkit.Explanation{Message: fmt.Sprintf("context-%d", calls)}}, err
}}))
var out, diag bytes.Buffer
result := app.Execute(ctx, []string{"promptkit", "test", tc.command, "--format=json"}, commandkit.Streams{Out: &out, Err: &diag})
if result.Status != tc.want || calls != len(tc.failures) || !errors.Is(result.Cause, first) || (tc.name == "all input" && !errors.Is(result.Cause, second)) || (tc.name == "mixed" && (!errors.Is(result.Cause, second) || !errors.Is(result.Cause, operational))) || (tc.cancel && !errors.Is(result.Cause, context.Canceled)) || out.Len() == 0 || !strings.Contains(diag.String(), "context-1") {
t.Fatalf("outcome=%#v calls=%d report=%q diagnostics=%q", result, calls, out.String(), diag.String())
}
})
}
}

View File

@@ -0,0 +1,209 @@
package ckprompt
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"testing"
"go.maximumdirect.net/ckconfig"
"go.maximumdirect.net/commandkit"
"go.maximumdirect.net/configkit"
"go.maximumdirect.net/promptkit"
)
func TestPromptConfigurationFailureCallbacks(t *testing.T) {
_, loadErr := configkit.Load[map[string]any](configkit.Bytes("prompt-config", []byte("broken: [")))
var native *configkit.LoadError
if !errors.As(loadErr, &native) {
t.Fatalf("fixture: %v", loadErr)
}
wrapped := fmt.Errorf("load: %w", loadErr)
diag := commandkit.Explanation{Message: "configuration diagnostic"}
suite := Suite[struct{}, struct{}]{
ListPrompts: func(context.Context, CatalogRequest, struct{}, struct{}) (commandkit.Acquired[[]promptkit.PromptIdentity], error) {
return commandkit.Acquired[[]promptkit.PromptIdentity]{Explanation: diag}, wrapped
},
ListProfiles: func(context.Context, CatalogRequest, struct{}, struct{}) (commandkit.Acquired[[]string], error) {
return commandkit.Acquired[[]string]{Explanation: diag}, wrapped
},
ListBackends: func(context.Context, CatalogRequest, struct{}, struct{}) (commandkit.Acquired[[]string], error) {
return commandkit.Acquired[[]string]{Explanation: diag}, wrapped
},
ListNamespaces: func(context.Context, NamespaceRequest, struct{}, struct{}) (commandkit.Acquired[[]string], error) {
return commandkit.Acquired[[]string]{Explanation: diag}, wrapped
},
ListCollections: func(context.Context, ckconfig.Selection, struct{}, struct{}) (commandkit.Acquired[[]promptkit.CollectionInfo], error) {
return commandkit.Acquired[[]promptkit.CollectionInfo]{Explanation: diag}, wrapped
},
InspectPrompt: func(context.Context, PromptRequest, struct{}, struct{}) (commandkit.Acquired[*promptkit.PromptInspection], error) {
return commandkit.Acquired[*promptkit.PromptInspection]{Explanation: diag}, wrapped
},
InspectProfile: func(context.Context, ProfileRequest, struct{}, struct{}) (commandkit.Acquired[*promptkit.ProfileInspection], error) {
return commandkit.Acquired[*promptkit.ProfileInspection]{Explanation: diag}, wrapped
},
InspectBackend: func(context.Context, BackendRequest, struct{}, struct{}) (commandkit.Acquired[*promptkit.BackendInspection], error) {
return commandkit.Acquired[*promptkit.BackendInspection]{Explanation: diag}, wrapped
},
InspectRequirements: func(context.Context, RequirementsRequest, struct{}, struct{}) (commandkit.Acquired[*promptkit.RequirementInspection], error) {
return commandkit.Acquired[*promptkit.RequirementInspection]{Explanation: diag}, wrapped
},
ValidateRequest: func(context.Context, ValidationRequest, struct{}, struct{}) (commandkit.Acquired[struct{}], error) {
return commandkit.Acquired[struct{}]{Explanation: diag}, wrapped
},
PrepareRequest: func(context.Context, PreparationRequest, struct{}, struct{}) (commandkit.Acquired[*promptkit.PreparedRun], error) {
return commandkit.Acquired[*promptkit.PreparedRun]{Explanation: diag}, wrapped
},
}
app := newPromptTestApp(t, Command(suite))
for _, args := range [][]string{{"promptkit", "list", "prompts"}, {"promptkit", "list", "profiles"}, {"promptkit", "list", "backends"}, {"promptkit", "list", "namespaces"}, {"promptkit", "list", "collections"}, {"promptkit", "show", "prompt", "example"}, {"promptkit", "show", "profile", "example"}, {"promptkit", "show", "backend", "example"}, {"promptkit", "requirements", "show", "example"}, {"promptkit", "requirements", "validate", "example"}, {"promptkit", "show", "prepared", "example"}} {
t.Run(strings.Join(args, "_"), func(t *testing.T) {
var out, diagnostic bytes.Buffer
result := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diagnostic})
var got *configkit.LoadError
if result.Kind != commandkit.OutcomeUsage || result.Status != 2 || !errors.Is(result.Cause, loadErr) || !errors.As(result.Cause, &got) || got != native || !strings.Contains(diagnostic.String(), "configuration diagnostic") {
t.Fatalf("outcome=%#v diagnostics=%q", result, diagnostic.String())
}
})
}
}
func TestPromptNativeConfigurationFailures(t *testing.T) {
_, loadErr := configkit.Load[map[string]any](configkit.Bytes("native-config", []byte("broken: [")))
load := func(context.Context, ckconfig.Selection, struct{}, struct{}) (*promptkit.Engine, error) {
return nil, fmt.Errorf("wrapped: %w", loadErr)
}
suite := FromEngine[struct{}, struct{}](load)
suite = WithRequestValidation(suite, load, nil)
suite = WithRequestPreparation(suite, load, nil)
app := newPromptTestApp(t, Command(suite))
for _, args := range [][]string{{"promptkit", "list", "prompts"}, {"promptkit", "show", "prompt", "example"}, {"promptkit", "requirements", "show", "example"}, {"promptkit", "requirements", "validate", "example"}, {"promptkit", "show", "prepared", "example"}} {
t.Run(strings.Join(args, "_"), func(t *testing.T) {
var diag bytes.Buffer
result := app.Execute(context.Background(), args, commandkit.Streams{Out: io.Discard, Err: &diag})
var native *configkit.LoadError
if result.Status != 2 || !errors.Is(result.Cause, loadErr) || !errors.As(result.Cause, &native) || !strings.Contains(diag.String(), "native-config") {
t.Fatalf("outcome=%#v diagnostics=%q", result, diag.String())
}
})
}
}
func TestBuilderConfigurationFailureDiagnostics(t *testing.T) {
_, malformed := configkit.Load[map[string]any](configkit.Bytes("builder-config", []byte("broken: [")))
path := configkit.Keys("version")
_, rejected := configkit.Load(configkit.Bytes("builder-config", []byte("version: 1\n")), configkit.Options[map[string]any]{
Definition: configkit.Definition[map[string]any]{Version: &configkit.VersionRule{
Path: path,
Check: func(_ configkit.Version, validation *configkit.Validation) error {
validation.Warning(path, "builder warning")
validation.Error(path, "builder rejection")
return nil
},
}},
})
for _, fixture := range []struct {
name string
cause error
code string
warning string
status int
}{
{"malformed", malformed, "yaml.invalid", "", 2},
{"rejected", rejected, "version.error", "builder warning", 2},
{"application failure", errors.New("builder unavailable"), "", "", 1},
} {
if fixture.cause == nil {
t.Fatalf("%s fixture succeeded", fixture.name)
}
for _, args := range [][]string{
{"promptkit", "requirements", "validate", "example"},
{"promptkit", "show", "prepared", "example"},
{"promptkit", "test", "reachability"},
{"promptkit", "test", "all"},
} {
for _, canceled := range []bool{false, true} {
name := fmt.Sprintf("%s/%s/canceled=%t", fixture.name, strings.Join(args, "_"), canceled)
t.Run(name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
loaderCalls, builderCalls := 0, 0
load := func(context.Context, ckconfig.Selection, struct{}, struct{}) (*promptkit.Engine, error) {
loaderCalls++
return nil, errors.New("unexpected engine load")
}
wrapped := fmt.Errorf("builder load: %w", fixture.cause)
buildError := func() error {
builderCalls++
if canceled {
cancel()
}
return wrapped
}
suite := WithRequestValidation(Suite[struct{}, struct{}]{}, load, func(context.Context, ValidationRequest, struct{}, struct{}) (promptkit.RunRequest, error) {
return promptkit.RunRequest{}, buildError()
})
suite = WithRequestPreparation(suite, load, func(context.Context, PreparationRequest, struct{}, struct{}) (promptkit.RunRequest, error) {
return promptkit.RunRequest{}, buildError()
})
suite = WithSmokeTesting(suite, load, func(context.Context, SmokeRequest, struct{}, struct{}) (promptkit.SmokeTestRequest, error) {
return promptkit.SmokeTestRequest{}, buildError()
})
app := newPromptTestApp(t, Command(suite))
var out, diagnostic bytes.Buffer
result := app.Execute(ctx, append(append([]string{}, args...), "--verbose"), commandkit.Streams{Out: &out, Err: &diagnostic})
wantStatus, wantCalls := fixture.status, 1
if args[len(args)-1] == "all" && !canceled {
wantCalls = 4
}
if canceled {
wantStatus = 1
if !errors.Is(result.Cause, context.Canceled) {
t.Fatalf("lost cancellation: %#v", result)
}
}
if result.Status != wantStatus || !errors.Is(result.Cause, wrapped) || loaderCalls != 0 || builderCalls != wantCalls {
t.Fatalf("result=%#v loader calls=%d builder calls=%d", result, loaderCalls, builderCalls)
}
if fixture.code != "" {
var expected, retained *configkit.LoadError
if !errors.As(fixture.cause, &expected) || !errors.As(result.Cause, &retained) || retained != expected {
t.Fatalf("lost loading error: %#v", result)
}
if !strings.Contains(diagnostic.String(), fixture.code) || !strings.Contains(diagnostic.String(), "builder-config") || !strings.Contains(diagnostic.String(), fixture.warning) {
t.Fatalf("diagnostics: %q", diagnostic.String())
}
}
})
}
}
}
}
func TestPromptConfigurationFailureCancellation(t *testing.T) {
_, loadErr := configkit.Load[map[string]any](configkit.Bytes("invalid", []byte("broken: [")))
ctx, cancel := context.WithCancel(context.Background())
calls := 0
suite := Suite[struct{}, struct{}]{InspectPrompt: func(context.Context, PromptRequest, struct{}, struct{}) (commandkit.Acquired[*promptkit.PromptInspection], error) {
calls++
cancel()
return commandkit.Acquired[*promptkit.PromptInspection]{}, loadErr
}}
app := newPromptTestApp(t, Command(suite))
var out bytes.Buffer
result := app.Execute(ctx, []string{"promptkit", "show", "prompt", "example"}, commandkit.Streams{Out: &out, Err: io.Discard})
if result.Status != 1 || !errors.Is(result.Cause, context.Canceled) || !errors.Is(result.Cause, loadErr) || out.Len() != 0 || calls != 1 {
t.Fatalf("outcome=%#v calls=%d output=%q", result, calls, out.String())
}
ctx, cancel = context.WithCancel(context.Background())
cancel()
calls = 0
result = app.Execute(ctx, []string{"promptkit", "show", "prompt", "example"}, commandkit.Streams{Out: &out, Err: io.Discard})
if result.Status != 1 || !errors.Is(result.Cause, context.Canceled) || calls != 0 || out.Len() != 0 {
t.Fatalf("pre-canceled=%#v calls=%d", result, calls)
}
}

View File

@@ -0,0 +1,133 @@
package ckprompt
import (
"bytes"
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"go.maximumdirect.net/ckconfig"
"go.maximumdirect.net/commandkit"
"go.maximumdirect.net/configkit"
"go.maximumdirect.net/promptkit"
)
func TestPromptConstructorConfigurationOutcomes(t *testing.T) {
dir := t.TempDir()
mainPath := filepath.Join(dir, "config.yml")
companionPath := filepath.Join(dir, "prompts.yml")
for path, data := range map[string]string{mainPath: "companion: prompts.yml\n", companionPath: "profiles: [\n"} {
if err := os.WriteFile(path, []byte(data), 0600); err != nil {
t.Fatal(err)
}
}
good := adapterEngine(t)
var constructorErr error
load := func(_ context.Context, selection ckconfig.Selection, _, _ struct{}) (*promptkit.Engine, error) {
if selection.Config.Value == "good" {
return good, nil
}
appConfig, err := configkit.Load[struct {
Companion string `yaml:"companion"`
}](configkit.File(selection.Config.Value))
if err != nil {
return nil, err
}
companion := filepath.Join(filepath.Dir(selection.Config.Value), appConfig.Config.Companion)
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Main: &configkit.Input{Source: configkit.File(companion)}}}, promptkit.WithBundledOpenRouter(false))
constructorErr = err
return engine, err
}
app := newPromptTestApp(t, Command(FromEngine[struct{}, struct{}](load)), ckconfig.Command(ckconfig.Suite[struct{}, struct{}]{Scopes: []ckconfig.Scope[struct{}, struct{}]{ConfigScope(load)}}))
cases := []struct {
name string
args []string
report, side string
}{
{"catalog", []string{"promptkit", "list", "prompts", "--config", mainPath}, "", ""},
{"show", []string{"config", "show", "--scope=promptkit", "--config", mainPath}, "", ""},
{"sources", []string{"config", "sources", "--format=json", "--scope=promptkit", "--config", mainPath}, `"sources"`, ""},
{"validate", []string{"config", "validate", "--details", "--format=json", "--scope=promptkit", "--config", mainPath}, `"code": "yaml.invalid"`, ""},
{"explain", []string{"config", "explain", "--list", "--scope=promptkit", "--config", mainPath}, "", ""},
{"diff left", []string{"config", "diff", "--scope=promptkit", "--config", mainPath, "--against-config=good"}, "", "left"},
{"diff right", []string{"config", "diff", "--scope=promptkit", "--config=good", "--against-config", mainPath}, "", "right"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
constructorErr = nil
var out, diag bytes.Buffer
result := app.Execute(context.Background(), tc.args, commandkit.Streams{Out: &out, Err: &diag})
var actual, expected *configkit.LoadError
if constructorErr == nil || !errors.As(constructorErr, &expected) || !errors.As(result.Cause, &actual) || actual != expected || !errors.Is(result.Cause, constructorErr) || !errors.Is(result.Cause, promptkit.ErrInvalidConfig) || result.Kind != commandkit.OutcomeUsage || result.Status != 2 {
t.Fatalf("outcome=%#v constructor=%v diagnostic=%q", result, constructorErr, diag.String())
}
if !strings.Contains(diag.String(), "yaml.invalid") || !strings.Contains(diag.String(), "prompts.yml") || (tc.report != "" && !strings.Contains(out.String(), tc.report)) || (tc.side != "" && !strings.Contains(diag.String(), "("+tc.side+")")) {
t.Fatalf("output=%q diagnostics=%q", out.String(), diag.String())
}
if tc.name == "sources" && !strings.Contains(out.String(), "prompts.yml") {
t.Fatalf("source evidence missing companion: %q", out.String())
}
})
}
}
func TestPromptConstructorFailurePrecedence(t *testing.T) {
dir := t.TempDir()
malformed := filepath.Join(dir, "prompts.yml")
if err := os.WriteFile(malformed, []byte("profiles: [\n"), 0600); err != nil {
t.Fatal(err)
}
_, invalid := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Main: &configkit.Input{Source: configkit.File(malformed)}}}, promptkit.WithBundledOpenRouter(false))
_, missing := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Main: &configkit.Input{Source: configkit.File(filepath.Join(dir, "missing.yml"))}}}, promptkit.WithBundledOpenRouter(false))
if invalid == nil || missing == nil || !errors.Is(invalid, promptkit.ErrInvalidConfig) || !errors.Is(missing, promptkit.ErrInvalidConfig) {
t.Fatalf("constructor fixtures invalid=%v missing=%v", invalid, missing)
}
operational := errors.New("independent failure")
for _, tc := range []struct {
name string
cause error
extra error
canceled bool
kind commandkit.OutcomeKind
}{
{"missing configuration", missing, promptkit.ErrInvalidConfig, false, commandkit.OutcomeOperational},
{"joined missing error", errors.Join(missing, os.ErrNotExist), os.ErrNotExist, false, commandkit.OutcomeOperational},
{"joined operational", errors.Join(invalid, operational), operational, false, commandkit.OutcomeOperational},
{"joined cancellation", errors.Join(invalid, context.Canceled), context.Canceled, false, commandkit.OutcomeOperational},
{"already canceled", nil, context.Canceled, true, commandkit.OutcomeOperational},
} {
for _, args := range [][]string{{"promptkit", "list", "prompts"}, {"config", "show", "--scope=promptkit"}} {
t.Run(tc.name+"/"+strings.Join(args, "_"), func(t *testing.T) {
calls := 0
load := func(context.Context, ckconfig.Selection, struct{}, struct{}) (*promptkit.Engine, error) {
calls++
if tc.cause != nil {
return nil, tc.cause
}
return adapterEngine(t), nil
}
app := newPromptTestApp(t, Command(FromEngine[struct{}, struct{}](load)), ckconfig.Command(ckconfig.Suite[struct{}, struct{}]{Scopes: []ckconfig.Scope[struct{}, struct{}]{ConfigScope(load)}}))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if tc.canceled {
cancel()
}
var out bytes.Buffer
result := app.Execute(ctx, args, commandkit.Streams{Out: &out})
if result.Kind != tc.kind || !errors.Is(result.Cause, tc.extra) {
t.Fatalf("outcome=%#v output=%q", result, out.String())
}
if tc.canceled {
if calls != 0 || out.Len() != 0 {
t.Fatalf("calls=%d output=%q", calls, out.String())
}
} else if calls != 1 || !errors.Is(result.Cause, tc.cause) || !errors.Is(result.Cause, promptkit.ErrInvalidConfig) {
t.Fatalf("outcome=%#v calls=%d", result, calls)
}
})
}
}
}

View File

@@ -1,13 +1,23 @@
// Package ckprompt, provided by go.maximumdirect.net/ckprompt, provides optional
// PromptKit configuration comparison,
// prompt catalogs, named inspections, requirements discovery and validation,
// 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. This module uses
// PromptKit v0.20.0 and its native engine inventory, including configured
// bundled resources.
// Package ckprompt adds PromptKit inspection and testing commands to CommandKit
// applications. Operators can list resources, inspect definitions, discover
// required inputs, validate and preview requests, and run smoke tests.
//
// Start with FromEngine and add optional operations with WithRequestValidation,
// WithRequestPreparation, and WithSmokeTesting. Command returns the command
// family; Declarations also includes its convenience flag aliases. Install
// these with commandkit.New or App.Register.
//
// A nonempty family installs --show-tokens for application commands as well as
// PromptKit commands. When requested, it observes PromptKit calls using the
// invocation context and reports usage on diagnostics after execution. Applications
// must pass that context to their work and wait for their own work before returning.
// Empty suites install no flag. Smoke-test usage remains in the command report.
//
// ConfigScope separately exposes engine configuration through ckconfig.
// ConfigScope preserves PromptKit focused discovery and whole-load evidence.
// Applications can compose PromptKit settings into an application-owned load
// and pass the completed result to promptkit.NewFromConfig.
//
// Importing this package installs neither command family. Applications own
// engine construction, credentials, and client configuration.
package ckprompt

View File

@@ -2,53 +2,53 @@
## PromptKit
Selected module: `go.maximumdirect.net/promptkit` at `v0.20.0`.
Selected module: `go.maximumdirect.net/promptkit` at `v0.25.0`.
Copyright (C) 2026 Eric Rakestraw
SPDX-License-Identifier: LGPL-3.0-or-later
License and notices: [LGPL v3.0](../../LICENSE) |
[LICENSE](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf/LICENSE).
[LICENSE](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/LICENSE).
[Source](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/8ff9aa3efdc9f16b9d2729e0a29ea083eb3c3eaf).
[Source](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d).
## ConfigKit
Selected module: `go.maximumdirect.net/configkit` at `v1.1.0` (direct dependency).
Selected module: `go.maximumdirect.net/configkit` at `v1.4.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://forge.maximumdirect.net/base-layer/configkit/src/commit/191015e289d7f2b91abb9fdd9c4f2f5cf75b4de9/LICENSE).
[LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3/LICENSE).
[Source](https://forge.maximumdirect.net/base-layer/configkit/src/commit/191015e289d7f2b91abb9fdd9c4f2f5cf75b4de9).
[Source](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3).
## ReleaseKit
Selected module: `go.maximumdirect.net/releasekit` at `v0.9.0` (transitive Go tool requirement; not a runtime import).
Selected module: `go.maximumdirect.net/releasekit` at `v0.10.0` (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://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4/LICENSE).
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243/LICENSE).
[Source](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/2180aa868ec2caa95fc8279fd59d5f0ebac41bd4).
[Source](https://forge.maximumdirect.net/base-layer/releasekit/src/commit/82bac1a3ab935beddd4b8789d1e07f52135d4243).
## JSON Schema
Selected module: `github.com/santhosh-tekuri/jsonschema/v6` at `v6.0.2` (transitive dependency).
Selected module: `github.com/santhosh-tekuri/jsonschema/v6` at `v6.0.3` (transitive dependency).
SPDX-License-Identifier: Apache-2.0
License and notices: [Apache 2.0](licenses/Apache-2.0.txt) |
[LICENSE](https://github.com/santhosh-tekuri/jsonschema/blob/29cbed948d24a04700eb94436416b18a07953b71/LICENSE).
[LICENSE](https://github.com/santhosh-tekuri/jsonschema/blob/b0fc661f4939578bc429f408c18202573dbafcc4/LICENSE).
[Source](https://github.com/santhosh-tekuri/jsonschema/tree/29cbed948d24a04700eb94436416b18a07953b71).
[Source](https://github.com/santhosh-tekuri/jsonschema/tree/b0fc661f4939578bc429f408c18202573dbafcc4).
## Regular expression engine
@@ -65,17 +65,17 @@ License and notices: [MIT](licenses/MIT.txt) |
## Go text
Selected module: `golang.org/x/text` at `v0.14.0` (transitive dependency).
Selected module: `golang.org/x/text` at `v0.44.0` (transitive dependency).
Copyright (c) 2009 The Go Authors. All rights reserved.
Copyright 2009 The Go Authors.
SPDX-License-Identifier: BSD-3-Clause
License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) |
[LICENSE](https://go.googlesource.com/text/+/6c97a165dd661335ff7bce6104a008558123c353/LICENSE) |
[PATENTS](https://go.googlesource.com/text/+/6c97a165dd661335ff7bce6104a008558123c353/PATENTS).
[LICENSE](https://go.googlesource.com/text/+/6070ac32abcdd1670599eeb3ee4d513c8184a513/LICENSE) |
[PATENTS](https://go.googlesource.com/text/+/6070ac32abcdd1670599eeb3ee4d513c8184a513/PATENTS).
[Source](https://go.googlesource.com/text/+/6c97a165dd661335ff7bce6104a008558123c353).
[Source](https://go.googlesource.com/text/+/6070ac32abcdd1670599eeb3ee4d513c8184a513).
## Standard Repository Policies
@@ -85,8 +85,9 @@ root): `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
the core module. The release policy uses baseline
`e833faddf120c789a9b45348edaf75720de16348`; the remaining material uses baseline
the core module. The documentation policy uses baseline
`beb5f191470a9daef2383981a6bfd02232490ab4`; the release policy uses
`e833faddf120c789a9b45348edaf75720de16348`; the remaining material uses
`d84a38ebab26f048cafbe59a2246700c35d29843`.
Copyright (C) 2026 Eric Rakestraw
@@ -97,15 +98,19 @@ 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).
## go-yaml v4
Selected module: `go.yaml.in/yaml/v4` at `v4.0.0-rc.6`.
Selected module: `go.yaml.in/yaml/v4` at `v4.0.0`.
Copyright 2006-2010 Kirill Simonov
@@ -115,14 +120,14 @@ Copyright 2025 The go-yaml Project Contributors
License and notices: [Apache 2.0](licenses/Apache-2.0.txt) |
[MIT](licenses/MIT.txt) |
[LICENSE](https://github.com/yaml/go-yaml/blob/1c17b9cee72bf81ae73a8be50fbd7dd3a9985125/LICENSE) |
[NOTICE](https://github.com/yaml/go-yaml/blob/1c17b9cee72bf81ae73a8be50fbd7dd3a9985125/NOTICE).
[LICENSE](https://github.com/yaml/go-yaml/blob/f2f9563503f11b7a60da0c532175dcc693ce8d5a/LICENSE) |
[NOTICE](https://github.com/yaml/go-yaml/blob/f2f9563503f11b7a60da0c532175dcc693ce8d5a/NOTICE).
[Source](https://github.com/yaml/go-yaml/tree/1c17b9cee72bf81ae73a8be50fbd7dd3a9985125).
[Source](https://github.com/yaml/go-yaml/tree/f2f9563503f11b7a60da0c532175dcc693ce8d5a).
## go-yaml v3
Selected module: `gopkg.in/yaml.v3` at `v3.0.1` (transitive dependency).
Selected module: `go.yaml.in/yaml/v3` at `v3.0.4` (transitive dependency).
Copyright (c) 2006-2010 Kirill Simonov
@@ -132,77 +137,80 @@ Copyright 2011-2016 Canonical Ltd.
License and notices: [MIT](licenses/MIT.txt) |
[Apache 2.0](licenses/Apache-2.0.txt) |
[LICENSE](https://github.com/go-yaml/yaml/blob/f6f7691b1fdeb513f56608cd2c32c51f8194bf51/LICENSE) |
[NOTICE](https://github.com/go-yaml/yaml/blob/f6f7691b1fdeb513f56608cd2c32c51f8194bf51/NOTICE).
[LICENSE](https://github.com/yaml/go-yaml/blob/c3552c15f996075a7634df5159d9161c67bf3d76/LICENSE) |
[NOTICE](https://github.com/yaml/go-yaml/blob/c3552c15f996075a7634df5159d9161c67bf3d76/NOTICE).
[Source](https://github.com/go-yaml/yaml/tree/f6f7691b1fdeb513f56608cd2c32c51f8194bf51).
[Source](https://github.com/yaml/go-yaml/tree/c3552c15f996075a7634df5159d9161c67bf3d76).
## Go modules
Selected module: `golang.org/x/mod` at `v0.40.0` (ReleaseKit tool dependency).
Selected module: `golang.org/x/mod` at `v0.43.0` (ReleaseKit tool dependency).
Copyright 2009 The Go Authors.
SPDX-License-Identifier: BSD-3-Clause
License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) |
[LICENSE](https://go.googlesource.com/mod/+/d3398d06de5fa5c71083d3d1c26f2cda73508e0f/LICENSE).
[LICENSE](https://go.googlesource.com/mod/+/d4f320b9266480df5ed3d791e0c68e64c58c5dde/LICENSE) |
[PATENTS](https://go.googlesource.com/mod/+/d4f320b9266480df5ed3d791e0c68e64c58c5dde/PATENTS).
[Source](https://go.googlesource.com/mod/+/d3398d06de5fa5c71083d3d1c26f2cda73508e0f).
[Source](https://go.googlesource.com/mod/+/d4f320b9266480df5ed3d791e0c68e64c58c5dde).
## Go tools
Selected module: `golang.org/x/tools` at `v0.6.0` (transitive dependency).
Selected module: `golang.org/x/tools` at `v0.52.0` (transitive dependency).
Copyright (c) 2009 The Go Authors. All rights reserved.
Copyright 2009 The Go Authors.
SPDX-License-Identifier: BSD-3-Clause
License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) |
[LICENSE](https://go.googlesource.com/tools/+/d0863f03daeff79ab917de5768285bb077f77b20/LICENSE).
[LICENSE](https://go.googlesource.com/tools/+/16517d951552611e7bd358c48ee1051fd0e57b0c/LICENSE) |
[PATENTS](https://go.googlesource.com/tools/+/16517d951552611e7bd358c48ee1051fd0e57b0c/PATENTS).
[Source](https://go.googlesource.com/tools/+/d0863f03daeff79ab917de5768285bb077f77b20).
[Source](https://go.googlesource.com/tools/+/16517d951552611e7bd358c48ee1051fd0e57b0c).
## Go system
## Go synchronization
Selected module: `golang.org/x/sys` at `v0.5.0` (transitive dependency).
Selected module: `golang.org/x/sync` at `v0.25.0` (transitive dependency).
Copyright (c) 2009 The Go Authors. All rights reserved.
Copyright 2009 The Go Authors.
SPDX-License-Identifier: BSD-3-Clause
License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) |
[LICENSE](https://go.googlesource.com/sys/+/90c8f94a055257f9ab343137cbada4e658750fbb/LICENSE).
[LICENSE](https://go.googlesource.com/sync/+/1f920df1e8fcf601d1aaf0f2ea500e1d2ccce105/LICENSE) |
[PATENTS](https://go.googlesource.com/sync/+/1f920df1e8fcf601d1aaf0f2ea500e1d2ccce105/PATENTS).
[Source](https://go.googlesource.com/sys/+/90c8f94a055257f9ab343137cbada4e658750fbb).
[Source](https://go.googlesource.com/sync/+/1f920df1e8fcf601d1aaf0f2ea500e1d2ccce105).
## Goldmark
Selected module: `github.com/yuin/goldmark/v2` at `v2.1.6` (ReleaseKit tool dependency).
Selected module: `github.com/yuin/goldmark/v2` at `v2.1.16` (ReleaseKit tool dependency).
Copyright (c) 2019 Yusuke Inuzuka
SPDX-License-Identifier: MIT
License and notices: [MIT](licenses/MIT.txt) |
[LICENSE](https://github.com/yuin/goldmark/blob/a8d4ee5a0bd7d5493fdd1e339b4e75df92f8684c/LICENSE).
[LICENSE](https://github.com/yuin/goldmark/blob/c3f939122ba4dd6f80e05043ad195b82e77fcb41/LICENSE).
[Source](https://github.com/yuin/goldmark/tree/a8d4ee5a0bd7d5493fdd1e339b4e75df92f8684c).
[Source](https://github.com/yuin/goldmark/tree/c3f939122ba4dd6f80e05043ad195b82e77fcb41).
## Cobra
Selected module: `github.com/spf13/cobra` at `v1.10.1` (core dependency).
Selected module: `github.com/spf13/cobra` at `v1.10.2` (core dependency).
SPDX-License-Identifier: Apache-2.0
License and notices: [Apache 2.0](licenses/Apache-2.0.txt) |
[LICENSE.txt](https://github.com/spf13/cobra/blob/7da941c3547e93b8c9f70bbd3befca79c6335388/LICENSE.txt).
[LICENSE.txt](https://github.com/spf13/cobra/blob/88b30ab89da2d0d0abb153818746c5a2d30eccec/LICENSE.txt).
[Source](https://github.com/spf13/cobra/tree/7da941c3547e93b8c9f70bbd3befca79c6335388).
[Source](https://github.com/spf13/cobra/tree/88b30ab89da2d0d0abb153818746c5a2d30eccec).
## pflag
Selected module: `github.com/spf13/pflag` at `v1.0.9` (core dependency).
Selected module: `github.com/spf13/pflag` at `v1.1.0` (core dependency).
Copyright (c) 2012 Alex Ogier. All rights reserved.
@@ -211,9 +219,9 @@ Copyright (c) 2012 The Go Authors. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) |
[LICENSE](https://github.com/spf13/pflag/blob/10438578954bba2527fe5cae3684d4532b064bbe/LICENSE).
[LICENSE](https://github.com/spf13/pflag/blob/f8a990678a6d44385313e9b19e40737f889f9b14/LICENSE).
[Source](https://github.com/spf13/pflag/tree/10438578954bba2527fe5cae3684d4532b064bbe).
[Source](https://github.com/spf13/pflag/tree/f8a990678a6d44385313e9b19e40737f889f9b14).
## go-md2man

View File

@@ -0,0 +1,4 @@
# ckprompt release errata
The v0.2.0 release note links to the wrong consumer-guide section. The correct
pinned section is [PromptKit configuration, definitions, and requirements](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.2.0/docs/consumers/guide.md#promptkit-configuration-definitions-and-requirements).

View File

@@ -0,0 +1,33 @@
# CommandKit ckprompt v0.10.0
CommandKit ckprompt v0.10.0 aligns with CommandKit core v0.7.0 and ckconfig
v0.9.0 and adopts PromptKit v0.23.2.
## Dependency updates
- ConfigKit v1.2.1 and stable go-yaml v4.0.0 update configuration loading.
- jsonschema v6.0.3 fixes validation-location reporting and numeric and email
validation edge cases. Go Text advances to v0.44.0.
- The selected core updates Cobra to v1.10.2 and pflag to v1.1.0. The
maintainer workflow uses ReleaseKit v0.10.0 and Go 1.27.4.
## Compatibility and upgrade
Pair `go.maximumdirect.net/ckprompt v0.10.0` with ckconfig v0.9.0 and core
v0.7.0. The consumer minimum remains Go 1.27.0. Applications continue to
construct engines and native requests through the existing callbacks.
Upstream validator fixes can change edge-case validation results and diagnostic
locations. Review scripts that depend on exact backend diagnostic or help text.
See the [consumer guide](../../../../docs/consumers/guide.md#promptkit-configuration-definitions-and-requirements)
and [PromptKit upgrade guidance](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/docs/releases/v0.23.2.md#compatibility-and-upgrade).
Configuration failures retain the classification introduced in ckprompt v0.9.0.
Identifiable invalid input selects status `2`; operational failures and
cancellation select status `1` under the
[configuration-failure contract](../../../../docs/cli.md#configuration-failure-classification).
When upgrading from v0.8.0 or earlier, also review the
[v0.9.0 upgrade guidance](v0.9.0.md#compatibility-and-upgrade).
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.10.0/integrations/ckprompt/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.10.0/integrations/ckprompt/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.10.0/integrations/ckprompt/docs/oss/attribution.md)

View File

@@ -0,0 +1,38 @@
# CommandKit ckprompt v0.11.0
CommandKit ckprompt v0.11.0 adopts PromptKit v0.24.0 and ConfigKit v1.4.0.
It supports application-owned shared configuration loading and exposes native
focused PromptKit inspection. Core remains v0.7.0 and the consumer minimum
remains Go 1.27.0.
## Compatibility and upgrade
This release selects ckconfig v0.10.0. Complete PromptKit
configuration documents now place settings under `promptkit`; mount wrapperless
settings with `SettingsInput` and collection fragments with `CollectionInput`.
Discovery inputs for fragments need an explicit destination. Resource IDs do
not gain a prefix, but configuration paths now use native locations such as
`/promptkit/profiles/0/model`. Focused listings use native paths; explicit
queries, sources, diagnostics, and comparison retain whole-load context.
PromptKit removed `Config.SchemaDir`, `WithSchemaFS`, and `WithSchemaFile`.
Use supported inline, source-relative, or explicit-root schema selection.
Request builders replace validation with `*promptkit.OutputContractInput`;
its pointer repair budget distinguishes omission from explicit zero. Resolved
reports include the budget, including zero, and prompt reports include native
schema selections. The default enables one repair for eligible modes, which
can add a generation call, latency, and usage. Applications own resource-version
policy and sensitivity of their extension fields.
Prepared reports now include `message_content_hash` and native schema evidence.
Migrate positional `PreparedRun` literals to keyed fields; older JSON without
the hash decodes with an empty hash. See the [PromptKit migration guide](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.24.0/docs/consumers/configuration-migration.md),
[format reference](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.24.0/docs/formats.md),
and [release notes](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.24.0/docs/releases/v0.24.0.md)
for the upstream contract. PromptKit v0.23.3's timeout and cancellation identity
corrections are included. The [consumer guide](../../../../docs/consumers/guide.md#promptkit-configuration-definitions-and-requirements)
links the maintained shared-load example.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.11.0/integrations/ckprompt/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.11.0/integrations/ckprompt/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.11.0/integrations/ckprompt/docs/oss/attribution.md)

View File

@@ -0,0 +1,58 @@
# CommandKit ckprompt v0.12.0
CommandKit ckprompt v0.12.0 adopts PromptKit v0.25.0 and adds automatic,
invocation-scoped token and cost reporting through normal integration installation.
## Automatic usage reporting
Both `Command` and `Declarations` install `--show-tokens` for application-owned
commands and the PromptKit family. Applications pass `Invocation.Context` through
their PromptKit work and wait for work they own before returning; no request
observers, accounting groups, or final reporting callbacks are needed in handlers.
Empty suites continue to install no commands, namespace, or usage capability.
The flag defaults to false, has no shorthand, accepts explicit false, and uses
the last occurrence when repeated. When enabled, the summary appears on
diagnostics after deferred messages and before any terminal failure explanation.
It is independent of the main result's `--format`; quiet suppresses it.
Help, including ckconfig's bare `config explain` fallback, does not start reporting.
Returned execution failures and cancellation retain observed usage.
The summary shows observed prompt executions, nonzero repair-call details, token
categories including reasoning and cache activity, available cache-hit ratio,
and USD cost with its native source. Unknown, incomplete, known-zero, and
terminal-coverage states remain distinct. Empty groups use standard zero totals.
PromptKit owns accounting; CommandKit adds no pricing estimates or cost defaults.
## Existing reports and upstream adoption
Smoke attempt and aggregate usage now retain `reasoning_tokens` and nullable
`cache_hit_ratio`. JSON/YAML ratios are numeric fractions; text adds percentages
with one decimal place. Smoke reports default to the text template, which retains
YAML evidence and adds percentage comments. Use `--format yaml` or `--format json`
for structured output. Smoke usage remains in its own report and is separate from
ordinary execution observation; its report has no added cost field.
Backend inspection forwards native provider and explicit zero-cost declarations,
including false. Review application-defined OpenRouter backends: select
`provider: openrouter` explicitly for its usage, cost, and authentication
conventions. Names and endpoint hostnames do not choose provider behavior.
PromptKit also supplies vLLM conventions and authentication findings, reasoning
usage, and optional `zero_cost` fallback. See the [upstream release notes](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/releases/v0.25.0.md)
and [backend format](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/formats.md#backend-definitions).
## Compatibility and upgrade
This release selects core v0.8.0 and ckconfig v0.11.0. ConfigKit remains
v1.4.0 and the Go consumer minimum remains 1.27.0. Existing integration factory
signatures remain unchanged. Resolve application flag or alias collisions with
`--show-tokens` before installing a nonempty family. Review positional upstream
struct literals and strict report decoders for added reasoning/cost fields, and
scripts relying on the prior default smoke representation.
The maintained [composed consumer](../../examples/composed) demonstrates automatic
reporting for a two-prompt application pipeline.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.12.0/integrations/ckprompt/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.12.0/integrations/ckprompt/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.12.0/integrations/ckprompt/docs/oss/attribution.md)

View File

@@ -1,34 +0,0 @@
# 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)

View File

@@ -0,0 +1,52 @@
# CommandKit ckprompt v0.5.0
CommandKit ckprompt v0.5.0 adds PromptKit v0.20.0 support, including request
preview, namespace selection, and shared text, YAML, and JSON output. It requires
CommandKit core v0.5.0, ckconfig v0.5.0, ConfigKit v1.1.0, and Go 1.27.0.
## Operator features
- Inspect prompts, profiles, and backends, and list available resources.
- Preview rendered requests without calling the model, or validate that a
request can be prepared with the supplied inputs.
- Choose namespaces and override request settings for supported commands.
- Run smoke tests and inspect their results, including incomplete or unsupported
checks and reports returned alongside errors.
- Inspect engine configuration through `config`, including detailed validation
findings, source information after failed loads, and configuration comparisons.
Applications choose which commands to enable. Reusable flag collections also
let application commands offer the same request flags. `ckprompt.Declarations`
adds the standard commands with their shorter flag aliases. Literal and file
inputs keep their command-line order.
## Correctness improvements
Aggregate smoke testing retains cancellation when it stops remaining tests,
including previously returned errors and reports. A prepared-request preview
fails if the provider returns no prepared request without an error. Parsed
provider-parameter objects are copied between independent request destinations,
so mutations in one callback do not change later requests. Configuration
inspection shares ckconfig's native diagnostic adapter.
## Compatibility and upgrade
This pre-1.0 minor release changes resource report shapes, input flags,
formatting, and configuration comparison behavior. Review the current
[CLI reference](../../../../docs/cli.md#promptkit-definition-inspection) and
[consumer guide](../../../../docs/consumers/guide.md#promptkit-configuration-definitions-and-requirements)
when updating declarations or code that reads reports. Applications continue to
own engine construction, credentials, and execution.
Upgrade all three CommandKit modules to v0.5.0 together. This release follows
published ckprompt v0.2.0 and adopts the vanity imports
`go.maximumdirect.net/configkit` and `go.maximumdirect.net/promptkit`.
Replace earlier upstream import paths consistently; types from different
module identities cannot be mixed. Review callers of the former prompt
version-report API and use native prompt, profile, and backend inspections.
The [module selection table](../../../../docs/consumers/guide.md#module-selection)
records the release dependencies.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.5.0/integrations/ckprompt/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.5.0/integrations/ckprompt/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.5.0/integrations/ckprompt/docs/oss/attribution.md)

View File

@@ -0,0 +1,16 @@
# CommandKit ckprompt v0.6.0
CommandKit ckprompt v0.6.0 selects CommandKit core and ckconfig v0.6.0.
Core adds shared debug input bindings and access to the selected reporting mode.
ConfigKit remains at v1.1.0 and PromptKit at v0.20.0.
## Compatibility and upgrade
Select `go.maximumdirect.net/ckprompt v0.6.0` with CommandKit core and ckconfig
v0.6.0. The consumer minimum remains Go 1.27.0. See the
[consumer guide](../../../../docs/consumers/guide.md#invocation-reporting)
for the new core reporting and debug input APIs.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.6.0/integrations/ckprompt/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.6.0/integrations/ckprompt/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.6.0/integrations/ckprompt/docs/oss/attribution.md)

View File

@@ -0,0 +1,21 @@
# CommandKit ckprompt v0.7.0
CommandKit ckprompt v0.7.0 adopts PromptKit v0.21.0 and ConfigKit v1.2.0.
Application-owned engine loaders can select main-relative companion imports
through PromptKit's existing configuration-source API. ckprompt exposes the
resulting engine through its inspection, request, and smoke-testing adapters.
[PromptKit v0.21.0 release notes](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.21.0/docs/releases/v0.21.0.md)
## Compatibility and upgrade
Pair `go.maximumdirect.net/ckprompt v0.7.0` with ckconfig v0.7.0 and CommandKit
core v0.6.0. The consumer minimum is Go 1.27.0.
Application loaders constructing ConfigKit `Input` or `LayeredOptions` must use
field-named struct literals to accommodate the fields added upstream. See the
[consumer guide](../../../../docs/consumers/guide.md#module-selection) for module
selection and loader guidance.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.7.0/integrations/ckprompt/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.7.0/integrations/ckprompt/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.7.0/integrations/ckprompt/docs/oss/attribution.md)

View File

@@ -0,0 +1,25 @@
# CommandKit ckprompt v0.8.0
CommandKit ckprompt v0.8.0 adopts ckconfig v0.8.0's shared configuration-error
classification across inspection, catalogs, requirements, request preparation,
and smoke testing. ConfigKit loading errors returned by application request
builders now provide their source context, warnings, and terminal diagnostics
through the same adaptation used for engine-loader failures.
## Compatibility and upgrade
Pair `go.maximumdirect.net/ckprompt v0.8.0` with ckconfig v0.8.0 and CommandKit
core v0.6.0. The selected upstream versions are ConfigKit v1.2.0 and PromptKit
v0.21.0. The consumer minimum is Go 1.27.0.
Identifiable invalid configuration input now selects status `2`, including
configuration errors returned by request builders. These failures previously
selected status `1`. Update scripts that interpret those statuses. Operational
failures, cancellation, and ambiguous or unknown failure evidence select status
`1`. In aggregate smoke testing, operational failures take precedence over input
failures. Typed causes and available reports are preserved through the shared
reporting lifecycle. See the [CLI contract](../../../../docs/cli.md#configuration-failure-classification).
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.8.0/integrations/ckprompt/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.8.0/integrations/ckprompt/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.8.0/integrations/ckprompt/docs/oss/attribution.md)

View File

@@ -0,0 +1,32 @@
# CommandKit ckprompt v0.9.0
This candidate upgrades PromptKit from v0.21.0 to v0.23.1. PromptKit's
constructor now preserves configuration causes without treating its category
sentinel as a separate failure.
## Compatibility and upgrade
Malformed PromptKit companion YAML returned by engine construction now selects
status `2` instead of `1`. Update scripts that interpret this status. Available
source and validation reports, diagnostics, typed ConfigKit causes, and
`promptkit.ErrInvalidConfig` recognition are retained. Operational failures and
cancellation continue to select status `1`. See the [configuration failure
contract](../../../../docs/cli.md#configuration-failure-classification).
Pair ckprompt v0.9.0 with ckconfig v0.8.0 and CommandKit core v0.6.0. The
selected upstream versions are ConfigKit v1.2.0 and PromptKit v0.23.1; the Go
consumer minimum remains 1.27.0. Native request builders continue to pass the
whole PromptKit request, including additive fields, and prepared reports carry
upstream fields such as parent run identifiers. Applications own construction
of engines and requests. See the [consumer guide](../../../../docs/consumers/guide.md#promptkit-configuration-definitions-and-requirements)
and [upstream upgrade guidance](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/74066167942fcf6f70c112359995739ec9789fa6/docs/releases/v0.23.1.md#compatibility-and-upgrade).
PromptKit v0.22.0 and v0.23.0 added fields to exported request, prepared,
result, and observation structs. If your application constructs affected types
with positional literals, migrate those literals to keyed fields when upgrading
from v0.21.0. See [PromptKit v0.22.0 compatibility](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/74066167942fcf6f70c112359995739ec9789fa6/docs/releases/v0.22.0.md#efficiency-and-compatibility)
and [PromptKit v0.23.0 upgrade guidance](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/74066167942fcf6f70c112359995739ec9789fa6/docs/releases/v0.23.0.md#compatibility-and-upgrade).
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.9.0/integrations/ckprompt/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.9.0/integrations/ckprompt/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.9.0/integrations/ckprompt/docs/oss/attribution.md)

Some files were not shown because too many files have changed in this diff Show More