Compare commits
50 Commits
integratio
...
integratio
| Author | SHA1 | Date | |
|---|---|---|---|
| cd5cf483a4 | |||
| 0b53a63648 | |||
| ef92089125 | |||
| 33f98db4f7 | |||
| 3e4309f084 | |||
| 3415d9337d | |||
| 98e3958dfb | |||
| 362afc79b6 | |||
| 611e66322d | |||
| 367d05b7d9 | |||
| 70cd68f960 | |||
| b7467c59fa | |||
| a0cdd3d7c5 | |||
| a0608a53ee | |||
| 07cc832f4a | |||
| 0d5e13c7a9 | |||
| ba6c9035b1 | |||
| d039efb11d | |||
| b6cb183a71 | |||
| ea3ce25001 | |||
| 68515668de | |||
| f0b4108151 | |||
| e2ffe82324 | |||
| d9df7e2d6b | |||
| 78e9c75dfe | |||
| d8f2f67671 | |||
| b1193564e9 | |||
| fe4e8d756d | |||
| dc0ab74135 | |||
| 91ef377bcd | |||
| 55e0f8c8b0 | |||
| a4aa76de33 | |||
| 1138960e96 | |||
| 54e951e38a | |||
| eedbd83e7e | |||
| 75949de63c | |||
| b874b1f076 | |||
| e70a0ef301 | |||
| 2a086b6389 | |||
| 6a090ba571 | |||
| ca6cf086f2 | |||
| 41bd3a69d4 | |||
| 0c9e719312 | |||
| 8e51ecf77e | |||
| 946181a13e | |||
| 320526d3fc | |||
| 1546122b0b | |||
| 71ba758a09 | |||
| b1c7962f51 | |||
| d330d7637f |
5
app.go
5
app.go
@@ -16,17 +16,22 @@ type App struct {
|
|||||||
aliases *alias.Resolver
|
aliases *alias.Resolver
|
||||||
flagAliases map[string]resolvedFlagAliases
|
flagAliases map[string]resolvedFlagAliases
|
||||||
discoveryFlags map[string]resolvedFlagAliases
|
discoveryFlags map[string]resolvedFlagAliases
|
||||||
|
features []*invocationFeatureRecord
|
||||||
|
featureFlags []commandmeta.Flag
|
||||||
snapshot *routingSnapshot
|
snapshot *routingSnapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
type routingSnapshot struct {
|
type routingSnapshot struct {
|
||||||
metadata *commandmeta.Command
|
metadata *commandmeta.Command
|
||||||
runners map[commandmeta.Key]commandPayload
|
runners map[commandmeta.Key]commandPayload
|
||||||
|
builtins map[commandmeta.Key]bool
|
||||||
aliases *alias.Resolver
|
aliases *alias.Resolver
|
||||||
canonical map[string]*canonicalNode
|
canonical map[string]*canonicalNode
|
||||||
commandAliases []commandmeta.CommandAlias
|
commandAliases []commandmeta.CommandAlias
|
||||||
flagAliases map[string]resolvedFlagAliases
|
flagAliases map[string]resolvedFlagAliases
|
||||||
discoveryFlags map[string]resolvedFlagAliases
|
discoveryFlags map[string]resolvedFlagAliases
|
||||||
|
features []*invocationFeatureRecord
|
||||||
|
featureFlags []commandmeta.Flag
|
||||||
completion bool
|
completion bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -58,6 +58,8 @@ func (a *App) builtinCommands() []Declaration {
|
|||||||
return renderVersionOutcome(identity, invocation.Reporter())
|
return renderVersionOutcome(identity, invocation.Reporter())
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
help.record.builtin = true
|
||||||
|
version.record.builtin = true
|
||||||
return []Declaration{help, version}
|
return []Declaration{help, version}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
25
command.go
25
command.go
@@ -17,6 +17,10 @@ import (
|
|||||||
// before changing an App registry.
|
// before changing an App registry.
|
||||||
type Command struct{ record *commandRecord }
|
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
|
// Declaration is a captured canonical command or application routing rule
|
||||||
// accepted by New and App.Register. Use []Declaration when collecting both
|
// accepted by New and App.Register. Use []Declaration when collecting both
|
||||||
// kinds. Group and RootGroup children remain Commands; install routing rules
|
// kinds. Group and RootGroup children remain Commands; install routing rules
|
||||||
@@ -71,10 +75,12 @@ type commandRecord struct {
|
|||||||
summary string
|
summary string
|
||||||
description string
|
description string
|
||||||
children []Command
|
children []Command
|
||||||
|
features []InvocationFeature
|
||||||
payload commandPayload
|
payload commandPayload
|
||||||
issues []error
|
issues []error
|
||||||
rootOnly bool
|
rootOnly bool
|
||||||
completion bool
|
completion bool
|
||||||
|
builtin bool
|
||||||
absent bool
|
absent bool
|
||||||
invalid bool
|
invalid bool
|
||||||
}
|
}
|
||||||
@@ -187,7 +193,8 @@ type CommandSpec[I any] struct {
|
|||||||
Flags []Flag[I]
|
Flags []Flag[I]
|
||||||
// Arguments declares the command's positional inputs.
|
// Arguments declares the command's positional inputs.
|
||||||
Arguments []Argument[I]
|
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
|
CheckInput func(I) error
|
||||||
// Run handles an invocation. It may be nil for a command used as a group.
|
// Run handles an invocation. It may be nil for a command used as a group.
|
||||||
Run func(Invocation, I) Outcome
|
Run func(Invocation, I) Outcome
|
||||||
@@ -256,9 +263,16 @@ func (c typedCommand[I]) prepare(flagValues, flagSpellings [][]string, occurrenc
|
|||||||
input := prepared.build()
|
input := prepared.build()
|
||||||
if c.spec.CheckInput != nil {
|
if c.spec.CheckInput != nil {
|
||||||
if err := c.spec.CheckInput(input); err != nil {
|
if err := c.spec.CheckInput(input); err != nil {
|
||||||
|
if errors.Is(err, ErrHelpRequested) {
|
||||||
|
return current.renderHelp(current.route.canonicalPath)
|
||||||
|
}
|
||||||
return classifyInputError(err)
|
return classifyInputError(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if current.featureEnabled && current.featureRequiredError != nil {
|
||||||
|
return classifyInputError(current.featureRequiredError)
|
||||||
|
}
|
||||||
|
current.startFeatures()
|
||||||
if c.privateRun != nil {
|
if c.privateRun != nil {
|
||||||
return c.privateRun(current.commandContext(), input)
|
return c.privateRun(current.commandContext(), input)
|
||||||
}
|
}
|
||||||
@@ -467,6 +481,15 @@ func validateCommandPlacement(command Command) error {
|
|||||||
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 {
|
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))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 := RootGroup("completion", "Generate shell completion scripts.", children...)
|
||||||
command.record.completion = true
|
command.record.completion = true
|
||||||
|
command.record.builtin = true
|
||||||
if !validCompletionExecutable(executable) {
|
if !validCompletionExecutable(executable) {
|
||||||
return WithError(command, fmt.Errorf("unsupported completion executable basename %q", executable))
|
return WithError(command, fmt.Errorf("unsupported completion executable basename %q", executable))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ func resolveCompletionContext(snapshot *routingSnapshot, completed []string, cur
|
|||||||
context.aliases = snapshot.flagAliases[context.route.canonicalPath.Key()].lookupRecords()
|
context.aliases = snapshot.flagAliases[context.route.canonicalPath.Key()].lookupRecords()
|
||||||
context.commandPosition = len(context.tail) == 0
|
context.commandPosition = len(context.tail) == 0
|
||||||
case routeDiscovery:
|
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.tail = append([]string(nil), context.route.args...)
|
||||||
context.aliases = snapshot.discoveryFlags[context.route.discoveryPath.Key()].lookupRecords()
|
context.aliases = snapshot.discoveryFlags[context.route.discoveryPath.Key()].lookupRecords()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ type completionFlagState struct {
|
|||||||
func completionFlags(context completionContext) []commandmeta.Flag {
|
func completionFlags(context completionContext) []commandmeta.Flag {
|
||||||
flags := make([]commandmeta.Flag, 0, len(context.command.Flags)+len(context.command.CoreFlags)+1)
|
flags := make([]commandmeta.Flag, 0, len(context.command.Flags)+len(context.command.CoreFlags)+1)
|
||||||
flags = append(flags, commandmeta.HelpFlag())
|
flags = append(flags, commandmeta.HelpFlag())
|
||||||
flags = append(flags, commandmeta.EffectiveFlags(context.command.Flags, context.command.CoreFlags)...)
|
flags = append(flags, commandmeta.EffectiveFlags(append(append([]commandmeta.Flag(nil), context.command.Flags...), context.command.InvocationFlags...), context.command.CoreFlags)...)
|
||||||
return flags
|
return flags
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
2
doc.go
2
doc.go
@@ -5,6 +5,8 @@
|
|||||||
//
|
//
|
||||||
// App.Execute runs a command and returns an Outcome; the application decides
|
// App.Execute runs a command and returns an Outcome; the application decides
|
||||||
// when to exit. Handlers use Invocation.Reporter for output and messages.
|
// 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;
|
// Optional ckconfig and ckprompt modules add inspection and testing commands;
|
||||||
// applications install those commands explicitly.
|
// applications install those commands explicitly.
|
||||||
package commandkit
|
package commandkit
|
||||||
|
|||||||
64
docs/cli.md
64
docs/cli.md
@@ -477,8 +477,8 @@ records preserve their returned order. No records are
|
|||||||
output begins with the scope heading and prints the same source fields,
|
output begins with the scope heading and prints the same source fields,
|
||||||
quoting labels and paths. These fields come from ConfigKit's source records;
|
quoting labels and paths. These fields come from ConfigKit's source records;
|
||||||
producing the report does not reload files or rerun version checks. See the
|
producing the report does not reload files or rerun version checks. See the
|
||||||
[ConfigKit v1.2.1 source
|
[ConfigKit v1.4.0 source
|
||||||
records](https://forge.maximumdirect.net/base-layer/configkit/src/commit/51ef3144158db1a09fabdbd1c7ae59908c84923b/records.go)
|
records](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3/records.go)
|
||||||
for native evidence definitions.
|
for native evidence definitions.
|
||||||
|
|
||||||
### Explain a configuration path
|
### Explain a configuration path
|
||||||
@@ -502,7 +502,12 @@ occurred in history; `--under POINTER` selects a subtree, and `--explicit=true`
|
|||||||
or `--explicit=false` filters current paths by native explicitness. Historical-only
|
or `--explicit=false` filters current paths by native explicitness. Historical-only
|
||||||
paths do not match an explicitness filter. These options require `--list`.
|
paths do not match an explicitness filter. These options require `--list`.
|
||||||
The report contains the scope and each selected path's current presence and,
|
The report contains the scope and each selected path's current presence and,
|
||||||
when present, its explicitness. Path discovery does not include values or history.
|
when present, its explicitness. Path discovery does not include values or
|
||||||
|
history. Focused scopes list their native candidates, such as paths beneath
|
||||||
|
`/promptkit`; explicit `--path`
|
||||||
|
queries use native whole-load paths, including outside the focus where supported.
|
||||||
|
A scope is not an access-control boundary. Sources and diagnostics retain the
|
||||||
|
whole load's evidence.
|
||||||
|
|
||||||
Pointer tokens use JSON Pointer escaping: `~1` represents `/` and `~0`
|
Pointer tokens use JSON Pointer escaping: `~1` represents `/` and `~0`
|
||||||
represents `~`. A malformed pointer is a usage error with status `2` and is
|
represents `~`. A malformed pointer is a usage error with status `2` and is
|
||||||
@@ -599,7 +604,10 @@ concise report contains `additions`, `changes`, and `deletions`. Additions and
|
|||||||
changes keep the configuration's path structure and show right-side values
|
changes keep the configuration's path structure and show right-side values
|
||||||
from the comparison. Deletions are JSON Pointer paths. Explicit null is a
|
from the comparison. Deletions are JSON Pointer paths. Explicit null is a
|
||||||
value, not a deletion. Changed lists and regions replaced as a whole are shown
|
value, not a deletion. Changed lists and regions replaced as a whole are shown
|
||||||
as whole values.
|
as whole values. Focused scopes render the selected subtree and compare native
|
||||||
|
views; differences at an atomic ancestor can remain in the result. An absent
|
||||||
|
focused effective value can fail output delivery, while an explicit null remains
|
||||||
|
null.
|
||||||
|
|
||||||
ConfigKit considers sensitivity on both sides. A secret value can change even
|
ConfigKit considers sensitivity on both sides. A secret value can change even
|
||||||
when both redacted snapshots look the same. For those ConfigKit-backed
|
when both redacted snapshots look the same. For those ConfigKit-backed
|
||||||
@@ -666,7 +674,7 @@ request overrides. Backend reports describe configured backend fields. An
|
|||||||
`api_key_env` value names an environment variable; it is not a credential
|
`api_key_env` value names an environment variable; it is not a credential
|
||||||
value or a claim that one is available. Neither report resolves references or
|
value or a claim that one is available. Neither report resolves references or
|
||||||
performs a network probe. See the [PromptKit resource inspection
|
performs a network probe. See the [PromptKit resource inspection
|
||||||
contracts](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/resource_inspection.go).
|
contracts](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/resource_inspection.go).
|
||||||
Omitting the ID is a usage error. Configuration loading follows the
|
Omitting the ID is a usage error. Configuration loading follows the
|
||||||
[configuration failure classification](#configuration-failure-classification);
|
[configuration failure classification](#configuration-failure-classification);
|
||||||
lookup failures and cancellation are operational.
|
lookup failures and cancellation are operational.
|
||||||
@@ -722,7 +730,7 @@ text output use YAML. Preparation can read resources and include rendered
|
|||||||
application content in the report. It does not guarantee that a later model
|
application content in the report. It does not guarantee that a later model
|
||||||
call will succeed. Application loaders and callbacks may have their own
|
call will succeed. Application loaders and callbacks may have their own
|
||||||
effects. The [PromptKit Prepare
|
effects. The [PromptKit Prepare
|
||||||
API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/engine.go)
|
API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/engine.go)
|
||||||
owns the prepared value and upstream preparation behavior. Configuration failures
|
owns the prepared value and upstream preparation behavior. Configuration failures
|
||||||
follow the [configuration failure classification](#configuration-failure-classification);
|
follow the [configuration failure classification](#configuration-failure-classification);
|
||||||
other preparation failures are operational.
|
other preparation failures are operational.
|
||||||
@@ -758,8 +766,8 @@ identity rather than changing the discovered requirements. An enabled profile
|
|||||||
namespace qualifies an explicitly supplied short profile ID; it does not
|
namespace qualifies an explicitly supplied short profile ID; it does not
|
||||||
rewrite the prompt's stored default reference. Requirements inspection does
|
rewrite the prompt's stored default reference. Requirements inspection does
|
||||||
not require the selected profile to be execution-ready. See the [PromptKit
|
not require the selected profile to be execution-ready. See the [PromptKit
|
||||||
v0.23.2 consumer
|
v0.25.0 consumer
|
||||||
guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/docs/consumers/pkg-promptkit.md)
|
guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/docs/consumers/pkg-promptkit.md)
|
||||||
for configuration, selection, and requirements behavior. For built-in flags
|
for configuration, selection, and requirements behavior. For built-in flags
|
||||||
other than `--llm-var`, repeating a flag uses its last value.
|
other than `--llm-var`, repeating a flag uses its last value.
|
||||||
Application-defined flags follow their own repetition rules.
|
Application-defined flags follow their own repetition rules.
|
||||||
@@ -870,7 +878,7 @@ applicable. It does not make a model call or retain a prepared execution
|
|||||||
snapshot. A successful report describes this preparation invocation; it does
|
snapshot. A successful report describes this preparation invocation; it does
|
||||||
not certify provider acceptance or guarantee later execution. See PromptKit's
|
not certify provider acceptance or guarantee later execution. See PromptKit's
|
||||||
[`Engine.ValidateRequest`
|
[`Engine.ValidateRequest`
|
||||||
API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/engine.go).
|
API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/engine.go).
|
||||||
|
|
||||||
Configuration errors returned by request construction or engine loading follow
|
Configuration errors returned by request construction or engine loading follow
|
||||||
the [configuration failure classification](#configuration-failure-classification).
|
the [configuration failure classification](#configuration-failure-classification).
|
||||||
@@ -936,11 +944,29 @@ The entries are:
|
|||||||
A catalog result is an inventory, not a readiness check or execution result.
|
A catalog result is an inventory, not a readiness check or execution result.
|
||||||
The owning provider controls membership and order. Namespace filters are
|
The owning provider controls membership and order. Namespace filters are
|
||||||
passed to PromptKit without local membership interpretation. See the
|
passed to PromptKit without local membership interpretation. See the
|
||||||
[PromptKit v0.23.2 consumer
|
[PromptKit v0.25.0 consumer
|
||||||
guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/docs/consumers/pkg-promptkit.md)
|
guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/docs/consumers/pkg-promptkit.md)
|
||||||
for resource and selection definitions. Catalog loading failures follow the
|
for resource and selection definitions. Catalog loading failures follow the
|
||||||
[configuration failure classification](#configuration-failure-classification).
|
[configuration failure classification](#configuration-failure-classification).
|
||||||
|
|
||||||
|
## PromptKit usage reporting
|
||||||
|
|
||||||
|
A nonempty PromptKit integration makes `--show-tokens` available after the full
|
||||||
|
command path, including application commands. It defaults to false; repeat it
|
||||||
|
or use `--show-tokens=false` to select the final Boolean value. When requested,
|
||||||
|
the diagnostic stream receives observed PromptKit execution totals after deferred
|
||||||
|
messages and before any terminal explanation. The summary is visible in ordinary,
|
||||||
|
verbose, and debug modes; quiet suppresses it. Main output and its `--format` are
|
||||||
|
independent. Help, version, completion, routing/parsing failures and rejected
|
||||||
|
command input produce no summary.
|
||||||
|
|
||||||
|
The report distinguishes unknown and incomplete token counts, cost and terminal
|
||||||
|
coverage. Cache hit ratio is shown when available; known costs include native
|
||||||
|
source information when present. Empty groups report native zero totals, not
|
||||||
|
measurements of smoke tests. Smoke-test usage appears separately in its command
|
||||||
|
report. Smoke reports default to text; `--format yaml` or `--format json` selects
|
||||||
|
structured output.
|
||||||
|
|
||||||
## PromptKit smoke testing
|
## PromptKit smoke testing
|
||||||
|
|
||||||
`promptkit test KIND` runs a PromptKit smoke test using the application's
|
`promptkit test KIND` runs a PromptKit smoke test using the application's
|
||||||
@@ -1001,7 +1027,7 @@ conflicting namespace flags use status `2`.
|
|||||||
| `--llm-api-key-env` | string | omitted | Name the environment variable containing the API key. |
|
| `--llm-api-key-env` | string | omitted | Name the environment variable containing the API key. |
|
||||||
| `--llm-transient-retries` | integer | omitted | Set the retry count for transient inference failures. |
|
| `--llm-transient-retries` | integer | omitted | Set the retry count for transient inference failures. |
|
||||||
| `--llm-extra-params` | JSON object | omitted | Supply provider parameters as a whole map. |
|
| `--llm-extra-params` | JSON object | omitted | Supply provider parameters as a whole map. |
|
||||||
| `--format` | `text`, `yaml`, `json` | automatic | Select the report format; automatic and text use YAML for these structured reports. |
|
| `--format` | `text`, `yaml`, `json` | automatic | Select the report format; automatic/text use the smoke text template (YAML evidence with percentage comments). YAML/JSON select structured output. |
|
||||||
|
|
||||||
These execution flags override settings for the selected operation. The
|
These execution flags override settings for the selected operation. The
|
||||||
`--llm-api-key-env` value is a variable name, not a credential value. The
|
`--llm-api-key-env` value is a variable name, not a credential value. The
|
||||||
@@ -1023,7 +1049,11 @@ The report includes `kind`, `supported`, `applicable`, `completed`, `reason`,
|
|||||||
contains selected IDs, selection source, endpoint, effective settings, and
|
contains selected IDs, selection source, endpoint, effective settings, and
|
||||||
settings-presence flags. Attempt entries retain their own facts, timing,
|
settings-presence flags. Attempt entries retain their own facts, timing,
|
||||||
failure, and token-usage evidence. Durations use Go duration strings; token
|
failure, and token-usage evidence. Durations use Go duration strings; token
|
||||||
counts preserve `value`, `known`, and `complete`.
|
counts preserve `value`, `known`, and `complete`. Both attempt and aggregate
|
||||||
|
usage include `reasoning_tokens` with that count state and `cache_hit_ratio`.
|
||||||
|
The structured ratio is a nullable numeric fraction: `0.2` means 20%, `0` is a
|
||||||
|
known zero ratio, and null means unavailable. Text adds available ratios as
|
||||||
|
percentages with one decimal place. PromptKit owns the ratio and token meanings.
|
||||||
|
|
||||||
For example, this report says the configured HTTP diagnostic is unavailable:
|
For example, this report says the configured HTTP diagnostic is unavailable:
|
||||||
|
|
||||||
@@ -1080,6 +1110,8 @@ attempts: []
|
|||||||
usage:
|
usage:
|
||||||
prompt_tokens: {value: 0, known: true, complete: true}
|
prompt_tokens: {value: 0, known: true, complete: true}
|
||||||
completion_tokens: {value: 0, known: true, complete: true}
|
completion_tokens: {value: 0, known: true, complete: true}
|
||||||
|
reasoning_tokens: {value: 0, known: true, complete: true}
|
||||||
|
cache_hit_ratio: null
|
||||||
total_tokens: {value: 0, known: true, complete: true}
|
total_tokens: {value: 0, known: true, complete: true}
|
||||||
cached_tokens: {value: 0, known: true, complete: true}
|
cached_tokens: {value: 0, known: true, complete: true}
|
||||||
cache_write_tokens: {value: 0, known: true, complete: true}
|
cache_write_tokens: {value: 0, known: true, complete: true}
|
||||||
@@ -1108,9 +1140,9 @@ separately from delivery failures through the [reporting
|
|||||||
API](consumers/guide.md#invocation-reporting).
|
API](consumers/guide.md#invocation-reporting).
|
||||||
|
|
||||||
Native configuration, selection, and diagnostic meanings remain owned by
|
Native configuration, selection, and diagnostic meanings remain owned by
|
||||||
PromptKit. See the [v0.23.2 consumer guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/docs/consumers/pkg-promptkit.md),
|
PromptKit. See the [v0.25.0 consumer guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/docs/consumers/pkg-promptkit.md),
|
||||||
[smoke API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/smoke_diagnostics.go),
|
[smoke API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/smoke_diagnostics.go),
|
||||||
and [engine API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/engine.go).
|
and [engine API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/engine.go).
|
||||||
|
|
||||||
## Outcome status
|
## Outcome status
|
||||||
|
|
||||||
|
|||||||
@@ -14,14 +14,14 @@ applications.
|
|||||||
| `go.maximumdirect.net/ckconfig` | You want operators to view, validate, explain, and compare ConfigKit configuration. |
|
| `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. |
|
| `go.maximumdirect.net/ckprompt` | You want operators to inspect PromptKit resources, check and preview requests, or run smoke tests. |
|
||||||
|
|
||||||
ckconfig v0.9.0 and ckprompt v0.10.0 select ConfigKit v1.2.1.
|
ckconfig v0.10.0 and ckprompt v0.11.0 select ConfigKit v1.4.0.
|
||||||
ckprompt v0.10.0 selects PromptKit v0.23.2.
|
ckprompt v0.11.0 selects PromptKit v0.24.0.
|
||||||
|
|
||||||
| Selection | Core | ckconfig | ckprompt | Upstream libraries and status |
|
| Selection | Core | ckconfig | ckprompt | Upstream libraries and status |
|
||||||
| --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
| Published core | v0.7.0 | — | — | Usable independently. |
|
| Published core | v0.8.0 | — | — | Usable independently. |
|
||||||
| ConfigKit integration | v0.7.0 | v0.9.0 | — | ConfigKit v1.2.1. |
|
| ConfigKit integration | v0.7.0 | v0.10.0 | — | ConfigKit v1.4.0. |
|
||||||
| PromptKit integration | v0.7.0 | v0.9.0 | v0.10.0 | ConfigKit v1.2.1 and PromptKit v0.23.2. |
|
| 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. |
|
| 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. |
|
||||||
|
|
||||||
For applications moving from ckprompt v0.8.0, the
|
For applications moving from ckprompt v0.8.0, the
|
||||||
@@ -31,15 +31,13 @@ cover migration of positional literals for affected native PromptKit structs.
|
|||||||
Install the published core with:
|
Install the published core with:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
go get go.maximumdirect.net/commandkit@v0.7.0
|
go get go.maximumdirect.net/commandkit@v0.8.0
|
||||||
```
|
```
|
||||||
|
|
||||||
Select either integration with `go get go.maximumdirect.net/ckconfig@v0.9.0`
|
Select either integration with `go get go.maximumdirect.net/ckconfig@v0.10.0`
|
||||||
or `go get go.maximumdirect.net/ckprompt@v0.10.0`. Both integrations select
|
or `go get go.maximumdirect.net/ckprompt@v0.11.0`. Both integrations select
|
||||||
core v0.7.0. ckprompt v0.10.0 selects ckconfig v0.9.0, which includes
|
core v0.7.0. ckprompt v0.11.0 selects ckconfig v0.10.0, including native subtree
|
||||||
`AdaptDiagnostics` and `ClassifyConfigurationError`. Both integrations build
|
scopes and path readers. These releases build independently.
|
||||||
independently against their released dependencies. An aligned workspace can
|
|
||||||
exercise the local sources together during development.
|
|
||||||
Published ckconfig v0.3.0 also uses ConfigKit v1.1.0 and does not compose with
|
Published ckconfig v0.3.0 also uses ConfigKit v1.1.0 and does not compose with
|
||||||
ckprompt v0.2.0's earlier ConfigKit dependency.
|
ckprompt v0.2.0's earlier ConfigKit dependency.
|
||||||
|
|
||||||
@@ -48,10 +46,15 @@ loaders should use keyed struct literals when constructing them. ConfigKit's
|
|||||||
release notes describe
|
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).
|
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 checkout selects PromptKit v0.23.2, which exposes main-relative
|
The current ckconfig checkout selects published core v0.8.0. The unreleased
|
||||||
companion imports through its existing configuration-source API. Applications
|
ckprompt checkout selects PromptKit v0.25.0 and requires local core and ckconfig
|
||||||
select those inputs when constructing
|
through the aligned workspace until its dependency requirements are updated.
|
||||||
the engine supplied to ckprompt's loader callback. [PromptKit companion import guidance](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/docs/consumers/pkg-promptkit.md#load-companion-prompts-relative-to-the-main-configuration).
|
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
|
Importing a module does not install its commands. Pass commands to
|
||||||
`commandkit.New` or `App.Register` explicitly. ckprompt depends on ckconfig's
|
`commandkit.New` or `App.Register` explicitly. ckprompt depends on ckconfig's
|
||||||
@@ -309,6 +312,14 @@ separate initialization calls do not guarantee distinct objects. See
|
|||||||
[ckconfig.Suite's GoDoc](../../integrations/ckconfig/contracts.go) for factory
|
[ckconfig.Suite's GoDoc](../../integrations/ckconfig/contracts.go) for factory
|
||||||
timing, omitted-factory zero values (including nil pointers), and ownership.
|
timing, omitted-factory zero values (including nil pointers), and ownership.
|
||||||
The application owns the state type and what it caches.
|
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
|
`ckconfig.FromConfigKit` adapts a typed ConfigKit loader without calling it
|
||||||
during construction. The bundled comparison adapters call the loader for the
|
during construction. The bundled comparison adapters call the loader for the
|
||||||
left side before the right, retain left diagnostics if right loading fails,
|
left side before the right, retain left diagnostics if right loading fails,
|
||||||
@@ -320,8 +331,10 @@ The `config` family provides scope discovery, validation, safe effective configu
|
|||||||
source inventory, path explanation, and ConfigKit-backed comparison for the
|
source inventory, path explanation, and ConfigKit-backed comparison for the
|
||||||
capabilities declared by its scopes. The [CLI reference](../cli.md#configuration-scopes)
|
capabilities declared by its scopes. The [CLI reference](../cli.md#configuration-scopes)
|
||||||
owns operator syntax and report details. `Scope.Features` declares optional modes; acquired
|
owns operator syntax and report details. `Scope.Features` declares optional modes; acquired
|
||||||
`View.Metadata` and `View.Findings` carry native path metadata and diagnostic
|
`View.Paths` supplies native discovery candidates; when nil, `View.Metadata`
|
||||||
records when available. `Findings.Messages` contains presentations associated
|
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.
|
with those records, while `Acquired.Diagnostics` carries independent messages.
|
||||||
Custom explanation providers implement `Explain`; CommandKit renders the
|
Custom explanation providers implement `Explain`; CommandKit renders the
|
||||||
acquired evidence. See `EffectiveWriter` and `ExplanationReader` in the
|
acquired evidence. See `EffectiveWriter` and `ExplanationReader` in the
|
||||||
@@ -343,8 +356,8 @@ 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
|
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 under `config` with validate/show/sources/explain and native diff operations;
|
||||||
it does not install PromptKit catalog, definition, or requirements commands.
|
it does not install PromptKit catalog, definition, or requirements commands.
|
||||||
Its override feature is disabled because the released PromptKit configuration
|
Its override feature is disabled by default. Applications may enable it only
|
||||||
loader does not accept ConfigKit override records.
|
when their own loader applies the supplied overrides.
|
||||||
|
|
||||||
### Install resource commands and optional checks
|
### Install resource commands and optional checks
|
||||||
|
|
||||||
@@ -382,13 +395,37 @@ suite := ckprompt.WithRequestValidation(
|
|||||||
validationCommand := ckprompt.Command(suite)
|
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
|
### Request builders and loading
|
||||||
|
|
||||||
If the loader is nil, the returned suite retains a wiring issue for installation
|
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
|
to report, even if capabilities are narrowed later. A builder runs before the
|
||||||
engine loader and receives the seed request, selection, typed input, shared
|
engine loader and receives the seed request, selection, typed input, shared
|
||||||
state, and invocation context. It returns the
|
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,
|
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
|
preserve operator values and bindings, and apply defaults only when a map key is
|
||||||
absent, so explicitly supplied empty values stay meaningful. Applications that
|
absent, so explicitly supplied empty values stay meaningful. Applications that
|
||||||
@@ -424,7 +461,7 @@ and uses `Engine.ValidateRequest`.
|
|||||||
Applications own engine construction and may build complete native requests in
|
Applications own engine construction and may build complete native requests in
|
||||||
callbacks. Preparation and validation use the supplied context; execution owns
|
callbacks. Preparation and validation use the supplied context; execution owns
|
||||||
prepared notifications and operation timeouts. See the [PromptKit consumer
|
prepared notifications and operation timeouts. See the [PromptKit consumer
|
||||||
guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/docs/consumers/pkg-promptkit.md)
|
guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/docs/consumers/pkg-promptkit.md)
|
||||||
for conversation and execution capabilities.
|
for conversation and execution capabilities.
|
||||||
|
|
||||||
`ckprompt.WithRequestPreparation` adds a separate callback backed by
|
`ckprompt.WithRequestPreparation` adds a separate callback backed by
|
||||||
@@ -463,7 +500,7 @@ complete return value is authoritative. The [CLI reference](../cli.md#promptkit-
|
|||||||
and reports.
|
and reports.
|
||||||
|
|
||||||
The [composed example](../../integrations/ckprompt/examples/composed/README.md)
|
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
|
requirements inspection, request validation, smoke testing, and an
|
||||||
application-owned `session restore` command.
|
application-owned `session restore` command.
|
||||||
|
|
||||||
@@ -487,7 +524,7 @@ These are independent defaults for unqualified caller-supplied prompt, profile,
|
|||||||
and backend names; qualified IDs pass through. Stored references and configuration
|
and backend names; qualified IDs pass through. Stored references and configuration
|
||||||
inspection are unchanged, while namespace and collection inventories remain global.
|
inspection are unchanged, while namespace and collection inventories remain global.
|
||||||
Catalog `--namespace` filters are separate from these defaults. See the released
|
Catalog `--namespace` filters are separate from these defaults. See the released
|
||||||
[namespace API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/namespaces.go).
|
[namespace API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/namespaces.go).
|
||||||
|
|
||||||
## Outcomes and ownership
|
## Outcomes and ownership
|
||||||
|
|
||||||
@@ -501,8 +538,8 @@ signal handling, and exit mapping; `Execute` never exits the process.
|
|||||||
Go declarations and GoDoc own exact exported contracts. ConfigKit owns
|
Go declarations and GoDoc own exact exported contracts. ConfigKit owns
|
||||||
configuration decoding, validation, and provenance. PromptKit owns prompt
|
configuration decoding, validation, and provenance. PromptKit owns prompt
|
||||||
formats, profile resolution, and inspection details. See the
|
formats, profile resolution, and inspection details. See the
|
||||||
[ConfigKit v1.2.1 source records](https://forge.maximumdirect.net/base-layer/configkit/src/commit/51ef3144158db1a09fabdbd1c7ae59908c84923b/records.go),
|
[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/382ccfb14b9630fd8f48c8364dbe2b6159637d71/engine.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/382ccfb14b9630fd8f48c8364dbe2b6159637d71/configuration_inspection.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/382ccfb14b9630fd8f48c8364dbe2b6159637d71/smoke_diagnostics.go),
|
[smoke diagnostics](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/smoke_diagnostics.go),
|
||||||
and [PromptKit v0.23.2 consumer guidance](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/docs/consumers/pkg-promptkit.md).
|
and [PromptKit v0.25.0 consumer guidance](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/docs/consumers/pkg-promptkit.md).
|
||||||
|
|||||||
@@ -118,12 +118,16 @@ go work init . ./integrations/ckconfig ./integrations/ckprompt
|
|||||||
If a workspace already exists, ensure it includes these three modules. Preserve
|
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
|
the ignored `go.work` and `go.work.sum`; do not commit them. Use
|
||||||
`GOWORK=off GOTOOLCHAIN=local` for dependency preparation
|
`GOWORK=off GOTOOLCHAIN=local` for dependency preparation
|
||||||
and independent module suites. Both integrations select released core v0.7.0;
|
and independent module suites. ckconfig selects released core v0.8.0 and builds
|
||||||
ckprompt also selects released ckconfig v0.9.0. Both integrations support
|
independently. ckprompt still selects core v0.7.0 and ckconfig v0.10.0; its
|
||||||
independent builds against their published dependencies. The aligned workspace
|
unreleased sources need the aligned workspace until its dependency requirements
|
||||||
exercises the local sources together.
|
are updated during release preparation. For an isolated ckprompt source check,
|
||||||
Run `GOWORK=off GOTOOLCHAIN=local go test ./...` separately from each module
|
use a temporary modfile replacing core and ckconfig with local sources. Before
|
||||||
directory. From the repository root, a workspace containing all three modules can also run:
|
ckprompt publication, run its independent suite against the newly published
|
||||||
|
dependency versions. 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
|
```sh
|
||||||
GOTOOLCHAIN=local go test ./...
|
GOTOOLCHAIN=local go test ./...
|
||||||
|
|||||||
@@ -44,9 +44,15 @@ application binding's position. The same occurrence stream selects reporting
|
|||||||
mode independently of the prepared application value. The invocation's mode
|
mode independently of the prepared application value. The invocation's mode
|
||||||
accessor reads the reporter's selection under its existing state mutex.
|
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
|
The reporter owns invocation-scoped visibility, message formatting, managed
|
||||||
report rendering, delivery observations, and finalization. It presents queued
|
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
|
closes its handles before `Execute` returns. It records rendering and write
|
||||||
errors separately for result and diagnostic destinations; the returned
|
errors separately for result and diagnostic destinations; the returned
|
||||||
`Outcome.Presentation` exposes those observations independently from the
|
`Outcome.Presentation` exposes those observations independently from the
|
||||||
@@ -91,7 +97,9 @@ Cobra and pflag imports remain inside this package.
|
|||||||
`integrations/ckconfig` owns ConfigKit adaptation, scope capture, the standard
|
`integrations/ckconfig` owns ConfigKit adaptation, scope capture, the standard
|
||||||
`config` command family, and native validate/show/sources/explain/diff behavior.
|
`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
|
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
|
initialized input, while one suite-owned state value is shared by an invocation's
|
||||||
acquisitions or comparison callback.
|
acquisitions or comparison callback.
|
||||||
|
|
||||||
|
|||||||
46
docs/releases/v0.8.0.md
Normal file
46
docs/releases/v0.8.0.md
Normal 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)
|
||||||
@@ -1,11 +1,35 @@
|
|||||||
# Future work
|
# Future work
|
||||||
|
|
||||||
Status — optional shell validation and future capability proposals.
|
Status — pending release coordination, optional verification, and future capability proposals.
|
||||||
No delivery dates are selected here.
|
No delivery dates are selected here.
|
||||||
|
|
||||||
|
## Pending release coordination
|
||||||
|
|
||||||
|
[Core v0.8.0](../releases/v0.8.0.md) is published with a hosted release page.
|
||||||
|
Automatic usage reporting and R1–R4 remediation are implemented.
|
||||||
|
|
||||||
|
[ckconfig v0.11.0](../../integrations/ckconfig/docs/releases/v0.11.0.md) is prepared
|
||||||
|
with released core v0.8.0. Publish it next, then prepare and publish
|
||||||
|
[ckprompt v0.12.0](../../integrations/ckprompt/docs/releases/v0.12.0.md) with both
|
||||||
|
published CommandKit dependencies under the
|
||||||
|
[release procedure](../release.md#scope-and-release-order). ckprompt's note remains
|
||||||
|
a draft and its module requirements still select the earlier published versions.
|
||||||
|
Until alignment, ckprompt needs the aligned workspace or temporary local-source
|
||||||
|
modfiles as described in the developer guide. Each integration publication runs
|
||||||
|
its independent suite against its 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
|
## Purpose and authority
|
||||||
|
|
||||||
Earlier 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
|
This document preserves unfinished work and unselected ideas under the
|
||||||
[release policy](../policy/release.md#release-documentation-and-preparation).
|
[release policy](../policy/release.md#release-documentation-and-preparation).
|
||||||
The completed shared debug binding and reporting-mode implementation is recorded
|
The completed shared debug binding and reporting-mode implementation is recorded
|
||||||
@@ -37,12 +61,11 @@ govern any future implementation. The [CLI reference](../cli.md), public GoDoc,
|
|||||||
and [consumer guide](../consumers/guide.md) own implemented behavior. Retaining
|
and [consumer guide](../consumers/guide.md) own implemented behavior. Retaining
|
||||||
an idea here does not select its syntax, API, priority, or delivery date.
|
an idea here does not select its syntax, API, priority, or delivery date.
|
||||||
|
|
||||||
## Release coordination
|
The completed ConfigKit v1.4.0 and PromptKit v0.24.0 adoption, audit remediation,
|
||||||
|
and coordinated integration releases are preserved in the
|
||||||
Core v0.7.0, ckconfig v0.9.0, and their hosted pages are published.
|
[release snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/54e951e38a404b4338c7967ac39c6c01159bf76d/docs/roadmap).
|
||||||
Publish ckprompt v0.10.0 with both released dependencies, then deliver its
|
ckconfig v0.10.0 and ckprompt v0.11.0 were published with hosted release pages;
|
||||||
hosted page using the [release procedure](../release.md#scope-and-release-order).
|
ckprompt passed its independent suite against released ckconfig v0.10.0.
|
||||||
Remove this item when coordination is complete.
|
|
||||||
|
|
||||||
## Optional verification
|
## Optional verification
|
||||||
|
|
||||||
@@ -127,6 +150,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
|
was also outside that scope. Any later extension needs a deliberate API and
|
||||||
presentation decision rather than assuming those behaviors are already provided.
|
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
|
### Release workflow extensions
|
||||||
|
|
||||||
Historical hosted-page backfilling and automated CI delivery remain separate
|
Historical hosted-page backfilling and automated CI delivery remain separate
|
||||||
|
|||||||
60
docs/roadmap/scriptorium-feature-request.md
Normal file
60
docs/roadmap/scriptorium-feature-request.md
Normal 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.
|
||||||
81
execute.go
81
execute.go
@@ -43,8 +43,13 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco
|
|||||||
var outcome Outcome
|
var outcome Outcome
|
||||||
path := parsed.Path
|
path := parsed.Path
|
||||||
handlerRan := false
|
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 {
|
if parsed.Failure != nil {
|
||||||
outcome = Usage(parsed.Failure.Message)
|
outcome = Usage(parsed.Failure.Message)
|
||||||
|
} else if err := current.prepareFeatures(&parsed, featureRequired); err != nil {
|
||||||
|
outcome = classifyInputError(err)
|
||||||
} else if current.route.kind == routeDiscovery {
|
} else if current.route.kind == routeDiscovery {
|
||||||
if parsed.HelpRequested {
|
if parsed.HelpRequested {
|
||||||
outcome = current.renderHelp(parsed.Path)
|
outcome = current.renderHelp(parsed.Path)
|
||||||
@@ -70,6 +75,7 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco
|
|||||||
outcome = classifyInputError(err)
|
outcome = classifyInputError(err)
|
||||||
} else {
|
} else {
|
||||||
handlerRan = true
|
handlerRan = true
|
||||||
|
current.featureEnabled = !routedSnapshot.builtins[parsed.Key]
|
||||||
outcome = run(current)
|
outcome = run(current)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -77,14 +83,73 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco
|
|||||||
return current.finalize(outcome, path, handlerRan)
|
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 {
|
type execution struct {
|
||||||
app *App
|
app *App
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
reporter *Reporter
|
reporter *Reporter
|
||||||
debugEvents []string
|
featureStarts []func(Invocation) (context.Context, func() Report)
|
||||||
snapshot *routingSnapshot
|
featureRequiredError error
|
||||||
session *internalcobra.Session
|
featureEnabled bool
|
||||||
route routeResult
|
featureReports []func() Report
|
||||||
|
debugEvents []string
|
||||||
|
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 {
|
type commandExecution struct {
|
||||||
@@ -340,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))
|
_ = 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 {
|
func (current *execution) usageText(path []string) string {
|
||||||
|
|||||||
@@ -24,9 +24,10 @@ type flagAliasMapping struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type flagAliasContext struct {
|
type flagAliasContext struct {
|
||||||
path commandpath.Path
|
path commandpath.Path
|
||||||
canonical map[string]capturedFlagSpelling
|
canonical map[string]capturedFlagSpelling
|
||||||
discovery bool
|
invocation map[string]capturedFlagSpelling
|
||||||
|
discovery bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (aliases resolvedFlagAliases) neutralRecords() []commandmeta.FlagAlias {
|
func (aliases resolvedFlagAliases) neutralRecords() []commandmeta.FlagAlias {
|
||||||
@@ -64,10 +65,28 @@ func (spelling capturedFlagSpelling) token() string {
|
|||||||
return "--" + spelling.name
|
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 {
|
func compileFlagAliases(rules []RoutingRule, roots map[string]*canonicalNode, aliases interface {
|
||||||
Resolve(commandpath.Path) commandpath.Path
|
Resolve(commandpath.Path) commandpath.Path
|
||||||
ProperSourcePrefixes() []commandpath.Path
|
ProperSourcePrefixes() []commandpath.Path
|
||||||
}) (map[string]resolvedFlagAliases, map[string]resolvedFlagAliases, error) {
|
}, features []commandmeta.Flag) (map[string]resolvedFlagAliases, map[string]resolvedFlagAliases, error) {
|
||||||
canonicalNodes := indexCanonicalNodes(roots)
|
canonicalNodes := indexCanonicalNodes(roots)
|
||||||
global := make(map[string]flagAliasMapping)
|
global := make(map[string]flagAliasMapping)
|
||||||
scoped := make(map[string]map[string]flagAliasMapping)
|
scoped := make(map[string]map[string]flagAliasMapping)
|
||||||
@@ -97,6 +116,13 @@ func compileFlagAliases(rules []RoutingRule, roots map[string]*canonicalNode, al
|
|||||||
canonicalContexts[key] = flagAliasContext{path: node.path.Clone(), canonical: canonicalFlagSpellings(node.command)}
|
canonicalContexts[key] = flagAliasContext{path: node.path.Clone(), canonical: canonicalFlagSpellings(node.command)}
|
||||||
}
|
}
|
||||||
discoveryContexts := discoverFlagContexts(rules, roots, aliases, canonicalNodes)
|
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)
|
canonicalKeys := sortedContextKeys(canonicalContexts)
|
||||||
resolvedCanonical := make(map[string]resolvedFlagAliases, len(canonicalContexts))
|
resolvedCanonical := make(map[string]resolvedFlagAliases, len(canonicalContexts))
|
||||||
@@ -236,7 +262,7 @@ func resolveFlagAliases(context flagAliasContext, mappings map[string]flagAliasM
|
|||||||
var resolve func(capturedFlagSpelling) (terminal, error)
|
var resolve func(capturedFlagSpelling) (terminal, error)
|
||||||
resolve = func(current capturedFlagSpelling) (terminal, error) {
|
resolve = func(current capturedFlagSpelling) (terminal, error) {
|
||||||
key := flagSpellingKey(current)
|
key := flagSpellingKey(current)
|
||||||
if endpoint, exists := context.canonical[key]; exists {
|
if endpoint, exists := context.canonicalSpelling(key); exists {
|
||||||
return terminal{spelling: endpoint, active: true}, nil
|
return terminal{spelling: endpoint, active: true}, nil
|
||||||
}
|
}
|
||||||
if result, exists := resolved[key]; exists {
|
if result, exists := resolved[key]; exists {
|
||||||
@@ -279,7 +305,7 @@ func resolveFlagAliases(context flagAliasContext, mappings map[string]flagAliasM
|
|||||||
}
|
}
|
||||||
continue
|
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))
|
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: terminal.spelling}
|
result.bySpelling[sourceKey] = resolvedFlagAlias{source: source, target: terminal.spelling}
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ func (a *App) helpView(route routeResult, snapshot *routingSnapshot) commandmeta
|
|||||||
if snapshot == nil {
|
if snapshot == nil {
|
||||||
return view
|
return view
|
||||||
}
|
}
|
||||||
|
view.CoreFlags = append(append([]commandmeta.Flag(nil), snapshot.featureFlags...), view.CoreFlags...)
|
||||||
view.CommandAliases = routeHelpAliases(snapshot, route)
|
view.CommandAliases = routeHelpAliases(snapshot, route)
|
||||||
if view.Discovery {
|
if view.Discovery {
|
||||||
view.FlagAliases = snapshot.discoveryFlags[route.discoveryPath.Key()].neutralRecords()
|
view.FlagAliases = snapshot.discoveryFlags[route.discoveryPath.Key()].neutralRecords()
|
||||||
|
|||||||
@@ -33,64 +33,19 @@ func FromConfigKit[I, S, T any](
|
|||||||
}
|
}
|
||||||
|
|
||||||
scope.Acquire = func(ctx context.Context, request Request, input I, state S) (commandkit.Acquired[View], error) {
|
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)
|
||||||
acquired := commandkit.Acquired[View]{}
|
|
||||||
if err != nil {
|
|
||||||
var loadError *configkit.LoadError
|
|
||||||
if errors.As(err, &loadError) && loadError != nil {
|
|
||||||
records := loadError.Diagnostics()
|
|
||||||
messages, explanation := configKitDiagnostics(name, loadError.Sources(), records)
|
|
||||||
acquired.Value.Sources = loadError
|
|
||||||
acquired.Value.Findings = &Findings{Records: records, Messages: messages}
|
|
||||||
acquired.Explanation = explanation
|
|
||||||
return acquired, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if result == nil {
|
|
||||||
if err != nil {
|
|
||||||
return acquired, err
|
|
||||||
}
|
|
||||||
return commandkit.Acquired[View]{}, fmt.Errorf("ConfigKit scope %q returned a nil result", name)
|
|
||||||
}
|
|
||||||
records := result.Diagnostics()
|
|
||||||
messages, explanation := configKitDiagnostics(name, result.Sources(), records)
|
|
||||||
acquired.Value = View{Sources: result, Findings: &Findings{Records: records, Messages: messages}}
|
|
||||||
acquired.Explanation = explanation
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return acquired, err
|
return acquired, err
|
||||||
}
|
}
|
||||||
metadata := result.Metadata()
|
metadata := result.Metadata()
|
||||||
acquired.Value.Effective, acquired.Value.Explanation, acquired.Value.Metadata = result, result, &metadata
|
acquired.Value.Effective, acquired.Value.Explanation, acquired.Value.Metadata, acquired.Value.Paths = result, result, &metadata, &metadata
|
||||||
return acquired, nil
|
return acquired, nil
|
||||||
}
|
}
|
||||||
scope.Compare = func(ctx context.Context, request ComparisonRequest[I], state S) (commandkit.Acquired[[]configkit.Difference], error) {
|
scope.Compare = func(ctx context.Context, request ComparisonRequest[I], state S) (commandkit.Acquired[[]configkit.Difference], error) {
|
||||||
if err := ctx.Err(); err != nil {
|
left, right, acquired, err := loadComparisonPair(ctx, name, load, request, state)
|
||||||
return commandkit.Acquired[[]configkit.Difference]{}, fmt.Errorf("ConfigKit scope %q comparison before left load: %w", name, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
if err != nil {
|
||||||
return acquired, err
|
return acquired, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return acquired, fmt.Errorf("ConfigKit scope %q comparison after 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)
|
|
||||||
if err != nil {
|
|
||||||
return acquired, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return acquired, fmt.Errorf("ConfigKit scope %q comparison before native diff: %w", name, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
acquired.Value, err = configkit.Diff(left, right)
|
acquired.Value, err = configkit.Diff(left, right)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return acquired, fmt.Errorf("ConfigKit scope %q native diff: %w", name, err)
|
return acquired, fmt.Errorf("ConfigKit scope %q native diff: %w", name, err)
|
||||||
@@ -100,6 +55,130 @@ func FromConfigKit[I, S, T any](
|
|||||||
return scope
|
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
|
||||||
|
if errors.As(err, &loadError) && loadError != nil {
|
||||||
|
records := loadError.Diagnostics()
|
||||||
|
messages, explanation := configKitDiagnostics(name, loadError.Sources(), records)
|
||||||
|
acquired.Value.Sources = loadError
|
||||||
|
acquired.Value.Findings = &Findings{Records: records, Messages: messages}
|
||||||
|
acquired.Explanation = explanation
|
||||||
|
return result, acquired, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if result == nil {
|
||||||
|
if err != nil {
|
||||||
|
return nil, acquired, err
|
||||||
|
}
|
||||||
|
return nil, acquired, fmt.Errorf("ConfigKit scope %q returned a nil result", name)
|
||||||
|
}
|
||||||
|
records := result.Diagnostics()
|
||||||
|
messages, explanation := configKitDiagnostics(name, result.Sources(), records)
|
||||||
|
acquired.Value = View{Sources: result, Findings: &Findings{Records: records, Messages: messages}}
|
||||||
|
acquired.Explanation = explanation
|
||||||
|
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]{}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, nil, acquired, fmt.Errorf("ConfigKit scope %q comparison before left load: %w", name, err)
|
||||||
|
}
|
||||||
|
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 nil, nil, acquired, err
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, nil, acquired, fmt.Errorf("ConfigKit scope %q comparison after left load: %w", name, err)
|
||||||
|
}
|
||||||
|
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 nil, nil, acquired, err
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, nil, acquired, fmt.Errorf("ConfigKit scope %q comparison before native diff: %w", name, err)
|
||||||
|
}
|
||||||
|
return left, right, acquired, nil
|
||||||
|
}
|
||||||
|
|
||||||
func loadComparisonSide[I, S, T any](
|
func loadComparisonSide[I, S, T any](
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
scope, side string,
|
scope, side string,
|
||||||
|
|||||||
@@ -80,11 +80,19 @@ type ExplanationReader interface {
|
|||||||
Explain(configkit.Path) (configkit.Explanation, bool)
|
Explain(configkit.Path) (configkit.Explanation, bool)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PathReader supplies native candidates for configuration path discovery.
|
||||||
|
type PathReader interface {
|
||||||
|
HistoricalPaths() []configkit.Path
|
||||||
|
}
|
||||||
|
|
||||||
// View exposes native configuration evidence used to build reports.
|
// View exposes native configuration evidence used to build reports.
|
||||||
type View struct {
|
type View struct {
|
||||||
Effective EffectiveWriter
|
Effective EffectiveWriter
|
||||||
Sources SourceReader
|
Sources SourceReader
|
||||||
Explanation ExplanationReader
|
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 supplies native configuration path metadata when available.
|
||||||
Metadata *configkit.Metadata
|
Metadata *configkit.Metadata
|
||||||
// Findings supplies native diagnostics and their ordinary presentations.
|
// Findings supplies native diagnostics and their ordinary presentations.
|
||||||
@@ -102,7 +110,8 @@ type Findings struct {
|
|||||||
|
|
||||||
// ScopeFeatures describes optional modes within configuration operations.
|
// ScopeFeatures describes optional modes within configuration operations.
|
||||||
type ScopeFeatures struct {
|
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
|
PathDiscovery bool
|
||||||
// PathShow indicates support for displaying a selected effective path.
|
// PathShow indicates support for displaying a selected effective path.
|
||||||
PathShow bool
|
PathShow bool
|
||||||
|
|||||||
@@ -154,3 +154,68 @@ func TestExplainBareHelpRecordsDeliveryFailure(t *testing.T) {
|
|||||||
t.Fatalf("help delivery = %#v, input/state/acquire=%d/%d/%d", result, inputs, states, calls)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,6 +4,12 @@
|
|||||||
// Use AppCommand for one application configuration loader, or Command with a
|
// Use AppCommand for one application configuration loader, or Command with a
|
||||||
// Suite for multiple named configurations and application-specific flags.
|
// Suite for multiple named configurations and application-specific flags.
|
||||||
// Install the returned command with commandkit.New or App.Register.
|
// 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.
|
// Importing this package alone installs no commands.
|
||||||
//
|
//
|
||||||
// ConfigKit owns configuration loading and interpretation. CommandKit formats
|
// ConfigKit owns configuration loading and interpretation. CommandKit formats
|
||||||
|
|||||||
@@ -2,16 +2,16 @@
|
|||||||
|
|
||||||
## ConfigKit
|
## ConfigKit
|
||||||
|
|
||||||
Selected module: `go.maximumdirect.net/configkit` at `v1.2.1`.
|
Selected module: `go.maximumdirect.net/configkit` at `v1.4.0`.
|
||||||
|
|
||||||
Copyright (C) 2026 Eric Rakestraw
|
Copyright (C) 2026 Eric Rakestraw
|
||||||
|
|
||||||
SPDX-License-Identifier: LGPL-3.0-or-later
|
SPDX-License-Identifier: LGPL-3.0-or-later
|
||||||
|
|
||||||
License and notices: [LGPL v3.0](../../LICENSE) |
|
License and notices: [LGPL v3.0](../../LICENSE) |
|
||||||
[LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/commit/51ef3144158db1a09fabdbd1c7ae59908c84923b/LICENSE).
|
[LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3/LICENSE).
|
||||||
|
|
||||||
[Source](https://forge.maximumdirect.net/base-layer/configkit/src/commit/51ef3144158db1a09fabdbd1c7ae59908c84923b).
|
[Source](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3).
|
||||||
|
|
||||||
## go-yaml v4
|
## go-yaml v4
|
||||||
|
|
||||||
|
|||||||
23
integrations/ckconfig/docs/releases/v0.10.0.md
Normal file
23
integrations/ckconfig/docs/releases/v0.10.0.md
Normal 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)
|
||||||
25
integrations/ckconfig/docs/releases/v0.11.0.md
Normal file
25
integrations/ckconfig/docs/releases/v0.11.0.md
Normal 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)
|
||||||
@@ -134,7 +134,11 @@ func runConfigExplanation[I, S any](invocation commandkit.Invocation, plan *conf
|
|||||||
if plan.under != nil {
|
if plan.under != nil {
|
||||||
prefix = pointerTokens(plan.under.String())
|
prefix = pointerTokens(plan.under.String())
|
||||||
}
|
}
|
||||||
for _, path := range acquired.Value.Metadata.HistoricalPaths() {
|
paths := acquired.Value.Paths
|
||||||
|
if paths == nil {
|
||||||
|
paths = acquired.Value.Metadata
|
||||||
|
}
|
||||||
|
for _, path := range paths.HistoricalPaths() {
|
||||||
pointer := path.String()
|
pointer := path.String()
|
||||||
if plan.under != nil && !pathWithin(pointer, prefix) {
|
if plan.under != nil && !pathWithin(pointer, prefix) {
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ module go.maximumdirect.net/ckconfig
|
|||||||
go 1.27.0
|
go 1.27.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
go.maximumdirect.net/commandkit v0.7.0
|
go.maximumdirect.net/commandkit v0.8.0
|
||||||
go.maximumdirect.net/configkit v1.2.1
|
go.maximumdirect.net/configkit v1.4.0
|
||||||
go.yaml.in/yaml/v4 v4.0.0
|
go.yaml.in/yaml/v4 v4.0.0
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -9,8 +9,10 @@ github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag=
|
|||||||
github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
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 h1:toLDGhHoVe6gBX5HWuzQ/Joz0cBqEhJXolW21m3axBk=
|
||||||
go.maximumdirect.net/commandkit v0.7.0/go.mod h1:sVp3JXKpm2YrP4Ie8Q3nWmQgwBdPN8uO+wQU72erDns=
|
go.maximumdirect.net/commandkit v0.7.0/go.mod h1:sVp3JXKpm2YrP4Ie8Q3nWmQgwBdPN8uO+wQU72erDns=
|
||||||
go.maximumdirect.net/configkit v1.2.1 h1:f+/6WjNl6CULbMr6ZSVwi4aty9rmuDfJlvpeU7I+HZM=
|
go.maximumdirect.net/commandkit v0.8.0 h1:EBDjr7SvfgvVDsA2S95hkOhgZe7oGZdDvURDJxHyX48=
|
||||||
go.maximumdirect.net/configkit v1.2.1/go.mod h1:ewu6blSokUDCMovy8JBXAdXRikGmlHXAQpFghnPWRfs=
|
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/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 h1:/LG1pNO84Z4l603j/xMn69CcS5OYhMQ/f7l2LoQUGuw=
|
||||||
go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
|
go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
|
||||||
|
|||||||
52
integrations/ckconfig/help_feature_test.go
Normal file
52
integrations/ckconfig/help_feature_test.go
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -150,7 +150,13 @@ func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operatio
|
|||||||
if input == nil {
|
if input == nil {
|
||||||
return fmt.Errorf("configuration input must not be 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 {
|
Run: func(invocation commandkit.Invocation, input *configCommandInput[I, S]) commandkit.Outcome {
|
||||||
return runConfigOperation(invocation, operation, input)
|
return runConfigOperation(invocation, operation, input)
|
||||||
|
|||||||
182
integrations/ckconfig/subtree_adapter_test.go
Normal file
182
integrations/ckconfig/subtree_adapter_test.go
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
later](COPYRIGHT). The accompanying [LICENSE](LICENSE) contains the full LGPL
|
||||||
v3 and GPL v3 texts. See [third-party attribution](docs/oss/attribution.md)
|
v3 and GPL v3 texts. See [third-party attribution](docs/oss/attribution.md)
|
||||||
for incorporated and dependency notices.
|
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.
|
||||||
|
|||||||
@@ -295,6 +295,7 @@ func ConfigScope[I, S any](load func(context.Context, ckconfig.Selection, I, S)
|
|||||||
Effective: *inspection,
|
Effective: *inspection,
|
||||||
Sources: *inspection,
|
Sources: *inspection,
|
||||||
Explanation: *inspection,
|
Explanation: *inspection,
|
||||||
|
Paths: *inspection,
|
||||||
Metadata: &metadata,
|
Metadata: &metadata,
|
||||||
Findings: &ckconfig.Findings{Records: inspection.Diagnostics(), Messages: messages.diagnostics},
|
Findings: &ckconfig.Findings{Records: inspection.Diagnostics(), Messages: messages.diagnostics},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -98,6 +98,9 @@ func adapterEngineFrom(t *testing.T, label, configuration string, options ...pro
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
for index := range inputs {
|
||||||
|
inputs[index].Destination = configkit.Keys("promptkit")
|
||||||
|
}
|
||||||
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{
|
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{
|
||||||
Underlays: []configkit.Underlay{{Inputs: inputs}},
|
Underlays: []configkit.Underlay{{Inputs: inputs}},
|
||||||
}}, append([]promptkit.Option{promptkit.WithBundledOpenRouter(false)}, options...)...)
|
}}, append([]promptkit.Option{promptkit.WithBundledOpenRouter(false)}, options...)...)
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ func buildCommand[I, S any](suite Suite[I, S], aliases *[]commandkit.Declaration
|
|||||||
for _, issue := range suite.issues {
|
for _, issue := range suite.issues {
|
||||||
command = commandkit.WithError(command, issue)
|
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 {
|
func newCatalogListCommand[I, S any](suite Suite[I, S], name string) commandkit.Command {
|
||||||
|
|||||||
@@ -247,6 +247,9 @@ profiles:
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
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))
|
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Underlays: []configkit.Underlay{{Inputs: inputs}}}}, promptkit.WithBundledOpenRouter(false))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("construct comparison engine: %v", err)
|
t.Fatalf("construct comparison engine: %v", err)
|
||||||
|
|||||||
@@ -163,6 +163,9 @@ profiles:
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
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))
|
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Underlays: []configkit.Underlay{{Inputs: inputs}}}}, promptkit.WithBundledOpenRouter(false))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("construct engine: %v", err)
|
t.Fatalf("construct engine: %v", err)
|
||||||
|
|||||||
@@ -81,8 +81,8 @@ func TestPromptConstructorFailurePrecedence(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
_, invalid := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Main: &configkit.Input{Source: configkit.File(malformed)}}}, promptkit.WithBundledOpenRouter(false))
|
_, invalid := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Main: &configkit.Input{Source: configkit.File(malformed)}}}, promptkit.WithBundledOpenRouter(false))
|
||||||
_, missing := promptkit.NewEngine(promptkit.Config{}, promptkit.WithBundledOpenRouter(false), promptkit.WithSchemaFile(filepath.Join(dir, "missing.json")))
|
_, 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) || !errors.Is(missing, os.ErrNotExist) {
|
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)
|
t.Fatalf("constructor fixtures invalid=%v missing=%v", invalid, missing)
|
||||||
}
|
}
|
||||||
operational := errors.New("independent failure")
|
operational := errors.New("independent failure")
|
||||||
@@ -91,11 +91,13 @@ func TestPromptConstructorFailurePrecedence(t *testing.T) {
|
|||||||
cause error
|
cause error
|
||||||
extra error
|
extra error
|
||||||
canceled bool
|
canceled bool
|
||||||
|
kind commandkit.OutcomeKind
|
||||||
}{
|
}{
|
||||||
{"missing schema", missing, os.ErrNotExist, false},
|
{"missing configuration", missing, promptkit.ErrInvalidConfig, false, commandkit.OutcomeOperational},
|
||||||
{"joined operational", errors.Join(invalid, operational), operational, false},
|
{"joined missing error", errors.Join(missing, os.ErrNotExist), os.ErrNotExist, false, commandkit.OutcomeOperational},
|
||||||
{"joined cancellation", errors.Join(invalid, context.Canceled), context.Canceled, false},
|
{"joined operational", errors.Join(invalid, operational), operational, false, commandkit.OutcomeOperational},
|
||||||
{"already canceled", nil, context.Canceled, true},
|
{"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"}} {
|
for _, args := range [][]string{{"promptkit", "list", "prompts"}, {"config", "show", "--scope=promptkit"}} {
|
||||||
t.Run(tc.name+"/"+strings.Join(args, "_"), func(t *testing.T) {
|
t.Run(tc.name+"/"+strings.Join(args, "_"), func(t *testing.T) {
|
||||||
@@ -115,7 +117,7 @@ func TestPromptConstructorFailurePrecedence(t *testing.T) {
|
|||||||
}
|
}
|
||||||
var out bytes.Buffer
|
var out bytes.Buffer
|
||||||
result := app.Execute(ctx, args, commandkit.Streams{Out: &out})
|
result := app.Execute(ctx, args, commandkit.Streams{Out: &out})
|
||||||
if result.Kind != commandkit.OutcomeOperational || result.Status != 1 || !errors.Is(result.Cause, tc.extra) {
|
if result.Kind != tc.kind || !errors.Is(result.Cause, tc.extra) {
|
||||||
t.Fatalf("outcome=%#v output=%q", result, out.String())
|
t.Fatalf("outcome=%#v output=%q", result, out.String())
|
||||||
}
|
}
|
||||||
if tc.canceled {
|
if tc.canceled {
|
||||||
|
|||||||
@@ -7,7 +7,17 @@
|
|||||||
// family; Declarations also includes its convenience flag aliases. Install
|
// family; Declarations also includes its convenience flag aliases. Install
|
||||||
// these with commandkit.New or App.Register.
|
// 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 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
|
// Importing this package installs neither command family. Applications own
|
||||||
// engine construction, credentials, and client configuration.
|
// engine construction, credentials, and client configuration.
|
||||||
package ckprompt
|
package ckprompt
|
||||||
|
|||||||
@@ -2,29 +2,29 @@
|
|||||||
|
|
||||||
## PromptKit
|
## PromptKit
|
||||||
|
|
||||||
Selected module: `go.maximumdirect.net/promptkit` at `v0.23.2`.
|
Selected module: `go.maximumdirect.net/promptkit` at `v0.25.0`.
|
||||||
|
|
||||||
Copyright (C) 2026 Eric Rakestraw
|
Copyright (C) 2026 Eric Rakestraw
|
||||||
|
|
||||||
SPDX-License-Identifier: LGPL-3.0-or-later
|
SPDX-License-Identifier: LGPL-3.0-or-later
|
||||||
|
|
||||||
License and notices: [LGPL v3.0](../../LICENSE) |
|
License and notices: [LGPL v3.0](../../LICENSE) |
|
||||||
[LICENSE](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/LICENSE).
|
[LICENSE](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/LICENSE).
|
||||||
|
|
||||||
[Source](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71).
|
[Source](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d).
|
||||||
|
|
||||||
## ConfigKit
|
## ConfigKit
|
||||||
|
|
||||||
Selected module: `go.maximumdirect.net/configkit` at `v1.2.1` (direct dependency).
|
Selected module: `go.maximumdirect.net/configkit` at `v1.4.0` (direct dependency).
|
||||||
|
|
||||||
Copyright (C) 2026 Eric Rakestraw
|
Copyright (C) 2026 Eric Rakestraw
|
||||||
|
|
||||||
SPDX-License-Identifier: LGPL-3.0-or-later
|
SPDX-License-Identifier: LGPL-3.0-or-later
|
||||||
|
|
||||||
License and notices: [LGPL v3.0](../../LICENSE) |
|
License and notices: [LGPL v3.0](../../LICENSE) |
|
||||||
[LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/commit/51ef3144158db1a09fabdbd1c7ae59908c84923b/LICENSE).
|
[LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3/LICENSE).
|
||||||
|
|
||||||
[Source](https://forge.maximumdirect.net/base-layer/configkit/src/commit/51ef3144158db1a09fabdbd1c7ae59908c84923b).
|
[Source](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3).
|
||||||
|
|
||||||
## ReleaseKit
|
## ReleaseKit
|
||||||
|
|
||||||
|
|||||||
38
integrations/ckprompt/docs/releases/v0.11.0.md
Normal file
38
integrations/ckprompt/docs/releases/v0.11.0.md
Normal 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)
|
||||||
62
integrations/ckprompt/docs/releases/v0.12.0.md
Normal file
62
integrations/ckprompt/docs/releases/v0.12.0.md
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
# 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
|
||||||
|
|
||||||
|
The coordinated release targets 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.
|
||||||
|
|
||||||
|
Draft preparation: publish core and ckconfig first, then align this module's two
|
||||||
|
CommandKit requirements and run its independent suite against those published
|
||||||
|
versions. The current checkout still selects the prior published requirements;
|
||||||
|
workspace and temporary local-source checks do not replace that release check.
|
||||||
|
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)
|
||||||
@@ -6,8 +6,8 @@ in-memory model client. **No model service or credentials are required.**
|
|||||||
|
|
||||||
Use Go 1.27.0 on `PATH`. An aligned workspace containing all three local modules
|
Use Go 1.27.0 on `PATH`. An aligned workspace containing all three local modules
|
||||||
exercises their current sources; follow the [workspace setup](../../../../docs/development.md#documentation-validation)
|
exercises their current sources; follow the [workspace setup](../../../../docs/development.md#documentation-validation)
|
||||||
from the repository root. The example also builds independently with
|
from the repository root. The current unreleased example requires the aligned workspace until core and
|
||||||
`GOWORK=off` against its module's released dependencies.
|
the integrations are released with aligned dependencies.
|
||||||
The [consumer guide](../../../../docs/consumers/guide.md#module-selection) owns
|
The [consumer guide](../../../../docs/consumers/guide.md#module-selection) owns
|
||||||
version and compatibility details.
|
version and compatibility details.
|
||||||
|
|
||||||
@@ -21,7 +21,7 @@ go run . promptkit list prompts --campaign spring
|
|||||||
go run . promptkit show prompt briefing --campaign spring --format yaml
|
go run . promptkit show prompt briefing --campaign spring --format yaml
|
||||||
```
|
```
|
||||||
|
|
||||||
The first command lists `app` and `promptkit` configurations and their available
|
The first command lists `app`, `storage`, and `promptkit` configurations and their available
|
||||||
operations. The next commands find and inspect the `briefing` prompt.
|
operations. The next commands find and inspect the `briefing` prompt.
|
||||||
`--campaign` is a selector supplied by this example, not a standard PromptKit flag.
|
`--campaign` is a selector supplied by this example, not a standard PromptKit flag.
|
||||||
|
|
||||||
@@ -30,6 +30,8 @@ operations. The next commands find and inspect the `briefing` prompt.
|
|||||||
```sh
|
```sh
|
||||||
go run . config validate --scope all --campaign spring --limit=0
|
go run . config validate --scope all --campaign spring --limit=0
|
||||||
go run . config diff --scope app --config fixtures/before.yml --against-config fixtures/after.yml
|
go run . config diff --scope app --config fixtures/before.yml --against-config fixtures/after.yml
|
||||||
|
go run . config show --scope storage --config fixtures/before.yml
|
||||||
|
go run . config diff --scope storage --config fixtures/before.yml --against-config fixtures/after.yml
|
||||||
go run . config diff --scope promptkit --config fixtures/before.yml --against-config fixtures/after.yml --campaign spring --against-campaign spring
|
go run . config diff --scope promptkit --config fixtures/before.yml --against-config fixtures/after.yml --campaign spring --against-campaign spring
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -44,8 +46,8 @@ The two sides have independent selectors and overrides:
|
|||||||
go run . config diff --scope app --campaign spring --limit=0 --against-campaign autumn --against-limit=0 --set '/campaigns/spring/model="left"' --against-set '/campaigns/spring/model="right"' --details
|
go run . config diff --scope app --campaign spring --limit=0 --against-campaign autumn --against-limit=0 --set '/campaigns/spring/model="left"' --against-set '/campaigns/spring/model="right"' --details
|
||||||
```
|
```
|
||||||
|
|
||||||
Only the application scope supports `--set` here. The released PromptKit loader
|
The application and storage scopes support `--set` here. The PromptKit scope
|
||||||
has no override handoff, so its configuration scope does not enable the feature.
|
does not advertise override support in this example.
|
||||||
An aggregate operation that includes that scope rejects overrides.
|
An aggregate operation that includes that scope rejects overrides.
|
||||||
|
|
||||||
## List resources and select namespaces
|
## List resources and select namespaces
|
||||||
@@ -155,7 +157,9 @@ selects the command context without loading an engine.
|
|||||||
The example installs `ckconfig.Command(suite)` and
|
The example installs `ckconfig.Command(suite)` and
|
||||||
`ckprompt.Declarations(definitions)` with application-owned aliases in a
|
`ckprompt.Declarations(definitions)` with application-owned aliases in a
|
||||||
`[]commandkit.Declaration`. `NewInput` initializes scope inputs; `NewState`
|
`[]commandkit.Declaration`. `NewInput` initializes scope inputs; `NewState`
|
||||||
creates a cache shared within an invocation. The loaders cache successful
|
creates a cache shared within an invocation. The application composes PromptKit
|
||||||
|
settings and resources into its ConfigKit load; the engine consumes the same
|
||||||
|
result, and `FromConfigKitSubtree` exposes `storage`. The loaders cache successful
|
||||||
configuration results by the complete configuration/overlay selection,
|
configuration results by the complete configuration/overlay selection,
|
||||||
overrides, and supplied campaign, including whether each value was supplied.
|
overrides, and supplied campaign, including whether each value was supplied.
|
||||||
These are example choices, not a CommandKit cache policy.
|
These are example choices, not a CommandKit cache policy.
|
||||||
@@ -169,3 +173,14 @@ the complete application.
|
|||||||
Run `GOWORK=auto GOTOOLCHAIN=local go test ./...` from this example directory
|
Run `GOWORK=auto GOTOOLCHAIN=local go test ./...` from this example directory
|
||||||
for an aligned workspace check. Use
|
for an aligned workspace check. Use
|
||||||
`GOWORK=off GOTOOLCHAIN=local go test ./...` to check the declared releases.
|
`GOWORK=off GOTOOLCHAIN=local go test ./...` to check the declared releases.
|
||||||
|
|
||||||
|
## Observe a pipeline
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run . pipeline run --show-tokens
|
||||||
|
go run . pipeline run --show-tokens --format json
|
||||||
|
```
|
||||||
|
|
||||||
|
The application passes its invocation context to both prompt executions. The
|
||||||
|
injected client provides the example usage and cost; ckprompt reports their
|
||||||
|
aggregate on diagnostics without accounting code in the pipeline handler.
|
||||||
|
|||||||
@@ -8,3 +8,6 @@ campaigns:
|
|||||||
prompt_id: briefing
|
prompt_id: briefing
|
||||||
profile_id: autumn
|
profile_id: autumn
|
||||||
model: autumn-model
|
model: autumn-model
|
||||||
|
storage:
|
||||||
|
driver: local
|
||||||
|
location: ./after
|
||||||
|
|||||||
@@ -8,3 +8,6 @@ campaigns:
|
|||||||
prompt_id: briefing
|
prompt_id: briefing
|
||||||
profile_id: autumn
|
profile_id: autumn
|
||||||
model: autumn-model
|
model: autumn-model
|
||||||
|
storage:
|
||||||
|
driver: local
|
||||||
|
location: ./before
|
||||||
|
|||||||
@@ -22,9 +22,16 @@ type campaign struct {
|
|||||||
Model string `yaml:"model"`
|
Model string `yaml:"model"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type storageConfiguration struct {
|
||||||
|
Driver string `yaml:"driver"`
|
||||||
|
Location string `yaml:"location"`
|
||||||
|
}
|
||||||
|
|
||||||
type appConfiguration struct {
|
type appConfiguration struct {
|
||||||
DefaultCampaign string `yaml:"default_campaign"`
|
PromptKit promptkit.Settings `yaml:"promptkit"`
|
||||||
Campaigns map[string]campaign `yaml:"campaigns"`
|
Storage storageConfiguration `yaml:"storage"`
|
||||||
|
DefaultCampaign string `yaml:"default_campaign"`
|
||||||
|
Campaigns map[string]campaign `yaml:"campaigns"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type inspectionInput struct {
|
type inspectionInput struct {
|
||||||
@@ -53,7 +60,8 @@ func (client *exampleLLMClient) Generate(context.Context, promptkit.GenerateRequ
|
|||||||
if client.calls != nil {
|
if client.calls != nil {
|
||||||
(*client.calls)++
|
(*client.calls)++
|
||||||
}
|
}
|
||||||
return &promptkit.GenerateResponse{Content: "Example response."}, nil
|
cost := 0.00125
|
||||||
|
return &promptkit.GenerateResponse{Content: "Example response.", Usage: promptkit.TokenUsage{PromptTokens: 10, CompletionTokens: 4, TotalTokens: 14, ReasoningTokens: 1, CachedTokens: 2, CacheWriteTokens: 0}, UsagePresence: &promptkit.TokenUsagePresence{PromptTokens: true, CompletionTokens: true, TotalTokens: true, ReasoningTokens: true, CachedTokens: true, CacheWriteTokens: true}, CostUSD: &cost}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type restoreInput struct {
|
type restoreInput struct {
|
||||||
@@ -95,26 +103,75 @@ func loadApplicationConfig(ctx context.Context, selection ckconfig.Selection, in
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
source := configkit.Mapping("composed application settings", map[string]any{
|
definition := configkit.Definition[appConfiguration]{
|
||||||
"default_campaign": "spring",
|
Defaults: func() appConfiguration {
|
||||||
"campaigns": map[string]any{
|
return appConfiguration{DefaultCampaign: "spring", Storage: storageConfiguration{Driver: "local", Location: "./data"}, Campaigns: map[string]campaign{
|
||||||
"spring": map[string]any{"prompt_id": "briefing", "profile_id": "spring", "model": "spring-model"},
|
"spring": {PromptID: "briefing", ProfileID: "spring", Model: "spring-model"},
|
||||||
"autumn": map[string]any{"prompt_id": "briefing", "profile_id": "autumn", "model": "autumn-model"},
|
"autumn": {PromptID: "briefing", ProfileID: "autumn", Model: "autumn-model"},
|
||||||
|
}}
|
||||||
},
|
},
|
||||||
})
|
Resolve: func(value *appConfiguration, resolution *configkit.Resolution) error {
|
||||||
|
name, chosen, err := selectedCampaign(*value, commandkit.Supplied[string]{})
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
deps := []configkit.Path{configkit.Keys("default_campaign"), configkit.Keys("campaigns", name)}
|
||||||
|
profilePath := configkit.Keys("promptkit", "profiles")
|
||||||
|
profileFound := false
|
||||||
|
for _, profile := range value.PromptKit.Profiles {
|
||||||
|
if profile.ID == chosen.ProfileID {
|
||||||
|
profileFound = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !profileFound {
|
||||||
|
value.PromptKit.Profiles = append(value.PromptKit.Profiles, promptkit.ProfileSettings{ID: chosen.ProfileID, Backend: new("local"), Endpoint: new("https://example.invalid/v1"), Model: new(chosen.Model), ExtraParams: map[string]any{"campaign": name}})
|
||||||
|
resolution.RecordNormalization(profilePath, "Selected campaign profile", deps...)
|
||||||
|
}
|
||||||
|
promptPath := configkit.Keys("promptkit", "prompts")
|
||||||
|
for index := range value.PromptKit.Prompts {
|
||||||
|
prompt := &value.PromptKit.Prompts[index]
|
||||||
|
if prompt.ID != "briefing" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if chosen.PromptID != prompt.ID {
|
||||||
|
prompt.ID = chosen.PromptID
|
||||||
|
resolution.RecordNormalization(promptPath, "Selected campaign prompt", deps...)
|
||||||
|
}
|
||||||
|
if prompt.DefaultProfile == nil {
|
||||||
|
prompt.DefaultProfile = new(chosen.ProfileID)
|
||||||
|
resolution.RecordDerivedDefault(promptPath.Index(index).Key("default_profile"), "Selected campaign profile", deps...)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
definition = promptkit.Configure(definition, func(value *appConfiguration) *promptkit.Settings { return &value.PromptKit })
|
||||||
|
resources := promptkit.SettingsInput(configkit.Mapping("example resources", map[string]any{
|
||||||
|
"collections": map[string]any{"field-notes": map[string]any{
|
||||||
|
"release_version": "1",
|
||||||
|
"backends": []any{map[string]any{"id": "demo", "endpoint": "https://example.invalid/v1"}},
|
||||||
|
"profiles": []any{map[string]any{"id": "assistant", "backend": "field-notes/demo", "model": "example-model"}},
|
||||||
|
"prompts": []any{map[string]any{"id": "briefing", "default_profile": "field-notes/assistant", "inputs": []any{map[string]any{"name": "topic", "required": true, "content_type": "text/plain", "description": "Topic to brief"}}, "messages": []any{map[string]any{"role": "user", "content": "Write a concise briefing about {{.topic}}."}}, "output": map[string]any{"format": "text", "validation_mode": "none"}}},
|
||||||
|
}},
|
||||||
|
"prompts": []any{map[string]any{"id": "briefing", "inputs": []any{map[string]any{"name": "topic", "required": true, "content_type": "text/plain", "description": "Topic to brief"}}, "messages": []any{map[string]any{"role": "user", "content": "Write a concise briefing about {{.topic}}. {{if .mode}}{{input \"notes\"}}{{end}}"}}, "output": map[string]any{"format": "text", "validation_mode": "none"}}},
|
||||||
|
"backends": []any{map[string]any{"id": "local", "endpoint": "https://example.invalid/v1"}},
|
||||||
|
}))
|
||||||
|
source := configkit.NoSource()
|
||||||
if selection.Config.Set {
|
if selection.Config.Set {
|
||||||
source = configkit.File(selection.Config.Value)
|
source = configkit.File(selection.Config.Value)
|
||||||
}
|
}
|
||||||
options := configkit.Options[appConfiguration]{}
|
options := configkit.LayeredOptions[appConfiguration]{Definition: definition, Underlays: []configkit.Underlay{promptkit.BundledOpenRouterUnderlay(), {Inputs: []configkit.Input{resources}}}}
|
||||||
if selection.Overlay.Set {
|
if selection.Overlay.Set {
|
||||||
options.Overlay = selection.Overlay.Value
|
options.Overlay = selection.Overlay.Value
|
||||||
options.Filesystem = &configkit.FilesystemContext{Root: ".", BaseDir: "."}
|
options.OverlayFilesystem = &configkit.FilesystemContext{Root: ".", BaseDir: "."}
|
||||||
}
|
}
|
||||||
if campaignInput.Set {
|
if campaignInput.Set {
|
||||||
options.Overrides = []configkit.Override{{Path: configkit.Keys("default_campaign"), Value: campaignInput.Value, Flag: "--campaign"}}
|
options.Overrides = []configkit.Override{{Path: configkit.Keys("default_campaign"), Value: campaignInput.Value, Flag: "--campaign"}}
|
||||||
}
|
}
|
||||||
options.Overrides = append(options.Overrides, selection.Overrides...)
|
options.Overrides = append(options.Overrides, selection.Overrides...)
|
||||||
result, err := configkit.Load(source, options)
|
result, err := configkit.LoadLayered(configkit.Input{Source: source}, options)
|
||||||
if err == nil && result != nil && cache != nil {
|
if err == nil && result != nil && cache != nil {
|
||||||
cache.applications = append(cache.applications, applicationCacheEntry{selection: selection, campaign: campaignInput, result: result})
|
cache.applications = append(cache.applications, applicationCacheEntry{selection: selection, campaign: campaignInput, result: result})
|
||||||
}
|
}
|
||||||
@@ -126,48 +183,14 @@ func loadPromptEngine(ctx context.Context, selection ckconfig.Selection, input *
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
name, chosen, err := selectedCampaign(application.Config, input.Campaign)
|
if _, _, err := selectedCampaign(application.Config, commandkit.Supplied[string]{}); err != nil {
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
engineConfig := configkit.Mapping("campaign "+name, map[string]any{
|
|
||||||
"collections": map[string]any{
|
|
||||||
"field-notes": map[string]any{
|
|
||||||
"release_version": "1",
|
|
||||||
"backends": []any{map[string]any{"id": "demo", "endpoint": "https://example.invalid/v1"}},
|
|
||||||
"profiles": []any{map[string]any{"id": "assistant", "backend": "field-notes/demo", "model": "example-model"}},
|
|
||||||
"prompts": []any{map[string]any{
|
|
||||||
"id": "briefing",
|
|
||||||
"default_profile": "field-notes/assistant",
|
|
||||||
"inputs": []any{map[string]any{"name": "topic", "required": true, "content_type": "text/plain", "description": "Topic to brief"}},
|
|
||||||
"messages": []any{map[string]any{"role": "user", "content": "Write a concise briefing about {{.topic}}."}},
|
|
||||||
"output": map[string]any{"format": "text", "validation_mode": "none"},
|
|
||||||
}},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"backends": []any{map[string]any{"id": "local", "endpoint": "https://example.invalid/v1"}},
|
|
||||||
"profiles": []any{map[string]any{
|
|
||||||
"id": chosen.ProfileID,
|
|
||||||
"backend": "local",
|
|
||||||
"endpoint": "https://example.invalid/v1",
|
|
||||||
"model": chosen.Model,
|
|
||||||
"extra_params": map[string]any{
|
|
||||||
"campaign": name,
|
|
||||||
},
|
|
||||||
}},
|
|
||||||
"prompts": []any{map[string]any{
|
|
||||||
"id": chosen.PromptID,
|
|
||||||
"default_profile": chosen.ProfileID,
|
|
||||||
"inputs": []any{map[string]any{"name": "topic", "required": true, "content_type": "text/plain", "description": "Topic to brief"}},
|
|
||||||
"messages": []any{map[string]any{"role": "user", "content": "Write a concise briefing about {{.topic}}. {{if .mode}}{{input \"notes\"}}{{end}}"}},
|
|
||||||
"output": map[string]any{"format": "text", "validation_mode": "none"},
|
|
||||||
}},
|
|
||||||
})
|
|
||||||
var client promptkit.LLMClient = &exampleLLMClient{}
|
var client promptkit.LLMClient = &exampleLLMClient{}
|
||||||
if cache != nil && cache.llmClient != nil {
|
if cache != nil && cache.llmClient != nil {
|
||||||
client = cache.llmClient
|
client = cache.llmClient
|
||||||
}
|
}
|
||||||
return promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Main: &configkit.Input{Source: engineConfig}}}, promptkit.WithLLMClient(client))
|
return promptkit.NewFromConfig(application, promptkit.RuntimeConfig{}, promptkit.WithLLMClient(client))
|
||||||
}
|
}
|
||||||
|
|
||||||
func selectedCampaign(configuration appConfiguration, supplied commandkit.Supplied[string]) (string, campaign, error) {
|
func selectedCampaign(configuration appConfiguration, supplied commandkit.Supplied[string]) (string, campaign, error) {
|
||||||
@@ -231,6 +254,8 @@ func newAppWithEngineLoader(
|
|||||||
|
|
||||||
appScope := ckconfig.FromConfigKit("app", "Application settings.", loadApplicationConfig)
|
appScope := ckconfig.FromConfigKit("app", "Application settings.", loadApplicationConfig)
|
||||||
appScope.Features.Overrides = true
|
appScope.Features.Overrides = true
|
||||||
|
storageScope := ckconfig.FromConfigKitSubtree("storage", "Storage settings.", configkit.Keys("storage"), loadApplicationConfig)
|
||||||
|
storageScope.Features.Overrides = true
|
||||||
engineScope := ckprompt.ConfigScope(engineLoader)
|
engineScope := ckprompt.ConfigScope(engineLoader)
|
||||||
configCommand := ckconfig.Command(ckconfig.Suite[*inspectionInput, *runCache]{
|
configCommand := ckconfig.Command(ckconfig.Suite[*inspectionInput, *runCache]{
|
||||||
NewInput: inputFactory,
|
NewInput: inputFactory,
|
||||||
@@ -242,10 +267,10 @@ func newAppWithEngineLoader(
|
|||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
Selectors: []ckconfig.Selector[*inspectionInput]{
|
Selectors: []ckconfig.Selector[*inspectionInput]{
|
||||||
{Binding: campaignSelector(), AgainstName: "against-campaign", Scopes: []string{"app", "promptkit"}},
|
{Binding: campaignSelector(), AgainstName: "against-campaign", Scopes: []string{"app", "storage", "promptkit"}},
|
||||||
{Binding: limitFlag, AgainstName: "against-limit", Scopes: []string{"app"}},
|
{Binding: limitFlag, AgainstName: "against-limit", Scopes: []string{"app"}},
|
||||||
},
|
},
|
||||||
Scopes: []ckconfig.Scope[*inspectionInput, *runCache]{appScope, engineScope},
|
Scopes: []ckconfig.Scope[*inspectionInput, *runCache]{appScope, storageScope, engineScope},
|
||||||
})
|
})
|
||||||
|
|
||||||
definitions := ckprompt.FromEngine(engineLoader)
|
definitions := ckprompt.FromEngine(engineLoader)
|
||||||
@@ -314,8 +339,25 @@ func newAppWithEngineLoader(
|
|||||||
return commandkit.Success()
|
return commandkit.Success()
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
pipeline := commandkit.NewCommand(commandkit.CommandSpec[struct{}]{Name: "run", Summary: "Run a two-prompt planning pipeline.", Run: func(inv commandkit.Invocation, _ struct{}) commandkit.Outcome {
|
||||||
|
engine, err := engineLoader(inv.Context, ckconfig.Selection{}, &inspectionInput{}, &runCache{llmClient: client})
|
||||||
|
if err != nil {
|
||||||
|
return commandkit.Failure("Could not load PromptKit engine.").WithCause(err)
|
||||||
|
}
|
||||||
|
results := make([]string, 0, 2)
|
||||||
|
for _, topic := range []string{"planning", "review"} {
|
||||||
|
result, err := engine.Run(inv.Context, promptkit.RunRequest{PromptID: "briefing", Inputs: map[string]promptkit.ArtifactRef{"topic": promptkit.Inline(topic)}, Vars: map[string]string{"mode": "", "topic": topic}})
|
||||||
|
if err != nil {
|
||||||
|
return commandkit.Failure("Pipeline prompt failed: " + err.Error()).WithCause(err)
|
||||||
|
}
|
||||||
|
results = append(results, result.RawOutput)
|
||||||
|
}
|
||||||
|
_ = inv.Reporter().Report(commandkit.Report{Value: results})
|
||||||
|
return commandkit.Success()
|
||||||
|
}})
|
||||||
declarations := []commandkit.Declaration{
|
declarations := []commandkit.Declaration{
|
||||||
configCommand,
|
configCommand,
|
||||||
|
commandkit.Group("pipeline", "Run an application pipeline.", pipeline),
|
||||||
commandkit.Completion("composed-example"),
|
commandkit.Completion("composed-example"),
|
||||||
commandkit.Group("session", "Manage saved sessions.", restore),
|
commandkit.Group("session", "Manage saved sessions.", restore),
|
||||||
commandkit.Group("request", "Inspect application-owned request inputs.", requestInspect),
|
commandkit.Group("request", "Inspect application-owned request inputs.", requestInspect),
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -294,7 +296,7 @@ func TestComposedPromptKitAndDomainCommandsRemainAvailable(t *testing.T) {
|
|||||||
{"config", "validate", "--scope", "all", "--campaign", "spring", "--limit=0"},
|
{"config", "validate", "--scope", "all", "--campaign", "spring", "--limit=0"},
|
||||||
{"config", "show", "--scope", "promptkit", "--campaign", "spring"},
|
{"config", "show", "--scope", "promptkit", "--campaign", "spring"},
|
||||||
{"config", "sources", "--scope", "promptkit", "--campaign", "spring"},
|
{"config", "sources", "--scope", "promptkit", "--campaign", "spring"},
|
||||||
{"config", "explain", "--scope", "promptkit", "--path", fmt.Sprintf("/profiles/%d/model", index), "--campaign", "spring"},
|
{"config", "explain", "--scope", "promptkit", "--path", fmt.Sprintf("/promptkit/profiles/%d/model", index), "--campaign", "spring"},
|
||||||
{"promptkit", "show", "prompt", "briefing", "--campaign", "spring", "--format", "yaml"},
|
{"promptkit", "show", "prompt", "briefing", "--campaign", "spring", "--format", "yaml"},
|
||||||
{"promptkit", "show", "profile", "spring", "--campaign", "spring"},
|
{"promptkit", "show", "profile", "spring", "--campaign", "spring"},
|
||||||
{"session", "restore", "session-42", "--campaign", "spring"},
|
{"session", "restore", "session-42", "--campaign", "spring"},
|
||||||
@@ -461,17 +463,19 @@ func TestPromptKitScopeDiffAndCatalogsUseSelectedCampaign(t *testing.T) {
|
|||||||
}
|
}
|
||||||
var diff struct {
|
var diff struct {
|
||||||
Changes struct {
|
Changes struct {
|
||||||
Profiles []struct {
|
PromptKit struct {
|
||||||
ID string `yaml:"id"`
|
Profiles []struct {
|
||||||
Model string `yaml:"model"`
|
ID string `yaml:"id"`
|
||||||
} `yaml:"profiles"`
|
Model string `yaml:"model"`
|
||||||
|
} `yaml:"profiles"`
|
||||||
|
} `yaml:"promptkit"`
|
||||||
} `yaml:"changes"`
|
} `yaml:"changes"`
|
||||||
}
|
}
|
||||||
if err := yaml.Unmarshal(output.Bytes(), &diff); err != nil {
|
if err := yaml.Unmarshal(output.Bytes(), &diff); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
foundChange := false
|
foundChange := false
|
||||||
for _, profile := range diff.Changes.Profiles {
|
for _, profile := range diff.Changes.PromptKit.Profiles {
|
||||||
if profile.ID == "spring" && profile.Model == "spring-model-after" {
|
if profile.ID == "spring" && profile.Model == "spring-model-after" {
|
||||||
foundChange = true
|
foundChange = true
|
||||||
}
|
}
|
||||||
@@ -740,3 +744,297 @@ func composedField(mapping *yaml.Node, name string) *yaml.Node {
|
|||||||
func ckconfigSelection(path string) ckconfig.Selection {
|
func ckconfigSelection(path string) ckconfig.Selection {
|
||||||
return ckconfig.Selection{Config: commandkit.Supplied[string]{Value: path, Set: true}}
|
return ckconfig.Selection{Config: commandkit.Supplied[string]{Value: path, Set: true}}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestComposedStorageScopeAndSharedResult(t *testing.T) {
|
||||||
|
cache := &runCache{}
|
||||||
|
selection := ckconfigSelection("fixtures/before.yml")
|
||||||
|
input := &inspectionInput{Campaign: commandkit.Supplied[string]{Value: "spring", Set: true}}
|
||||||
|
result, err := loadApplicationConfig(context.Background(), selection, input, cache)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
engine, err := loadPromptEngine(context.Background(), selection, input, cache)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(cache.applications) != 1 || cache.applications[0].result != result {
|
||||||
|
t.Fatal("engine did not use the selected application result")
|
||||||
|
}
|
||||||
|
inspection, err := engine.InspectConfiguration()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
appView, ok := result.InspectSubtree(configkit.Keys("promptkit"))
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("missing application inspection")
|
||||||
|
}
|
||||||
|
var appYAML, promptYAML bytes.Buffer
|
||||||
|
if err := appView.WriteEffective(&appYAML); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := inspection.WriteEffective(&promptYAML); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if appYAML.String() != promptYAML.String() {
|
||||||
|
t.Fatal("engine inspection differs from shared application result")
|
||||||
|
}
|
||||||
|
app, err := newApp()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
args []string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{[]string{"config", "show", "--scope=storage", "--config=fixtures/before.yml"}, "./before"},
|
||||||
|
{[]string{"config", "explain", "--scope=storage", "--config=fixtures/before.yml", "--path=/storage/location"}, "/storage/location"},
|
||||||
|
{[]string{"config", "diff", "--scope=storage", "--config=fixtures/before.yml", "--against-config=fixtures/after.yml"}, "./after"},
|
||||||
|
{[]string{"config", "show", "--scope=storage", `--set=/storage/location="custom"`, "--campaign=spring"}, "custom"},
|
||||||
|
{[]string{"config", "show", "--scope=app"}, "promptkit:"},
|
||||||
|
{[]string{"config", "validate", "--scope=all"}, "storage"},
|
||||||
|
} {
|
||||||
|
var output, diagnostics bytes.Buffer
|
||||||
|
outcome := app.Execute(context.Background(), tc.args, commandkit.Streams{Out: &output, Err: &diagnostics})
|
||||||
|
if outcome.Kind != commandkit.OutcomeSuccess || !strings.Contains(output.String(), tc.want) {
|
||||||
|
t.Errorf("%v: %#v output=%q diagnostics=%q", tc.args, outcome, output.String(), diagnostics.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var diagnostics bytes.Buffer
|
||||||
|
outcome := app.Execute(context.Background(), []string{"config", "show", "--scope=storage", "--config=fixtures/missing.yml"}, commandkit.Streams{Out: io.Discard, Err: &diagnostics})
|
||||||
|
if outcome.Kind != commandkit.OutcomeOperational || !strings.Contains(diagnostics.String(), "missing.yml") {
|
||||||
|
t.Fatalf("failed load: %#v %q", outcome, diagnostics.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestComposedCampaignPromptID(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "campaign.yml")
|
||||||
|
if err := os.WriteFile(path, []byte("campaigns:\n spring:\n prompt_id: custom\n profile_id: spring\n model: spring-model\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
selection := ckconfigSelection(path)
|
||||||
|
cache := &runCache{}
|
||||||
|
input := &inspectionInput{}
|
||||||
|
result, err := loadApplicationConfig(t.Context(), selection, input, cache)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
engine, err := loadPromptEngine(t.Context(), selection, input, cache)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
view, ok := result.InspectSubtree(configkit.Keys("promptkit"))
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("missing application inspection")
|
||||||
|
}
|
||||||
|
inspection, err := engine.InspectConfiguration()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var applicationOutput, engineOutput bytes.Buffer
|
||||||
|
if err := view.WriteEffective(&applicationOutput); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := inspection.WriteEffective(&engineOutput); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
applicationValue, err := commandkit.DecodeYAMLReport(&applicationOutput)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
engineValue, err := commandkit.DecodeYAMLReport(&engineOutput)
|
||||||
|
if err != nil || !reflect.DeepEqual(applicationValue, engineValue) {
|
||||||
|
t.Fatalf("shared inspection mismatch: application=%#v engine=%#v error=%v", applicationValue, engineValue, err)
|
||||||
|
}
|
||||||
|
app, err := newApp()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var output, diagnostics bytes.Buffer
|
||||||
|
outcome := app.Execute(t.Context(), []string{"promptkit", "list", "prompts", "--config=" + path, "--format=json"}, commandkit.Streams{Out: &output, Err: &diagnostics})
|
||||||
|
if outcome.Kind != commandkit.OutcomeSuccess {
|
||||||
|
t.Fatalf("catalog failed: %#v, %s", outcome, diagnostics.String())
|
||||||
|
}
|
||||||
|
var prompts []struct{ ID string }
|
||||||
|
if err := json.Unmarshal(output.Bytes(), &prompts); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, prompt := range prompts {
|
||||||
|
if prompt.ID == "custom" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("catalog lacks selected campaign prompt: %s", output.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPipelineAutomaticallyReportsNativeUsage(t *testing.T) {
|
||||||
|
app, err := newApp()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
args []string
|
||||||
|
summary bool
|
||||||
|
quiet bool
|
||||||
|
}{
|
||||||
|
{"enabled", []string{"pipeline", "run", "--show-tokens"}, true, false},
|
||||||
|
{"disabled", []string{"pipeline", "run", "--show-tokens=false"}, false, false},
|
||||||
|
{"omitted", []string{"pipeline", "run"}, false, false},
|
||||||
|
{"json", []string{"pipeline", "run", "--format=json", "--show-tokens"}, true, false},
|
||||||
|
{"quiet", []string{"pipeline", "run", "--quiet", "--show-tokens"}, false, true},
|
||||||
|
} {
|
||||||
|
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})
|
||||||
|
if result.Status != 0 || strings.Contains(diag.String(), "Observed PromptKit execution usage") != tc.summary {
|
||||||
|
t.Fatalf("%#v out=%q err=%q", result, out.String(), diag.String())
|
||||||
|
}
|
||||||
|
if tc.summary && (!strings.Contains(diag.String(), "Prompts: 2") || !strings.Contains(diag.String(), "Total tokens: 28") || !strings.Contains(diag.String(), "Cost: USD 0.0025 [provider]")) {
|
||||||
|
t.Fatalf("summary=%q", diag.String())
|
||||||
|
}
|
||||||
|
if tc.name == "json" && !strings.Contains(out.String(), `"Example response."`) {
|
||||||
|
t.Fatalf("json=%q", out.String())
|
||||||
|
}
|
||||||
|
if tc.quiet && out.Len() != 0 {
|
||||||
|
t.Fatalf("quiet output=%q", out.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPipelineAcquisitionFailureStillReports(t *testing.T) {
|
||||||
|
cause := errors.New("load failed")
|
||||||
|
app, err := newAppWithEngineLoader(nil, func(context.Context, ckconfig.Selection, *inspectionInput, *runCache) (*promptkit.Engine, error) {
|
||||||
|
return nil, cause
|
||||||
|
}, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var diag bytes.Buffer
|
||||||
|
out := app.Execute(context.Background(), []string{"pipeline", "run", "--show-tokens"}, commandkit.Streams{Err: &diag})
|
||||||
|
if !errors.Is(out.Cause, cause) || !strings.Contains(diag.String(), "Prompts: 0") || !strings.Contains(diag.String(), "ERROR:") {
|
||||||
|
t.Fatalf("%#v %q", out, diag.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestObserverCompositionAndInstallationPaths(t *testing.T) {
|
||||||
|
client := &exampleLLMClient{}
|
||||||
|
loads := 0
|
||||||
|
loader := func(ctx context.Context, selection ckconfig.Selection, input *inspectionInput, cache *runCache) (*promptkit.Engine, error) {
|
||||||
|
loads++
|
||||||
|
return loadPromptEngine(ctx, selection, input, cache)
|
||||||
|
}
|
||||||
|
suite := ckprompt.FromEngine(loader)
|
||||||
|
for _, factory := range []string{"command", "declarations"} {
|
||||||
|
for _, first := range []bool{true, false} {
|
||||||
|
var explicit int
|
||||||
|
command := commandkit.NewCommand(commandkit.CommandSpec[struct{}]{Name: "run", Run: func(inv commandkit.Invocation, _ struct{}) commandkit.Outcome {
|
||||||
|
engine, err := loader(inv.Context, ckconfig.Selection{}, &inspectionInput{}, &runCache{llmClient: client})
|
||||||
|
if err != nil {
|
||||||
|
return commandkit.Failure("load").WithCause(err)
|
||||||
|
}
|
||||||
|
for range 2 {
|
||||||
|
_, err = engine.Run(inv.Context, promptkit.RunRequest{PromptID: "briefing", Inputs: map[string]promptkit.ArtifactRef{"topic": promptkit.Inline("topic")}, Vars: map[string]string{"topic": "topic", "mode": ""}, Observer: func(promptkit.ExecutionEvent) { explicit++ }})
|
||||||
|
if err != nil {
|
||||||
|
return commandkit.Failure("run").WithCause(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return commandkit.Success()
|
||||||
|
}})
|
||||||
|
var declarations []commandkit.Declaration
|
||||||
|
if factory == "command" {
|
||||||
|
declarations = []commandkit.Declaration{ckprompt.Command(suite)}
|
||||||
|
} else {
|
||||||
|
declarations = ckprompt.Declarations(suite)
|
||||||
|
}
|
||||||
|
var app *commandkit.App
|
||||||
|
var err error
|
||||||
|
if first {
|
||||||
|
app, err = commandkit.New(commandkit.Identity{Name: "test"}, declarations...)
|
||||||
|
if err == nil {
|
||||||
|
err = app.Register(command)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
app, err = commandkit.New(commandkit.Identity{Name: "test"}, command)
|
||||||
|
if err == nil {
|
||||||
|
err = app.Register(declarations...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := app.Register(commandkit.Completion("test")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
before := loads
|
||||||
|
for _, args := range [][]string{{"run", "--help"}, {"promptkit", "--help"}, {"__complete", "run", "--show"}} {
|
||||||
|
app.Execute(context.Background(), args, commandkit.Streams{})
|
||||||
|
if loads != before {
|
||||||
|
t.Fatal("help acquired engine")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var diag bytes.Buffer
|
||||||
|
out := app.Execute(context.Background(), []string{"run", "--show-tokens"}, commandkit.Streams{Err: &diag})
|
||||||
|
if out.Status != 0 || explicit == 0 || !strings.Contains(diag.String(), "Prompts: 2") || !strings.Contains(diag.String(), "Total tokens: 28") {
|
||||||
|
t.Fatalf("%s %v: %#v explicit=%d %q", factory, first, out, explicit, diag.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
empty := ckprompt.Command(ckprompt.Suite[struct{}, struct{}]{})
|
||||||
|
app, err := commandkit.New(commandkit.Identity{Name: "test"}, empty, commandkit.NewCommand(commandkit.CommandSpec[struct{}]{Name: "run", Run: func(commandkit.Invocation, struct{}) commandkit.Outcome { return commandkit.Success() }}))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if out := app.Execute(context.Background(), []string{"run", "--show-tokens"}, commandkit.Streams{}); out.Kind != commandkit.OutcomeUsage {
|
||||||
|
t.Fatalf("empty suite installed flag: %#v", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSmokeUsageIsSeparateAndAliasAware(t *testing.T) {
|
||||||
|
app, err := newAppWithEngineLoader(nil, loadPromptEngine, func(_ context.Context, request ckprompt.SmokeRequest, _ *inspectionInput, _ *runCache) (commandkit.Acquired[*promptkit.SmokeTestReport], error) {
|
||||||
|
return commandkit.Acquired[*promptkit.SmokeTestReport]{Value: &promptkit.SmokeTestReport{Kind: request.Request.Kind, Supported: true}}, nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, args := range [][]string{{"promptkit", "test", "authentication", "--show-tokens"}, {"smoke", "authentication", "--show-tokens"}} {
|
||||||
|
var out, diag bytes.Buffer
|
||||||
|
result := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diag})
|
||||||
|
if result.Status != 0 || !strings.Contains(diag.String(), "Prompts: 0") || !strings.Contains(diag.String(), "Smoke-test usage is reported separately") || !strings.Contains(out.String(), "authentication") {
|
||||||
|
t.Fatalf("%v: %#v %q %q", args, result, out.String(), diag.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNarrowSuiteReportsReturnedCancellation(t *testing.T) {
|
||||||
|
suite := ckprompt.Suite[struct{}, struct{}]{InspectPrompt: func(context.Context, ckprompt.PromptRequest, struct{}, struct{}) (commandkit.Acquired[*promptkit.PromptInspection], error) {
|
||||||
|
t.Fatal("unexpected acquisition")
|
||||||
|
return commandkit.Acquired[*promptkit.PromptInspection]{}, nil
|
||||||
|
}}
|
||||||
|
command := commandkit.NewCommand(commandkit.CommandSpec[struct{}]{Name: "run", Run: func(inv commandkit.Invocation, _ struct{}) commandkit.Outcome {
|
||||||
|
return commandkit.Failure("canceled").WithCause(context.Canceled)
|
||||||
|
}})
|
||||||
|
app, err := commandkit.New(commandkit.Identity{Name: "test"}, ckprompt.Command(suite), command)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var diag bytes.Buffer
|
||||||
|
out := app.Execute(context.Background(), []string{"run", "--show-tokens"}, commandkit.Streams{Err: &diag})
|
||||||
|
if !errors.Is(out.Cause, context.Canceled) || !strings.Contains(diag.String(), "Prompts: 0") || !strings.Contains(diag.String(), "ERROR: canceled") {
|
||||||
|
t.Fatalf("%#v %q", out, diag.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExplainHelpDoesNotReportUsage(t *testing.T) {
|
||||||
|
app, err := newApp()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, args := range [][]string{{"config", "explain", "--show-tokens"}, {"config", "explain", "--help", "--show-tokens"}} {
|
||||||
|
var out, diag bytes.Buffer
|
||||||
|
result := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diag})
|
||||||
|
if result.Status != 0 || !strings.Contains(out.String(), "Usage:") || diag.Len() != 0 {
|
||||||
|
t.Fatalf("%v: %#v %q %q", args, result, out.String(), diag.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,10 +3,10 @@ module go.maximumdirect.net/ckprompt
|
|||||||
go 1.27.0
|
go 1.27.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
go.maximumdirect.net/ckconfig v0.9.0
|
go.maximumdirect.net/ckconfig v0.10.0
|
||||||
go.maximumdirect.net/commandkit v0.7.0
|
go.maximumdirect.net/commandkit v0.7.0
|
||||||
go.maximumdirect.net/configkit v1.2.1
|
go.maximumdirect.net/configkit v1.4.0
|
||||||
go.maximumdirect.net/promptkit v0.23.2
|
go.maximumdirect.net/promptkit v0.25.0
|
||||||
go.yaml.in/yaml/v4 v4.0.0
|
go.yaml.in/yaml/v4 v4.0.0
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -11,14 +11,16 @@ github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiT
|
|||||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag=
|
github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag=
|
||||||
github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
go.maximumdirect.net/ckconfig v0.9.0 h1:s9Ikga4wt4K1NpLCX9bLhm5vbcm1Fgqy9yk2lmO4Sss=
|
go.maximumdirect.net/ckconfig v0.10.0 h1:BXxCaBw+N8i5DuYDOMb366PZLUg+PFU/GZsqgVgVZ+o=
|
||||||
go.maximumdirect.net/ckconfig v0.9.0/go.mod h1:yGjFVr2UzjJjiwDdMwsKehuQfvvtv7rTEOIk5NQOY00=
|
go.maximumdirect.net/ckconfig v0.10.0/go.mod h1:zZUNz/GncMcy2EMMxwRasoB3brnakV3GEPcnAsfZ+OQ=
|
||||||
go.maximumdirect.net/commandkit v0.7.0 h1:toLDGhHoVe6gBX5HWuzQ/Joz0cBqEhJXolW21m3axBk=
|
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.7.0/go.mod h1:sVp3JXKpm2YrP4Ie8Q3nWmQgwBdPN8uO+wQU72erDns=
|
||||||
go.maximumdirect.net/configkit v1.2.1 h1:f+/6WjNl6CULbMr6ZSVwi4aty9rmuDfJlvpeU7I+HZM=
|
go.maximumdirect.net/configkit v1.4.0 h1:TfOupZbQ23/ZMs+xt5lmyukCF11ekqKep8KbmFQD63o=
|
||||||
go.maximumdirect.net/configkit v1.2.1/go.mod h1:ewu6blSokUDCMovy8JBXAdXRikGmlHXAQpFghnPWRfs=
|
go.maximumdirect.net/configkit v1.4.0/go.mod h1:ewu6blSokUDCMovy8JBXAdXRikGmlHXAQpFghnPWRfs=
|
||||||
go.maximumdirect.net/promptkit v0.23.2 h1:nE+Qqqbw5GN4PHD2e5OEWUHXcYkESZm3ryZVBsKWwFQ=
|
go.maximumdirect.net/promptkit v0.24.0 h1:C6UFY8WgW10PIEuXQN2Z0qi0at5mD3/GQoPul6alYHo=
|
||||||
go.maximumdirect.net/promptkit v0.23.2/go.mod h1:vPFg76VXcffP0JBFMS2WADCHwV5FYvO2O4bvIoiDlwc=
|
go.maximumdirect.net/promptkit v0.24.0/go.mod h1:o2axdkV11KTPDgk81i2vrJ66dtcedXRhau/Ko3YSZ4A=
|
||||||
|
go.maximumdirect.net/promptkit v0.25.0 h1:vJOfxauwASllOSDceR2oypJ4NEwIh2s6F8dDexEzdM8=
|
||||||
|
go.maximumdirect.net/promptkit v0.25.0/go.mod h1:o2axdkV11KTPDgk81i2vrJ66dtcedXRhau/Ko3YSZ4A=
|
||||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
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 h1:/LG1pNO84Z4l603j/xMn69CcS5OYhMQ/f7l2LoQUGuw=
|
||||||
go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
|
go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
|
||||||
|
|||||||
@@ -38,7 +38,8 @@ func TestResourceInspectionsForwardNativeReports(t *testing.T) {
|
|||||||
extra := map[string]any{}
|
extra := map[string]any{}
|
||||||
prompt := &promptkit.PromptInspection{PromptID: "p", PromptHash: "hash", Description: &empty, Inputs: &inputs, Messages: []promptkit.PromptMessageInspection{{Role: "user", Content: "captured {{.topic}}"}}}
|
prompt := &promptkit.PromptInspection{PromptID: "p", PromptHash: "hash", Description: &empty, Inputs: &inputs, Messages: []promptkit.PromptMessageInspection{{Role: "user", Content: "captured {{.topic}}"}}}
|
||||||
profile := &promptkit.ProfileInspection{ProfileID: "p", Temperature: nil, MaxTokens: &zero, APIKeyRequired: &no, ExtraParams: &extra}
|
profile := &promptkit.ProfileInspection{ProfileID: "p", Temperature: nil, MaxTokens: &zero, APIKeyRequired: &no, ExtraParams: &extra}
|
||||||
backend := &promptkit.BackendInspection{BackendID: "b", Endpoint: "https://example.invalid", QueueCapacity: &zero, ExtraParams: &extra}
|
provider := "vllm"
|
||||||
|
backend := &promptkit.BackendInspection{BackendID: "b", Provider: &provider, ZeroCost: &no, Endpoint: "https://example.invalid", QueueCapacity: &zero, ExtraParams: &extra}
|
||||||
var selections []ckconfig.Selection
|
var selections []ckconfig.Selection
|
||||||
calls := 0
|
calls := 0
|
||||||
suite := Suite[struct{}, struct{}]{
|
suite := Suite[struct{}, struct{}]{
|
||||||
|
|||||||
109
integrations/ckprompt/schema_reporting_test.go
Normal file
109
integrations/ckprompt/schema_reporting_test.go
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
package ckprompt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"go.maximumdirect.net/ckconfig"
|
||||||
|
commandkit "go.maximumdirect.net/commandkit"
|
||||||
|
promptkit "go.maximumdirect.net/promptkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNativeSchemaAndPreparedEvidenceReports(t *testing.T) {
|
||||||
|
const fixture = `profiles:
|
||||||
|
- id: default
|
||||||
|
endpoint: https://example.invalid/v1
|
||||||
|
model: example
|
||||||
|
prompts:
|
||||||
|
- id: inline
|
||||||
|
default_profile: default
|
||||||
|
messages: [{role: user, content: hello}]
|
||||||
|
output:
|
||||||
|
format: json
|
||||||
|
validation_mode: json_schema
|
||||||
|
schema: {type: object}
|
||||||
|
repair_attempts: 0
|
||||||
|
- id: referenced
|
||||||
|
default_profile: default
|
||||||
|
messages: [{role: user, content: hello}]
|
||||||
|
output:
|
||||||
|
format: json
|
||||||
|
validation_mode: json_schema
|
||||||
|
schema_file: schema.json
|
||||||
|
repair_attempts: 0
|
||||||
|
`
|
||||||
|
engine := adapterEngineFrom(t, "schemas", fixture)
|
||||||
|
loader := func(context.Context, ckconfig.Selection, struct{}, struct{}) (*promptkit.Engine, error) {
|
||||||
|
return engine, nil
|
||||||
|
}
|
||||||
|
suite := WithRequestPreparation(FromEngine(loader), loader, nil)
|
||||||
|
app := newPromptTestApp(t, Command(suite))
|
||||||
|
for _, id := range []string{"inline", "referenced"} {
|
||||||
|
native, err := engine.InspectPrompt(t.Context(), id)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if native.OutputContract.RepairAttempts != 0 || (id == "inline" && native.OutputContract.Schema == nil) || (id == "referenced" && native.OutputContract.SchemaFile == nil) {
|
||||||
|
t.Fatalf("native output = %#v", native.OutputContract)
|
||||||
|
}
|
||||||
|
var output bytes.Buffer
|
||||||
|
result := app.Execute(t.Context(), []string{"promptkit", "show", "prompt", id, "--format=json"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||||
|
var actual any
|
||||||
|
decoder := json.NewDecoder(&output)
|
||||||
|
decoder.UseNumber()
|
||||||
|
err = decoder.Decode(&actual)
|
||||||
|
if result.Kind != commandkit.OutcomeSuccess || err != nil || !reflect.DeepEqual(actual, jsonValue(t, native)) {
|
||||||
|
t.Fatalf("report = %#v, %v, %#v", result, err, actual)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
native, err := engine.Prepare(t.Context(), promptkit.RunRequest{PromptID: "inline"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if native.MessageContentHash == "" || native.OutputContract.RepairAttempts != 0 || native.OutputContract.Schema == nil {
|
||||||
|
t.Fatalf("native prepared = %#v", native)
|
||||||
|
}
|
||||||
|
var output bytes.Buffer
|
||||||
|
outcome := app.Execute(t.Context(), []string{"promptkit", "show", "prepared", "inline", "--format=json"}, commandkit.Streams{Out: &output, Err: io.Discard})
|
||||||
|
var actual any
|
||||||
|
decoder := json.NewDecoder(&output)
|
||||||
|
decoder.UseNumber()
|
||||||
|
err = decoder.Decode(&actual)
|
||||||
|
if outcome.Kind != commandkit.OutcomeSuccess || err != nil {
|
||||||
|
t.Fatalf("prepared report = %#v, %v", outcome, err)
|
||||||
|
}
|
||||||
|
gotReport := actual.(map[string]any)
|
||||||
|
expected := jsonValue(t, native).(map[string]any)
|
||||||
|
for _, key := range []string{"message_content_hash", "output_contract", "structured_output"} {
|
||||||
|
if !reflect.DeepEqual(gotReport[key], expected[key]) {
|
||||||
|
t.Errorf("%s = %#v, want %#v", key, gotReport[key], expected[key])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPreparationBuilderForwardsReplacementRepairBudget(t *testing.T) {
|
||||||
|
engine := adapterEngine(t)
|
||||||
|
loader := func(context.Context, ckconfig.Selection, struct{}, struct{}) (*promptkit.Engine, error) {
|
||||||
|
return engine, nil
|
||||||
|
}
|
||||||
|
zero := 0
|
||||||
|
for _, budget := range []*int{nil, &zero} {
|
||||||
|
replacement := &promptkit.OutputContractInput{Format: promptkit.FormatJSON, ValidationMode: promptkit.ValidationJSON, RepairAttempts: budget}
|
||||||
|
request := promptkit.RunRequest{PromptID: "empty", Validation: replacement}
|
||||||
|
want, err := engine.Prepare(t.Context(), request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
suite := WithRequestPreparation(Suite[struct{}, struct{}]{}, loader, func(context.Context, PreparationRequest, struct{}, struct{}) (promptkit.RunRequest, error) {
|
||||||
|
return request, nil
|
||||||
|
})
|
||||||
|
got, err := suite.PrepareRequest(t.Context(), PreparationRequest{}, struct{}{}, struct{}{})
|
||||||
|
if err != nil || !reflect.DeepEqual(got.Value.OutputContract, want.OutputContract) || got.Value.MessageContentHash != want.MessageContentHash || (budget == nil && got.Value.OutputContract.RepairAttempts != 1) || (budget != nil && got.Value.OutputContract.RepairAttempts != 0) {
|
||||||
|
t.Fatalf("replacement = %#v, %v; native = %#v", got.Value, err, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
118
integrations/ckprompt/shared_load_test.go
Normal file
118
integrations/ckprompt/shared_load_test.go
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
package ckprompt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"go.maximumdirect.net/ckconfig"
|
||||||
|
commandkit "go.maximumdirect.net/commandkit"
|
||||||
|
configkit "go.maximumdirect.net/configkit"
|
||||||
|
promptkit "go.maximumdirect.net/promptkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestConfigScopeUsesNativeSharedLoadPaths(t *testing.T) {
|
||||||
|
type application struct {
|
||||||
|
Name string `yaml:"app_name"`
|
||||||
|
PromptKit promptkit.Settings `yaml:"promptkit"`
|
||||||
|
}
|
||||||
|
definition := promptkit.Configure(configkit.Definition[application]{Validate: func(_ *application, v *configkit.Validation) {
|
||||||
|
v.Warning(configkit.Keys("app_name"), "application warning")
|
||||||
|
}}, func(a *application) *promptkit.Settings { return &a.PromptKit })
|
||||||
|
source := "app_name: example\npromptkit:\n " + strings.ReplaceAll(strings.TrimSpace(adapterPrompt), "\n", "\n ") + "\n"
|
||||||
|
result, err := configkit.Load(configkit.Bytes("shared application", []byte(source)), configkit.Options[application]{Definition: definition})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
engine, err := promptkit.NewFromConfig(result, promptkit.RuntimeConfig{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
native, err := engine.InspectConfiguration()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
scope := ConfigScope(func(context.Context, ckconfig.Selection, struct{}, struct{}) (*promptkit.Engine, error) {
|
||||||
|
return engine, nil
|
||||||
|
})
|
||||||
|
app := newPromptTestApp(t, ckconfig.Command(ckconfig.Suite[struct{}, struct{}]{Scopes: []ckconfig.Scope[struct{}, struct{}]{scope}}))
|
||||||
|
run := func(args ...string) ([]string, string, string) {
|
||||||
|
t.Helper()
|
||||||
|
var out, diag bytes.Buffer
|
||||||
|
argv := append([]string{"config", "explain", "--scope=promptkit", "--format=json", "--verbose"}, args...)
|
||||||
|
outcome := app.Execute(context.Background(), argv, commandkit.Streams{Out: &out, Err: &diag})
|
||||||
|
if outcome.Kind != commandkit.OutcomeSuccess {
|
||||||
|
t.Fatalf("%v: %#v %s", args, outcome, diag.String())
|
||||||
|
}
|
||||||
|
var report struct {
|
||||||
|
Paths []struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
} `json:"paths"`
|
||||||
|
}
|
||||||
|
if args[0] == "--list" {
|
||||||
|
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var paths []string
|
||||||
|
for _, entry := range report.Paths {
|
||||||
|
paths = append(paths, entry.Path)
|
||||||
|
}
|
||||||
|
return paths, out.String(), diag.String()
|
||||||
|
}
|
||||||
|
metadata := native.Metadata()
|
||||||
|
expected := func(prefix string, explicit *bool) []string {
|
||||||
|
var paths []string
|
||||||
|
for _, path := range native.HistoricalPaths() {
|
||||||
|
info, present := metadata.Lookup(path)
|
||||||
|
if !present || (prefix != "" && !strings.HasPrefix(path.String(), prefix)) || (explicit != nil && info.Explicit != *explicit) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
paths = append(paths, path.String())
|
||||||
|
}
|
||||||
|
return paths
|
||||||
|
}
|
||||||
|
yes := true
|
||||||
|
for _, tc := range []struct {
|
||||||
|
args []string
|
||||||
|
prefix string
|
||||||
|
explicit *bool
|
||||||
|
}{
|
||||||
|
{[]string{"--list"}, "", nil}, {[]string{"--list", "--historical"}, "", nil}, {[]string{"--list", "--under=/promptkit/prompts"}, "/promptkit/prompts", nil}, {[]string{"--list", "--explicit=true"}, "", &yes},
|
||||||
|
} {
|
||||||
|
paths, _, diag := run(tc.args...)
|
||||||
|
if !reflect.DeepEqual(paths, expected(tc.prefix, tc.explicit)) || !strings.Contains(diag, "application warning") {
|
||||||
|
t.Fatalf("paths=%v want=%v diagnostics=%q", paths, expected(tc.prefix, tc.explicit), diag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, output, diag := run("--path=/app_name")
|
||||||
|
if !strings.Contains(output, "app_name") || !strings.Contains(output, "shared application") || !strings.Contains(diag, "application warning") {
|
||||||
|
t.Fatalf("output=%q diagnostics=%q", output, diag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequirementsReportsApplicationInputDefaults(t *testing.T) {
|
||||||
|
type application struct {
|
||||||
|
PromptKit promptkit.Settings `yaml:"promptkit"`
|
||||||
|
}
|
||||||
|
settings := promptkit.Settings{
|
||||||
|
Profiles: []promptkit.ProfileSettings{{ID: "default", Endpoint: new("https://example.invalid/v1"), Model: new("example")}},
|
||||||
|
Prompts: []promptkit.PromptSettings{{ID: "briefing", DefaultProfile: new("default"), Inputs: []promptkit.PromptInputSettings{{Name: "doc", Required: true, ContentType: new("text/plain"), Description: new("application default")}}, Messages: []promptkit.PromptMessageSettings{{Role: new("user"), Content: new("hello")}}, Output: &promptkit.PromptOutputSettings{Format: new("text"), ValidationMode: new("none")}}},
|
||||||
|
}
|
||||||
|
definition := promptkit.Configure(configkit.Definition[application]{Defaults: func() application { return application{PromptKit: settings} }}, func(value *application) *promptkit.Settings { return &value.PromptKit })
|
||||||
|
result, err := configkit.Load(configkit.NoSource(), configkit.Options[application]{Definition: definition})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
engine, err := promptkit.NewFromConfig(result, promptkit.RuntimeConfig{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
native, _, report, _ := executeRequirementsAgainstNative(t, engine, promptkit.RequirementInspectionRequest{PromptID: "briefing"}, []string{"promptkit", "requirements", "show", "briefing"})
|
||||||
|
if len(native.Inputs) != 1 || native.Inputs[0].ContentType == nil || *native.Inputs[0].ContentType != "text/plain" || native.Inputs[0].Description == nil || *native.Inputs[0].Description != "application default" || len(report) == 0 {
|
||||||
|
t.Fatalf("native requirements = %#v, report = %#v", native, report)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -121,7 +121,7 @@ func runSmokeTest[I, S any](invocation commandkit.Invocation, suite Suite[I, S],
|
|||||||
return definitionFailure(invocation.Context, smokeFailureMessage(input.kind), acquired.Explanation, operationErr)
|
return definitionFailure(invocation.Context, smokeFailureMessage(input.kind), acquired.Explanation, operationErr)
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = invocation.Reporter().Report(commandkit.Report{Value: smokeReportFromNative(acquired.Value)})
|
_ = invocation.Reporter().Report(commandkit.Report{Value: smokeReportFromNative(acquired.Value), TextTemplate: smokeTextTemplate})
|
||||||
if operationErr != nil {
|
if operationErr != nil {
|
||||||
return definitionFailure(invocation.Context, smokeFailureMessage(input.kind), acquired.Explanation, operationErr)
|
return definitionFailure(invocation.Context, smokeFailureMessage(input.kind), acquired.Explanation, operationErr)
|
||||||
}
|
}
|
||||||
@@ -184,7 +184,7 @@ func runSmokeAggregate[I, S any](invocation commandkit.Invocation, suite Suite[I
|
|||||||
if len(results) == 0 {
|
if len(results) == 0 {
|
||||||
return definitionFailure(invocation.Context, "PromptKit aggregate smoke testing did not produce any results.", combineSmokeExplanations(explanations), errors.Join(operationErrors...))
|
return definitionFailure(invocation.Context, "PromptKit aggregate smoke testing did not produce any results.", combineSmokeExplanations(explanations), errors.Join(operationErrors...))
|
||||||
}
|
}
|
||||||
_ = invocation.Reporter().Report(commandkit.Report{Value: smokeResultsReport(results)})
|
_ = invocation.Reporter().Report(commandkit.Report{Value: smokeResultsReport(results), TextTemplate: smokeAggregateTextTemplate})
|
||||||
if len(operationErrors) > 0 {
|
if len(operationErrors) > 0 {
|
||||||
return definitionFailure(invocation.Context, "One or more PromptKit smoke tests failed.", combineSmokeExplanations(explanations), errors.Join(operationErrors...))
|
return definitionFailure(invocation.Context, "One or more PromptKit smoke tests failed.", combineSmokeExplanations(explanations), errors.Join(operationErrors...))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
package ckprompt
|
package ckprompt
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"text/template"
|
||||||
|
|
||||||
|
commandkit "go.maximumdirect.net/commandkit"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
promptkit "go.maximumdirect.net/promptkit"
|
promptkit "go.maximumdirect.net/promptkit"
|
||||||
@@ -88,6 +92,8 @@ type smokeAttemptDTO struct {
|
|||||||
type smokeUsageDTO struct {
|
type smokeUsageDTO struct {
|
||||||
PromptTokens smokeTokenCount `json:"prompt_tokens"`
|
PromptTokens smokeTokenCount `json:"prompt_tokens"`
|
||||||
CompletionTokens smokeTokenCount `json:"completion_tokens"`
|
CompletionTokens smokeTokenCount `json:"completion_tokens"`
|
||||||
|
ReasoningTokens smokeTokenCount `json:"reasoning_tokens"`
|
||||||
|
CacheHitRatio *float64 `json:"cache_hit_ratio"`
|
||||||
TotalTokens smokeTokenCount `json:"total_tokens"`
|
TotalTokens smokeTokenCount `json:"total_tokens"`
|
||||||
CachedTokens smokeTokenCount `json:"cached_tokens"`
|
CachedTokens smokeTokenCount `json:"cached_tokens"`
|
||||||
CacheWriteTokens smokeTokenCount `json:"cache_write_tokens"`
|
CacheWriteTokens smokeTokenCount `json:"cache_write_tokens"`
|
||||||
@@ -222,11 +228,33 @@ func durationString(duration *time.Duration) *string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func smokeUsageFromNative(usage promptkit.ObservedTokenUsage) smokeUsageDTO {
|
func smokeUsageFromNative(usage promptkit.ObservedTokenUsage) smokeUsageDTO {
|
||||||
|
var ratio *float64
|
||||||
|
if value, ok := usage.CacheHitRatio(); ok {
|
||||||
|
ratio = &value
|
||||||
|
}
|
||||||
return smokeUsageDTO{
|
return smokeUsageDTO{
|
||||||
PromptTokens: smokeTokenCount(usage.PromptTokens),
|
PromptTokens: smokeTokenCount(usage.PromptTokens),
|
||||||
CompletionTokens: smokeTokenCount(usage.CompletionTokens),
|
CompletionTokens: smokeTokenCount(usage.CompletionTokens),
|
||||||
|
ReasoningTokens: smokeTokenCount(usage.ReasoningTokens),
|
||||||
|
CacheHitRatio: ratio,
|
||||||
TotalTokens: smokeTokenCount(usage.TotalTokens),
|
TotalTokens: smokeTokenCount(usage.TotalTokens),
|
||||||
CachedTokens: smokeTokenCount(usage.CachedTokens),
|
CachedTokens: smokeTokenCount(usage.CachedTokens),
|
||||||
CacheWriteTokens: smokeTokenCount(usage.CacheWriteTokens),
|
CacheWriteTokens: smokeTokenCount(usage.CacheWriteTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The text view retains the full structured evidence and adds readable ratios.
|
||||||
|
var smokeTemplateFuncs = template.FuncMap{
|
||||||
|
"smokeEvidence": func(value any) (string, error) {
|
||||||
|
var b bytes.Buffer
|
||||||
|
err := commandkit.RenderReport(&b, commandkit.Report{Value: value}, commandkit.FormatYAML)
|
||||||
|
return b.String(), err
|
||||||
|
},
|
||||||
|
"percent": func(value *float64) float64 { return *value * 100 },
|
||||||
|
}
|
||||||
|
var smokeTextTemplate = template.Must(commandkit.ParseTextTemplate("smoke", `{{smokeEvidence .}}{{with .Usage.CacheHitRatio}}# Cache hit ratio: {{printf "%.1f" (percent .)}}%
|
||||||
|
{{end}}{{range $index, $attempt := .Attempts}}{{with $attempt.Usage.CacheHitRatio}}# Attempt {{$index}} cache hit ratio: {{printf "%.1f" (percent .)}}%
|
||||||
|
{{end}}{{end}}`, smokeTemplateFuncs))
|
||||||
|
var smokeAggregateTextTemplate = template.Must(commandkit.ParseTextTemplate("smoke aggregate", `{{smokeEvidence .}}{{range .Tests}}{{with .Report}}{{with .Usage.CacheHitRatio}}# Cache hit ratio: {{printf "%.1f" (percent .)}}%
|
||||||
|
{{end}}{{range $index, $attempt := .Attempts}}{{with $attempt.Usage.CacheHitRatio}}# Attempt {{$index}} cache hit ratio: {{printf "%.1f" (percent .)}}%
|
||||||
|
{{end}}{{end}}{{end}}{{end}}`, smokeTemplateFuncs))
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
package ckprompt
|
package ckprompt
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"errors"
|
"errors"
|
||||||
|
commandkit "go.maximumdirect.net/commandkit"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"text/template"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
promptkit "go.maximumdirect.net/promptkit"
|
promptkit "go.maximumdirect.net/promptkit"
|
||||||
@@ -215,3 +219,51 @@ func containsSmokeKey(value any, want string) bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSmokeUsageReasoningAndCacheRatioRepresentations(t *testing.T) {
|
||||||
|
known := func(n int) promptkit.ObservedTokenCount {
|
||||||
|
return promptkit.ObservedTokenCount{Value: n, Known: true, Complete: true}
|
||||||
|
}
|
||||||
|
usage := promptkit.ObservedTokenUsage{PromptTokens: known(8), CachedTokens: known(1), ReasoningTokens: known(3)}
|
||||||
|
projected := smokeUsageFromNative(usage)
|
||||||
|
if projected.CacheHitRatio == nil || *projected.CacheHitRatio != 0.125 || projected.ReasoningTokens.Value != 3 {
|
||||||
|
t.Fatalf("usage=%#v", projected)
|
||||||
|
}
|
||||||
|
usage.CachedTokens = known(0)
|
||||||
|
zero := smokeUsageFromNative(usage)
|
||||||
|
if zero.CacheHitRatio == nil || *zero.CacheHitRatio != 0 {
|
||||||
|
t.Fatalf("zero ratio=%#v", zero)
|
||||||
|
}
|
||||||
|
usage.PromptTokens = promptkit.ObservedTokenCount{}
|
||||||
|
if smokeUsageFromNative(usage).CacheHitRatio != nil {
|
||||||
|
t.Fatal("unknown ratio is present")
|
||||||
|
}
|
||||||
|
report := smokeReportDTO{Kind: promptkit.SmokeTestAuthentication, Supported: true, Usage: projected, Attempts: []smokeAttemptDTO{{Usage: zero}}}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
value any
|
||||||
|
tmpl *template.Template
|
||||||
|
}{
|
||||||
|
{"single", report, smokeTextTemplate},
|
||||||
|
{"aggregate", smokeAggregateDTO{Tests: []smokeResultDTO{{Kind: promptkit.SmokeTestAuthentication, Report: &report}}}, smokeAggregateTextTemplate},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
for _, format := range []commandkit.Format{commandkit.FormatText, commandkit.FormatYAML, commandkit.FormatJSON} {
|
||||||
|
var out bytes.Buffer
|
||||||
|
if err := commandkit.RenderReport(&out, commandkit.Report{Value: tc.value, TextTemplate: tc.tmpl}, format); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
text := out.String()
|
||||||
|
if !strings.Contains(text, "reasoning_tokens") || !strings.Contains(text, "cache_hit_ratio") || !strings.Contains(text, "attempts") || !strings.Contains(text, "supported") {
|
||||||
|
t.Fatalf("missing evidence: %s", text)
|
||||||
|
}
|
||||||
|
if format == commandkit.FormatText && (!strings.Contains(text, "12.5%") || !strings.Contains(text, "0.0%")) {
|
||||||
|
t.Fatalf("ratios: %s", text)
|
||||||
|
}
|
||||||
|
if format != commandkit.FormatText && !strings.Contains(text, "0.125") {
|
||||||
|
t.Fatalf("raw ratio: %s", text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
83
integrations/ckprompt/usage_report.go
Normal file
83
integrations/ckprompt/usage_report.go
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package ckprompt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"text/template"
|
||||||
|
|
||||||
|
commandkit "go.maximumdirect.net/commandkit"
|
||||||
|
promptkit "go.maximumdirect.net/promptkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
type usageInput struct{ ShowTokens bool }
|
||||||
|
|
||||||
|
type usageSummary struct {
|
||||||
|
Prompts int
|
||||||
|
RepairCalls uint64
|
||||||
|
CoverageComplete bool
|
||||||
|
Usage promptkit.ObservedTokenUsage
|
||||||
|
Cost promptkit.ObservedCost
|
||||||
|
CacheHitRatio *float64
|
||||||
|
Smoke bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func usageFeature() commandkit.InvocationFeature {
|
||||||
|
return commandkit.NewInvocationFeature(commandkit.InvocationFeatureSpec[usageInput]{
|
||||||
|
Flags: []commandkit.Flag[usageInput]{commandkit.BoolFlag(commandkit.FlagMeta{Name: "show-tokens", Usage: "Show token usage and available cost information after execution."}, false, func(i *usageInput, v commandkit.Supplied[bool]) { i.ShowTokens = v.Value })},
|
||||||
|
Start: func(inv commandkit.Invocation, input usageInput) (context.Context, func() commandkit.Report) {
|
||||||
|
if !input.ShowTokens {
|
||||||
|
return inv.Context, nil
|
||||||
|
}
|
||||||
|
group := new(promptkit.ExecutionGroup)
|
||||||
|
ctx := promptkit.WithExecutionObserver(inv.Context, group.Observe)
|
||||||
|
smoke := inv.CanonicalPath() == "promptkit test"
|
||||||
|
return ctx, func() commandkit.Report { return usageReport(group.Snapshot(), smoke) }
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func usageReport(summary promptkit.ExecutionGroupSummary, smoke bool) commandkit.Report {
|
||||||
|
value := usageSummary{Prompts: len(summary.Members), RepairCalls: summary.RepairCalls, CoverageComplete: summary.TerminalCoverageComplete, Usage: summary.Usage, Cost: summary.CostUSD, Smoke: smoke}
|
||||||
|
if ratio, ok := summary.Usage.CacheHitRatio(); ok {
|
||||||
|
value.CacheHitRatio = &ratio
|
||||||
|
}
|
||||||
|
return commandkit.Report{Value: value, TextTemplate: usageTextTemplate}
|
||||||
|
}
|
||||||
|
|
||||||
|
func usageCount(count promptkit.ObservedTokenCount) string {
|
||||||
|
if !count.Known {
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
if !count.Complete {
|
||||||
|
return fmt.Sprintf("%d (incomplete)", count.Value)
|
||||||
|
}
|
||||||
|
return fmt.Sprint(count.Value)
|
||||||
|
}
|
||||||
|
func usageCost(cost promptkit.ObservedCost) string {
|
||||||
|
if !cost.Known {
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
result := fmt.Sprintf("USD %.6g", cost.Value)
|
||||||
|
if !cost.Complete {
|
||||||
|
result += " (incomplete subtotal)"
|
||||||
|
}
|
||||||
|
if cost.Source != "" {
|
||||||
|
result += fmt.Sprintf(" [%s]", cost.Source)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
var usageTextTemplate = template.Must(commandkit.ParseTextTemplate("observed usage", `Observed PromptKit execution usage
|
||||||
|
Prompts: {{.Prompts}}
|
||||||
|
{{if .RepairCalls}} Repair calls: {{.RepairCalls}}
|
||||||
|
{{end}}Prompt tokens: {{count .Usage.PromptTokens}}
|
||||||
|
Completion tokens: {{count .Usage.CompletionTokens}}
|
||||||
|
Reasoning tokens: {{count .Usage.ReasoningTokens}}
|
||||||
|
Total tokens: {{count .Usage.TotalTokens}}
|
||||||
|
Cached tokens: {{count .Usage.CachedTokens}}
|
||||||
|
Cache-write tokens: {{count .Usage.CacheWriteTokens}}
|
||||||
|
{{with .CacheHitRatio}}Cache hit ratio: {{printf "%.1f" (percent .)}}%
|
||||||
|
{{end}}Cost: {{cost .Cost}}
|
||||||
|
Terminal coverage: {{if .CoverageComplete}}complete{{else}}incomplete{{end}}
|
||||||
|
{{if .Smoke}}Smoke-test usage is reported separately in the command report.
|
||||||
|
{{end}}`, template.FuncMap{"count": usageCount, "cost": usageCost, "percent": func(value *float64) float64 { return *value * 100 }}))
|
||||||
47
integrations/ckprompt/usage_report_test.go
Normal file
47
integrations/ckprompt/usage_report_test.go
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package ckprompt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
commandkit "go.maximumdirect.net/commandkit"
|
||||||
|
promptkit "go.maximumdirect.net/promptkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUsageSummaryPreservesNativeEvidence(t *testing.T) {
|
||||||
|
count := func(n int, known, complete bool) promptkit.ObservedTokenCount {
|
||||||
|
return promptkit.ObservedTokenCount{Value: n, Known: known, Complete: complete}
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
summary promptkit.ExecutionGroupSummary
|
||||||
|
smoke bool
|
||||||
|
want []string
|
||||||
|
absent []string
|
||||||
|
}{
|
||||||
|
{name: "empty", summary: new(promptkit.ExecutionGroup).Snapshot(), want: []string{"Prompts: 0", "Prompt tokens: 0", "Cost: USD 0", "Terminal coverage: complete"}, absent: []string{"Repair calls:", "Cache hit ratio:", "[provider]"}},
|
||||||
|
{name: "unknown", summary: promptkit.ExecutionGroupSummary{Members: []promptkit.ExecutionGroupMember{{RunID: "a"}}}, smoke: true, want: []string{"Prompts: 1", "Prompt tokens: unknown", "Cost: unknown", "Terminal coverage: incomplete", "Smoke-test usage is reported separately"}},
|
||||||
|
{name: "known", summary: promptkit.ExecutionGroupSummary{Members: []promptkit.ExecutionGroupMember{{}, {}}, TerminalCoverageComplete: true, RepairCalls: 2, Usage: promptkit.ObservedTokenUsage{PromptTokens: count(8, true, true), CompletionTokens: count(9, true, false), ReasoningTokens: count(0, true, true), CachedTokens: count(1, true, true)}, CostUSD: promptkit.ObservedCost{Value: 0.012345678, Known: true, Source: promptkit.CostSource("mixed")}}, want: []string{"Prompts: 2", "Repair calls: 2", "Completion tokens: 9 (incomplete)", "Reasoning tokens: 0", "Cache hit ratio: 12.5%", "Cost: USD 0.0123457 (incomplete subtotal) [mixed]"}},
|
||||||
|
{name: "configured zero", summary: promptkit.ExecutionGroupSummary{CostUSD: promptkit.ObservedCost{Known: true, Complete: true, Source: promptkit.CostSource("configured_zero")}}, want: []string{"Cost: USD 0 [configured_zero]"}},
|
||||||
|
{name: "provider zero", summary: promptkit.ExecutionGroupSummary{CostUSD: promptkit.ObservedCost{Known: true, Complete: true, Source: promptkit.CostSource("provider")}}, want: []string{"Cost: USD 0 [provider]"}},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
report := usageReport(tc.summary, tc.smoke)
|
||||||
|
var out bytes.Buffer
|
||||||
|
if err := commandkit.RenderReport(&out, report, commandkit.FormatText); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, want := range tc.want {
|
||||||
|
if !strings.Contains(out.String(), want) {
|
||||||
|
t.Errorf("missing %q in %q", want, out.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, absent := range tc.absent {
|
||||||
|
if strings.Contains(out.String(), absent) {
|
||||||
|
t.Errorf("unexpected %q in %q", absent, out.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -37,6 +37,9 @@ func validationTestEngine(t *testing.T, configuration string, options ...promptk
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
for index := range inputs {
|
||||||
|
inputs[index].Destination = configkit.Keys("promptkit")
|
||||||
|
}
|
||||||
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{
|
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{
|
||||||
Underlays: []configkit.Underlay{{Inputs: inputs}},
|
Underlays: []configkit.Underlay{{Inputs: inputs}},
|
||||||
}}, append([]promptkit.Option{promptkit.WithBundledOpenRouter(false)}, options...)...)
|
}}, append([]promptkit.Option{promptkit.WithBundledOpenRouter(false)}, options...)...)
|
||||||
|
|||||||
40
integrations/ckprompt/vllm_evidence_test.go
Normal file
40
integrations/ckprompt/vllm_evidence_test.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package ckprompt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"go.maximumdirect.net/ckconfig"
|
||||||
|
commandkit "go.maximumdirect.net/commandkit"
|
||||||
|
"go.maximumdirect.net/configkit"
|
||||||
|
promptkit "go.maximumdirect.net/promptkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
type smokeTransport func(*http.Request) (*http.Response, error)
|
||||||
|
|
||||||
|
func (f smokeTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||||
|
|
||||||
|
func TestVLLMAuthenticationEvidenceFlowsThroughCommand(t *testing.T) {
|
||||||
|
source := configkit.Input{Destination: configkit.Keys("promptkit"), Source: configkit.Mapping("fixture", map[string]any{"backends": []any{map[string]any{"id": "local", "provider": "vllm", "endpoint": "https://example.invalid/v1", "zero_cost": false}}})}
|
||||||
|
client := &http.Client{Transport: smokeTransport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"object":"list","data":[]}`)), Request: r}, nil
|
||||||
|
})}
|
||||||
|
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Main: &source}, HTTPClient: client}, promptkit.WithBundledOpenRouter(false))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
loader := func(context.Context, ckconfig.Selection, struct{}, struct{}) (*promptkit.Engine, error) {
|
||||||
|
return engine, nil
|
||||||
|
}
|
||||||
|
suite := WithSmokeTesting(FromEngine(loader), loader, nil)
|
||||||
|
app := newPromptTestApp(t, Command(suite))
|
||||||
|
var out bytes.Buffer
|
||||||
|
result := app.Execute(context.Background(), []string{"promptkit", "test", "authentication", "--llm-backend=local", "--format=json"}, commandkit.Streams{Out: &out})
|
||||||
|
if result.Status != 0 || !strings.Contains(out.String(), `"supported": true`) || !strings.Contains(out.String(), `"applicable": true`) || !strings.Contains(out.String(), `"credentials_accepted": true`) {
|
||||||
|
t.Fatalf("outcome=%#v report=%s", result, out.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -77,7 +77,7 @@ func (session *Session) Parse(argv []string) commandmeta.Result {
|
|||||||
}
|
}
|
||||||
|
|
||||||
remaining := append(commandpath.CloneTokens(unconsumed), tail...)
|
remaining := append(commandpath.CloneTokens(unconsumed), tail...)
|
||||||
localFlags := commandmeta.EffectiveFlags(selectedNode.Flags, selectedNode.CoreFlags)
|
localFlags := commandmeta.EffectiveFlags(append(append([]commandmeta.Flag(nil), selectedNode.Flags...), selectedNode.InvocationFlags...), selectedNode.CoreFlags)
|
||||||
aliases := session.flagAliases
|
aliases := session.flagAliases
|
||||||
if session.flagAliasesForPath != nil {
|
if session.flagAliasesForPath != nil {
|
||||||
aliases = session.flagAliasesForPath(result.Path)
|
aliases = session.flagAliasesForPath(result.Path)
|
||||||
@@ -115,6 +115,15 @@ func (session *Session) Parse(argv []string) commandmeta.Result {
|
|||||||
result.FlagSpellings[index] = raw.spellingsCopy()
|
result.FlagSpellings[index] = raw.spellingsCopy()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
result.InvocationFlagValues = make([][]string, len(selectedNode.InvocationFlags))
|
||||||
|
result.InvocationFlagSpellings = make([][]string, len(selectedNode.InvocationFlags))
|
||||||
|
for index, flag := range selectedNode.InvocationFlags {
|
||||||
|
if value := selected.Flags().Lookup(flag.Name); value != nil {
|
||||||
|
raw := value.Value.(*rawValue)
|
||||||
|
result.InvocationFlagValues[index] = raw.valuesCopy()
|
||||||
|
result.InvocationFlagSpellings[index] = raw.spellingsCopy()
|
||||||
|
}
|
||||||
|
}
|
||||||
if helpFlag := selected.Flags().Lookup("help"); helpFlag != nil {
|
if helpFlag := selected.Flags().Lookup("help"); helpFlag != nil {
|
||||||
helpRequested, err := helpFlag.Value.(*rawValue).lastBool()
|
helpRequested, err := helpFlag.Value.(*rawValue).lastBool()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -271,7 +280,7 @@ func (session *Session) UsageLine(path []string) (string, *commandmeta.Failure)
|
|||||||
if flag.Name != "debug" || !flag.Boolean {
|
if flag.Name != "debug" || !flag.Boolean {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for _, effective := range commandmeta.EffectiveFlags(declaration.Flags, declaration.CoreFlags) {
|
for _, effective := range commandmeta.EffectiveFlags(append(append([]commandmeta.Flag(nil), declaration.Flags...), declaration.InvocationFlags...), declaration.CoreFlags) {
|
||||||
if effective.Name == "debug" {
|
if effective.Name == "debug" {
|
||||||
spelling := "--debug"
|
spelling := "--debug"
|
||||||
if effective.Short != "" {
|
if effective.Short != "" {
|
||||||
@@ -330,7 +339,7 @@ func buildTree(root *commandmeta.Command) (*spfcobra.Command, map[*spfcobra.Comm
|
|||||||
helpFlag := backend.Flags().Lookup("help")
|
helpFlag := backend.Flags().Lookup("help")
|
||||||
helpFlag.NoOptDefVal = "true"
|
helpFlag.NoOptDefVal = "true"
|
||||||
helpFlag.Usage = "help for this command (default: false)"
|
helpFlag.Usage = "help for this command (default: false)"
|
||||||
for _, declarationFlag := range commandmeta.EffectiveFlags(declaration.Flags, declaration.CoreFlags) {
|
for _, declarationFlag := range commandmeta.EffectiveFlags(append(append([]commandmeta.Flag(nil), declaration.Flags...), declaration.InvocationFlags...), declaration.CoreFlags) {
|
||||||
value := &rawValue{boolean: declarationFlag.Boolean}
|
value := &rawValue{boolean: declarationFlag.Boolean}
|
||||||
backend.Flags().VarP(value, declarationFlag.Name, declarationFlag.Short, flagUsage(declarationFlag))
|
backend.Flags().VarP(value, declarationFlag.Name, declarationFlag.Short, flagUsage(declarationFlag))
|
||||||
backendFlag := backend.Flags().Lookup(declarationFlag.Name)
|
backendFlag := backend.Flags().Lookup(declarationFlag.Name)
|
||||||
|
|||||||
@@ -16,9 +16,10 @@ type Command struct {
|
|||||||
Runnable bool
|
Runnable bool
|
||||||
Flags []Flag
|
Flags []Flag
|
||||||
// CoreFlags are parsed by CommandKit but do not occupy consumer binding indexes.
|
// CoreFlags are parsed by CommandKit but do not occupy consumer binding indexes.
|
||||||
CoreFlags []Flag
|
CoreFlags []Flag
|
||||||
Arguments []Argument
|
InvocationFlags []Flag
|
||||||
Children []*Command
|
Arguments []Argument
|
||||||
|
Children []*Command
|
||||||
}
|
}
|
||||||
|
|
||||||
// Argument describes one positional input for usage rendering.
|
// Argument describes one positional input for usage rendering.
|
||||||
@@ -196,15 +197,17 @@ type ReportingSelection struct {
|
|||||||
|
|
||||||
// Result contains the selected command and raw input collected by the adapter.
|
// Result contains the selected command and raw input collected by the adapter.
|
||||||
type Result struct {
|
type Result struct {
|
||||||
Key Key
|
Key Key
|
||||||
Path []string
|
Path []string
|
||||||
HelpRequested bool
|
HelpRequested bool
|
||||||
FlagValues [][]string
|
FlagValues [][]string
|
||||||
FlagSpellings [][]string
|
FlagSpellings [][]string
|
||||||
FlagOccurrences []FlagOccurrence
|
InvocationFlagValues [][]string
|
||||||
Reporting ReportingSelection
|
InvocationFlagSpellings [][]string
|
||||||
Operands []string
|
FlagOccurrences []FlagOccurrence
|
||||||
Failure *Failure
|
Reporting ReportingSelection
|
||||||
|
Operands []string
|
||||||
|
Failure *Failure
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseOptions selects flag aliases for parser contexts.
|
// ParseOptions selects flag aliases for parser contexts.
|
||||||
|
|||||||
98
invocation_feature.go
Normal file
98
invocation_feature.go
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
package commandkit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"go.maximumdirect.net/commandkit/internal/commandmeta"
|
||||||
|
)
|
||||||
|
|
||||||
|
// InvocationFeature is a captured, reusable invocation-wide capability.
|
||||||
|
// Attach it to an installed command with WithInvocationFeature.
|
||||||
|
type InvocationFeature struct{ record *invocationFeatureRecord }
|
||||||
|
|
||||||
|
// InvocationFeatureSpec declares invocation flags and a report producer.
|
||||||
|
// NewInput creates fresh input for each invocation; nil uses the zero value.
|
||||||
|
// Start receives the current invocation and may return a replacement context
|
||||||
|
// and a function producing a report at invocation finalization. Start is required.
|
||||||
|
// Features start in installation traversal order after command input construction
|
||||||
|
// and successful CheckInput; each receives the context returned by its predecessor.
|
||||||
|
// A nil context leaves it unchanged and a nil report function produces no report.
|
||||||
|
// Report functions run once after deferred messages and before terminal explanations,
|
||||||
|
// even after a returned failure or cancellation. Reports render as text on
|
||||||
|
// diagnostics, with quiet suppressing delivery. Generated help, version and
|
||||||
|
// completion, and preflight failures do not start features.
|
||||||
|
type InvocationFeatureSpec[I any] struct {
|
||||||
|
NewInput func() I
|
||||||
|
Flags []Flag[I]
|
||||||
|
Start func(Invocation, I) (context.Context, func() Report)
|
||||||
|
}
|
||||||
|
|
||||||
|
type invocationFeaturePayload interface {
|
||||||
|
bridgeFlags() []commandmeta.Flag
|
||||||
|
requiredError([][]string) error
|
||||||
|
prepare([][]string, [][]string, []commandmeta.FlagOccurrence, bool) (func(Invocation) (context.Context, func() Report), error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type typedInvocationFeature[I any] struct{ spec InvocationFeatureSpec[I] }
|
||||||
|
|
||||||
|
func (f typedInvocationFeature[I]) bridgeFlags() []commandmeta.Flag {
|
||||||
|
return (typedCommand[I]{spec: CommandSpec[I]{Flags: f.spec.Flags}}).bridgeFlags()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f typedInvocationFeature[I]) requiredError(values [][]string) error {
|
||||||
|
for i, flag := range f.spec.Flags {
|
||||||
|
if flag.binding.meta.Required && !flag.binding.deferredRequired && len(values[i]) == 0 {
|
||||||
|
return fmt.Errorf("required flag --%s was not supplied", flag.binding.meta.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f typedInvocationFeature[I]) prepare(values, spellings [][]string, occurrences []commandmeta.FlagOccurrence, required bool) (func(Invocation) (context.Context, func() Report), error) {
|
||||||
|
input, err := prepareInputWithOccurrences(CommandSpec[I]{NewInput: f.spec.NewInput, Flags: f.spec.Flags}, values, spellings, occurrences, nil, required)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return func(inv Invocation) (context.Context, func() Report) { return f.spec.Start(inv, input.build()) }, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type invocationFeatureRecord struct {
|
||||||
|
payload invocationFeaturePayload
|
||||||
|
issues []error
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewInvocationFeature captures flag declarations and callbacks without invoking
|
||||||
|
// them. Construction errors are reported when an attached command is installed.
|
||||||
|
func NewInvocationFeature[I any](spec InvocationFeatureSpec[I]) InvocationFeature {
|
||||||
|
spec.Flags = append([]Flag[I](nil), spec.Flags...)
|
||||||
|
record := &invocationFeatureRecord{payload: typedInvocationFeature[I]{spec: spec}}
|
||||||
|
if err := validateBindings(spec.Flags, nil); err != nil {
|
||||||
|
record.issues = append(record.issues, err)
|
||||||
|
}
|
||||||
|
for _, flag := range spec.Flags {
|
||||||
|
if commandmeta.IsReportingFlag(flag.binding.meta.Name) {
|
||||||
|
record.issues = append(record.issues, fmt.Errorf("feature flag name %q is reserved for reporting", flag.binding.meta.Name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if spec.Start == nil {
|
||||||
|
record.issues = append(record.issues, fmt.Errorf("invocation feature requires Start"))
|
||||||
|
}
|
||||||
|
return InvocationFeature{record: record}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithInvocationFeature returns a copy of command with feature attached. When
|
||||||
|
// installed, the feature applies to the application, not only this command.
|
||||||
|
// Reusing the same feature in one application installs it once. An absent
|
||||||
|
// command contributes no feature, but attached errors are still reported.
|
||||||
|
func WithInvocationFeature(command Command, feature InvocationFeature) Command {
|
||||||
|
var record commandRecord
|
||||||
|
if command.record == nil {
|
||||||
|
record.invalid = true
|
||||||
|
record.issues = append(record.issues, fmt.Errorf("invalid zero command declaration"))
|
||||||
|
} else {
|
||||||
|
record = *command.record
|
||||||
|
}
|
||||||
|
record.features = append(append([]InvocationFeature(nil), record.features...), feature)
|
||||||
|
return Command{record: &record}
|
||||||
|
}
|
||||||
137
invocation_feature_external_test.go
Normal file
137
invocation_feature_external_test.go
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
package commandkit_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
ck "go.maximumdirect.net/commandkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
type observationKey struct{}
|
||||||
|
type observationInput struct{ enabled bool }
|
||||||
|
|
||||||
|
func observationFeature() ck.InvocationFeature {
|
||||||
|
return ck.NewInvocationFeature(ck.InvocationFeatureSpec[observationInput]{Flags: []ck.Flag[observationInput]{ck.BoolFlag(ck.FlagMeta{Name: "observe", Short: "o"}, false, func(i *observationInput, v ck.Supplied[bool]) { i.enabled = v.Value })}, Start: func(inv ck.Invocation, i observationInput) (context.Context, func() ck.Report) {
|
||||||
|
if !i.enabled {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return context.WithValue(inv.Context, observationKey{}, true), func() ck.Report { return ck.Report{Value: "observed"} }
|
||||||
|
}})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvocationFeaturePublicAssembly(t *testing.T) {
|
||||||
|
feature := observationFeature()
|
||||||
|
var contexts []bool
|
||||||
|
cmd := ck.NewCommand(ck.CommandSpec[struct{}]{Name: "run", Run: func(inv ck.Invocation, _ struct{}) ck.Outcome {
|
||||||
|
contexts = append(contexts, inv.Context.Value(observationKey{}) == true)
|
||||||
|
_ = inv.Reporter().Report(ck.Report{Value: map[string]string{"result": "ok"}})
|
||||||
|
return ck.Success()
|
||||||
|
}})
|
||||||
|
owner := ck.WithInvocationFeature(ck.Group("feature", ""), feature)
|
||||||
|
for _, featureFirst := range []bool{true, false} {
|
||||||
|
var first, second ck.Declaration = owner, cmd
|
||||||
|
if !featureFirst {
|
||||||
|
first, second = second, first
|
||||||
|
}
|
||||||
|
app, err := ck.New(ck.Identity{Name: "test"}, first)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := app.Register(second, ck.Alias("execute", "run"), ck.FlagAlias("--watch", "--observe")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
args []string
|
||||||
|
summary bool
|
||||||
|
}{{[]string{"execute", "--watch", "--format=json"}, true}, {[]string{"run", "--observe=false"}, false}, {[]string{"run", "--observe", "--quiet"}, false}, {[]string{"run", "--quiet", "--observe"}, false}} {
|
||||||
|
var out, diag bytes.Buffer
|
||||||
|
result := app.Execute(context.Background(), tc.args, ck.Streams{Out: &out, Err: &diag})
|
||||||
|
if result.Status != 0 || strings.Contains(diag.String(), "observed") != tc.summary {
|
||||||
|
t.Fatalf("args %v: %#v %q", tc.args, result, diag.String())
|
||||||
|
}
|
||||||
|
if tc.summary && !strings.Contains(out.String(), `"result": "ok"`) {
|
||||||
|
t.Fatalf("main output %q", out.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
conflict := ck.NewCommand(ck.CommandSpec[struct{}]{Name: "conflict", Flags: []ck.Flag[struct{}]{ck.BoolFlag(ck.FlagMeta{Name: "observe"}, false, func(*struct{}, ck.Supplied[bool]) {})}})
|
||||||
|
if app.Register(conflict) == nil {
|
||||||
|
t.Fatal("expected collision")
|
||||||
|
}
|
||||||
|
var diag bytes.Buffer
|
||||||
|
if app.Execute(context.Background(), []string{"execute", "--watch"}, ck.Streams{Err: &diag}).Status != 0 || !strings.Contains(diag.String(), "observed") {
|
||||||
|
t.Fatal("failed registration changed prior routing")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other, err := ck.New(ck.Identity{Name: "test"}, owner, cmd)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var diag bytes.Buffer
|
||||||
|
other.Execute(context.Background(), []string{"run", "--observe"}, ck.Streams{Err: &diag})
|
||||||
|
if !strings.Contains(diag.String(), "observed") {
|
||||||
|
t.Fatal("feature unavailable in reused app")
|
||||||
|
}
|
||||||
|
plain, err := ck.New(ck.Identity{Name: "test"}, cmd)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result := plain.Execute(context.Background(), []string{"run", "--observe"}, ck.Streams{}); result.Kind != ck.OutcomeUsage {
|
||||||
|
t.Fatalf("flag present without feature: %#v", result)
|
||||||
|
}
|
||||||
|
if len(contexts) != 11 || !contexts[0] || contexts[1] || !contexts[2] {
|
||||||
|
t.Fatalf("invocation isolation: %v", contexts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvocationFeaturePublicFailureAndRollback(t *testing.T) {
|
||||||
|
cause := errors.New("canceled")
|
||||||
|
feature := observationFeature()
|
||||||
|
existing := ck.NewCommand(ck.CommandSpec[struct{}]{Name: "taken", Flags: []ck.Flag[struct{}]{ck.BoolFlag(ck.FlagMeta{Name: "observe"}, false, func(*struct{}, ck.Supplied[bool]) {})}, Run: func(ck.Invocation, struct{}) ck.Outcome { return ck.Success() }})
|
||||||
|
app, err := ck.New(ck.Identity{Name: "test"}, existing)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := app.Register(ck.WithInvocationFeature(ck.Group("feature", ""), feature)); err == nil {
|
||||||
|
t.Fatal("expected collision")
|
||||||
|
}
|
||||||
|
if app.Execute(context.Background(), []string{"taken", "--observe"}, ck.Streams{}).Status != 0 {
|
||||||
|
t.Fatal("failed registration changed existing command")
|
||||||
|
}
|
||||||
|
reject := false
|
||||||
|
run := ck.WithInvocationFeature(ck.NewCommand(ck.CommandSpec[struct{}]{Name: "run", CheckInput: func(struct{}) error {
|
||||||
|
if reject {
|
||||||
|
return errors.New("reject")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}, Run: func(inv ck.Invocation, _ struct{}) ck.Outcome {
|
||||||
|
_ = inv.Reporter().AtEnd().Warn("deferred")
|
||||||
|
return ck.Domain("canceled", 9).WithCause(cause).WithExplanation("stopped")
|
||||||
|
}}), feature)
|
||||||
|
app, err = ck.New(ck.Identity{Name: "test"}, run)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, mode := range []string{"", "--verbose", "--debug"} {
|
||||||
|
args := []string{"run", "--observe"}
|
||||||
|
if mode != "" {
|
||||||
|
args = append(args, mode)
|
||||||
|
}
|
||||||
|
var diag bytes.Buffer
|
||||||
|
out := app.Execute(context.Background(), args, ck.Streams{Err: &diag})
|
||||||
|
if out.Kind != ck.OutcomeDomain || out.Status != 9 || !errors.Is(out.Cause, cause) || !strings.Contains(diag.String(), "observed\nERROR: stopped") {
|
||||||
|
t.Fatalf("%v: %#v %q", args, out, diag.String())
|
||||||
|
}
|
||||||
|
if mode != "" && strings.Index(diag.String(), "deferred") > strings.Index(diag.String(), "observed") {
|
||||||
|
t.Fatalf("order %q", diag.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reject = true
|
||||||
|
var diag bytes.Buffer
|
||||||
|
app.Execute(context.Background(), []string{"run", "--observe"}, ck.Streams{Err: &diag})
|
||||||
|
if strings.Contains(diag.String(), "observed") {
|
||||||
|
t.Fatal("report after rejected input")
|
||||||
|
}
|
||||||
|
}
|
||||||
383
invocation_feature_test.go
Normal file
383
invocation_feature_test.go
Normal file
@@ -0,0 +1,383 @@
|
|||||||
|
package commandkit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"text/template"
|
||||||
|
|
||||||
|
internalcobra "go.maximumdirect.net/commandkit/internal/cobra"
|
||||||
|
commandmeta "go.maximumdirect.net/commandkit/internal/commandmeta"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInvocationFeatureCaptureAndInstallation(t *testing.T) {
|
||||||
|
type input struct{ enabled bool }
|
||||||
|
flags := []Flag[input]{BoolFlag(FlagMeta{Name: "observe", Short: "o"}, false, func(i *input, v Supplied[bool]) { i.enabled = v.Value })}
|
||||||
|
feature := NewInvocationFeature(InvocationFeatureSpec[input]{Flags: flags, Start: func(inv Invocation, _ input) (context.Context, func() Report) { return inv.Context, nil }})
|
||||||
|
flags[0] = BoolFlag(FlagMeta{Name: "changed"}, false, func(*input, Supplied[bool]) {})
|
||||||
|
original := Group("owner", "", Group("child", ""))
|
||||||
|
attached := WithInvocationFeature(original, feature)
|
||||||
|
first, err := New(Identity{Name: "test"}, attached, Group("other", ""), FlagAlias("--watch", "--observe"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
second, err := New(Identity{Name: "test"}, attached)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(first.features) != 1 || len(second.features) != 1 || first.features[0] != second.features[0] || first.featureFlags[0].Name != "observe" {
|
||||||
|
t.Fatal("feature capture or reuse failed")
|
||||||
|
}
|
||||||
|
if len(original.record.features) != 0 {
|
||||||
|
t.Fatal("attachment mutated original")
|
||||||
|
}
|
||||||
|
if _, ok := first.flagAliases[""].bySpelling[flagSpellingKey(capturedFlagSpelling{name: "watch"})]; !ok {
|
||||||
|
t.Fatal("feature alias missing")
|
||||||
|
}
|
||||||
|
if err := first.Register(WithInvocationFeature(Group("reused", ""), feature)); err != nil || len(first.features) != 1 {
|
||||||
|
t.Fatalf("deduplication: %v", err)
|
||||||
|
}
|
||||||
|
if err := first.Register(Group("collision", "", NewCommand(CommandSpec[struct{}]{Name: "nested", Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "observe"}, false, func(*struct{}, Supplied[bool]) {})}}))); err == nil {
|
||||||
|
t.Fatal("expected local collision")
|
||||||
|
}
|
||||||
|
if first.commands["collision"] != nil || len(first.features) != 1 {
|
||||||
|
t.Fatal("failed registration mutated registry")
|
||||||
|
}
|
||||||
|
if err := second.Register(WithInvocationFeature(Group("another", ""), NewInvocationFeature(InvocationFeatureSpec[input]{Flags: flags, Start: func(inv Invocation, _ input) (context.Context, func() Report) { return inv.Context, nil }}))); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := second.Register(WithInvocationFeature(Group("duplicate", ""), NewInvocationFeature(InvocationFeatureSpec[input]{Flags: []Flag[input]{BoolFlag(FlagMeta{Name: "observe"}, false, func(*input, Supplied[bool]) {})}, Start: func(inv Invocation, _ input) (context.Context, func() Report) { return inv.Context, nil }}))); err == nil {
|
||||||
|
t.Fatal("expected feature collision")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvocationFeatureInvalidAndAbsent(t *testing.T) {
|
||||||
|
marker := errors.New("wiring")
|
||||||
|
invalid := NewInvocationFeature(InvocationFeatureSpec[struct{}]{})
|
||||||
|
for _, command := range []Command{WithInvocationFeature(NoCommand(), invalid), WithInvocationFeature(Group("x", ""), InvocationFeature{}), WithInvocationFeature(Command{}, NewInvocationFeature(InvocationFeatureSpec[struct{}]{Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { return inv.Context, nil }})), WithError(WithInvocationFeature(NoCommand(), invalid), marker)} {
|
||||||
|
_, err := New(Identity{Name: "test"}, command)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("invalid feature accepted")
|
||||||
|
}
|
||||||
|
if len(command.record.issues) > 0 && errors.Is(command.record.issues[0], marker) && !errors.Is(err, marker) {
|
||||||
|
t.Fatalf("lost attached error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
feature := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { return inv.Context, nil }})
|
||||||
|
app, err := New(Identity{Name: "test"}, WithInvocationFeature(NoCommand(), feature))
|
||||||
|
if err != nil || len(app.features) != 0 {
|
||||||
|
t.Fatalf("absent feature: %v", err)
|
||||||
|
}
|
||||||
|
bad := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "debug"}, false, func(*struct{}, Supplied[bool]) {})}, Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { return inv.Context, nil }})
|
||||||
|
if _, err = New(Identity{Name: "test"}, WithInvocationFeature(Group("x", ""), bad)); err == nil || !strings.Contains(err.Error(), "reserved") {
|
||||||
|
t.Fatalf("reporting collision: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvocationFeatureRegistrationOrderAndAliasCollision(t *testing.T) {
|
||||||
|
feature := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "observe", Short: "o"}, false, func(*struct{}, Supplied[bool]) {})}, Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { return inv.Context, nil }})
|
||||||
|
owner := WithInvocationFeature(Group("owner", ""), feature)
|
||||||
|
collision := NewCommand(CommandSpec[struct{}]{Name: "local", Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "other", Short: "o"}, false, func(*struct{}, Supplied[bool]) {})}})
|
||||||
|
for _, pair := range [][2]Command{{owner, collision}, {collision, owner}} {
|
||||||
|
app, err := New(Identity{Name: "test"}, pair[0])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
old := app.buildRoutingSnapshot()
|
||||||
|
if err := app.Register(pair[1]); err == nil {
|
||||||
|
t.Fatal("expected collision")
|
||||||
|
}
|
||||||
|
if app.commands[pair[1].record.name] != nil || len(app.features) != len(old.features) {
|
||||||
|
t.Fatal("registration was not atomic")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := New(Identity{Name: "test"}, owner, FlagAlias("--observe", "--verbose")); err == nil {
|
||||||
|
t.Fatal("feature spelling accepted as alias source")
|
||||||
|
}
|
||||||
|
if _, err := New(Identity{Name: "test"}, owner, FlagAliasFor("owner", "--watch", "--observe")); err != nil {
|
||||||
|
t.Fatalf("feature alias rejected: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvocationFeatureFlagsParseAndDiscover(t *testing.T) {
|
||||||
|
type featureInput struct{ selected Supplied[bool] }
|
||||||
|
constructed := 0
|
||||||
|
feature := NewInvocationFeature(InvocationFeatureSpec[featureInput]{
|
||||||
|
NewInput: func() featureInput { constructed++; return featureInput{} },
|
||||||
|
Flags: []Flag[featureInput]{BoolFlag(FlagMeta{Name: "observe", Short: "o"}, false, func(i *featureInput, v Supplied[bool]) { i.selected = v })},
|
||||||
|
Start: func(inv Invocation, _ featureInput) (context.Context, func() Report) {
|
||||||
|
return inv.Context, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
type localInput struct{ name string }
|
||||||
|
var got string
|
||||||
|
cmd := NewCommand(CommandSpec[localInput]{Name: "run", Flags: []Flag[localInput]{ValueFlag(FlagMeta{Name: "name"}, (*string)(nil), func(s string) (string, error) { return s, nil }, func(i *localInput, v Supplied[string]) { i.name = v.Value })}, Run: func(_ Invocation, i localInput) Outcome { got = i.name; return Success() }})
|
||||||
|
app, err := New(Identity{Name: "test"}, WithInvocationFeature(cmd, feature), Alias("short path", "run"), FlagAlias("--watch", "--observe"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if out := app.Execute(context.Background(), []string{"run", "--watch", "--observe=false", "--name=ok"}, Streams{}); out.Status != 0 || got != "ok" {
|
||||||
|
t.Fatalf("result=%#v name=%q", out, got)
|
||||||
|
}
|
||||||
|
if out := app.Execute(context.Background(), []string{"run", "--observe=bad", "--observe=true"}, Streams{}); out.Kind != OutcomeUsage {
|
||||||
|
t.Fatalf("invalid earlier occurrence: %#v", out)
|
||||||
|
}
|
||||||
|
if out := app.Execute(context.Background(), []string{"run", "--observe=bad", "--help"}, Streams{}); out.Kind != OutcomeUsage {
|
||||||
|
t.Fatalf("help invalid flag: %#v", out)
|
||||||
|
}
|
||||||
|
if constructed != 1 {
|
||||||
|
t.Fatal("help or invalid input constructed feature input")
|
||||||
|
}
|
||||||
|
snapshot := app.routeSnapshot()
|
||||||
|
for _, path := range [][]string{nil, {"run"}, {"short"}} {
|
||||||
|
route := resolveEnteredRoute(path, snapshot)
|
||||||
|
view := app.helpView(route, snapshot)
|
||||||
|
session := internalcobra.Prepare(snapshot.metadata, commandmeta.ParseOptions{})
|
||||||
|
content, failure := session.RenderHelpView(view)
|
||||||
|
if failure != nil || !strings.Contains(content, "--observe") {
|
||||||
|
t.Fatalf("help %v: %q %#v", path, content, failure)
|
||||||
|
}
|
||||||
|
ctx := resolveCompletionContext(snapshot, path, "--obs")
|
||||||
|
target := completionTargetFor(snapshot, ctx)
|
||||||
|
found := false
|
||||||
|
for _, choice := range target.choices {
|
||||||
|
if choice.Value == "--observe" {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatalf("completion %v: %#v", path, target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvocationFeatureLifecycleAndFinalization(t *testing.T) {
|
||||||
|
type key struct{}
|
||||||
|
type input struct{ on bool }
|
||||||
|
var events []string
|
||||||
|
feature := NewInvocationFeature(InvocationFeatureSpec[input]{
|
||||||
|
NewInput: func() input { events = append(events, "feature input"); return input{} },
|
||||||
|
Flags: []Flag[input]{BoolFlag(FlagMeta{Name: "observe"}, false, func(i *input, v Supplied[bool]) { i.on = v.Value })},
|
||||||
|
Start: func(inv Invocation, i input) (context.Context, func() Report) {
|
||||||
|
events = append(events, "start")
|
||||||
|
if !i.on {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return context.WithValue(inv.Context, key{}, "value"), func() Report { events = append(events, "report"); return Report{Value: "summary"} }
|
||||||
|
},
|
||||||
|
})
|
||||||
|
var reject bool
|
||||||
|
cmd := NewCommand(CommandSpec[struct{}]{Name: "run", NewInput: func() struct{} { events = append(events, "input"); return struct{}{} }, CheckInput: func(struct{}) error {
|
||||||
|
events = append(events, "check")
|
||||||
|
if reject {
|
||||||
|
return errors.New("rejected")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}, Run: func(inv Invocation, _ struct{}) Outcome {
|
||||||
|
events = append(events, "run")
|
||||||
|
if inv.Context.Value(key{}) != "value" {
|
||||||
|
t.Error("missing context")
|
||||||
|
}
|
||||||
|
_ = inv.Reporter().AtEnd().Warn("deferred")
|
||||||
|
return Failure("failed")
|
||||||
|
}})
|
||||||
|
app, err := New(Identity{Name: "test"}, WithInvocationFeature(cmd, feature), Completion("test"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var output, diagnostics bytes.Buffer
|
||||||
|
outcome := app.Execute(context.Background(), []string{"run", "--observe", "--verbose", "--format=json"}, Streams{Out: &output, Err: &diagnostics})
|
||||||
|
if outcome.Kind != OutcomeOperational || !reflect.DeepEqual(events, []string{"input", "check", "feature input", "start", "run", "report"}) {
|
||||||
|
t.Fatalf("events=%v outcome=%#v", events, outcome)
|
||||||
|
}
|
||||||
|
if !strings.Contains(diagnostics.String(), "WARN: deferred\nsummary\nERROR: failed") {
|
||||||
|
t.Fatalf("ordering: %q", diagnostics.String())
|
||||||
|
}
|
||||||
|
events = nil
|
||||||
|
reject = true
|
||||||
|
diagnostics.Reset()
|
||||||
|
app.Execute(context.Background(), []string{"run", "--observe"}, Streams{Err: &diagnostics})
|
||||||
|
if !reflect.DeepEqual(events, []string{"input", "check"}) || strings.Contains(diagnostics.String(), "summary") {
|
||||||
|
t.Fatalf("check rejection: %v %q", events, diagnostics.String())
|
||||||
|
}
|
||||||
|
reject = false
|
||||||
|
for _, args := range [][]string{{"run", "--help"}, {"version", "--observe"}, {"completion", "bash", "--observe"}, {"missing", "--observe"}, {"run", "--observe=invalid"}} {
|
||||||
|
events = nil
|
||||||
|
app.Execute(context.Background(), args, Streams{})
|
||||||
|
if len(events) != 0 {
|
||||||
|
t.Fatalf("builtin or error %v: %v", args, events)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
events = nil
|
||||||
|
diagnostics.Reset()
|
||||||
|
app.Execute(context.Background(), []string{"run", "--observe", "--quiet"}, Streams{Err: &diagnostics})
|
||||||
|
if !strings.Contains(diagnostics.String(), "ERROR: failed") || strings.Contains(diagnostics.String(), "summary") || events[len(events)-1] != "report" {
|
||||||
|
t.Fatalf("quiet: %v %q", events, diagnostics.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvocationFeatureDiagnosticFailures(t *testing.T) {
|
||||||
|
cause := errors.New("domain cause")
|
||||||
|
failTemplate := template.Must(template.New("bad").Parse("{{call .}}"))
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
report Report
|
||||||
|
writer io.Writer
|
||||||
|
quiet bool
|
||||||
|
render, write bool
|
||||||
|
}{
|
||||||
|
{name: "render", report: Report{Value: func() (string, error) { return "", errors.New("bad template") }, TextTemplate: failTemplate}, render: true},
|
||||||
|
{name: "quiet render", report: Report{Value: func() (string, error) { return "", errors.New("bad template") }, TextTemplate: failTemplate}, quiet: true, render: true},
|
||||||
|
{name: "short write", report: Report{Value: "summary"}, writer: &reporterTestWriter{n: 1}, write: true},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
feature := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) {
|
||||||
|
return nil, func() Report { return tc.report }
|
||||||
|
}})
|
||||||
|
cmd := WithInvocationFeature(NewCommand(CommandSpec[struct{}]{Name: "run", Run: func(Invocation, struct{}) Outcome { return Domain("domain", 7).WithCause(cause) }}), feature)
|
||||||
|
app, err := New(Identity{Name: "test"}, cmd)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
args := []string{"run"}
|
||||||
|
if tc.quiet {
|
||||||
|
args = append(args, "--quiet")
|
||||||
|
}
|
||||||
|
out := app.Execute(context.Background(), args, Streams{Err: tc.writer})
|
||||||
|
if out.Kind != OutcomeDomain || out.Status != 7 || !errors.Is(out.Cause, cause) || (out.Presentation.Diagnostics.RenderError != nil) != tc.render || (out.Presentation.Diagnostics.WriteError != nil) != tc.write {
|
||||||
|
t.Fatalf("outcome=%#v", out)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequiredInvocationFlagDoesNotBlockBuiltinsOrGroupHelp(t *testing.T) {
|
||||||
|
feature := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "observe", Required: true}, false, func(*struct{}, Supplied[bool]) {})}, Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) {
|
||||||
|
t.Fatal("feature started")
|
||||||
|
return nil, nil
|
||||||
|
}})
|
||||||
|
app, err := New(Identity{Name: "test"}, WithInvocationFeature(Group("group", ""), feature))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, args := range [][]string{{"version"}, {"help"}, {"group"}, {"group", "--help"}} {
|
||||||
|
if out := app.Execute(context.Background(), args, Streams{}); out.Status != 0 {
|
||||||
|
t.Fatalf("%v: %#v", args, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvocationFeaturesChainContextsAndReports(t *testing.T) {
|
||||||
|
type chainKey struct{}
|
||||||
|
var order []string
|
||||||
|
first := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) {
|
||||||
|
order = append(order, "first start")
|
||||||
|
return context.WithValue(inv.Context, chainKey{}, "first"), func() Report { order = append(order, "first report"); return Report{Value: "first"} }
|
||||||
|
}})
|
||||||
|
second := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) {
|
||||||
|
if inv.Context.Value(chainKey{}) != "first" {
|
||||||
|
t.Error("feature context not propagated")
|
||||||
|
}
|
||||||
|
order = append(order, "second start")
|
||||||
|
return nil, func() Report { order = append(order, "second report"); return Report{Value: "second"} }
|
||||||
|
}})
|
||||||
|
cmd := NewCommand(CommandSpec[struct{}]{Name: "run", Run: func(inv Invocation, _ struct{}) Outcome {
|
||||||
|
if inv.Context.Value(chainKey{}) != "first" {
|
||||||
|
t.Error("nil context did not preserve previous context")
|
||||||
|
}
|
||||||
|
order = append(order, "run")
|
||||||
|
return Success()
|
||||||
|
}})
|
||||||
|
cmd = WithInvocationFeature(WithInvocationFeature(cmd, first), second)
|
||||||
|
app, err := New(Identity{Name: "test"}, cmd)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var diag bytes.Buffer
|
||||||
|
out := app.Execute(context.Background(), []string{"run"}, Streams{Err: &diag})
|
||||||
|
if out.Status != 0 || !reflect.DeepEqual(order, []string{"first start", "second start", "run", "first report", "second report"}) || diag.String() != "first\nsecond\n" {
|
||||||
|
t.Fatalf("%#v %v %q", out, order, diag.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFeatureOccurrencePartitionsPreserveCapturedOrder(t *testing.T) {
|
||||||
|
type inner struct{ order []string }
|
||||||
|
type outer struct{ values FlagValues[inner] }
|
||||||
|
got := make(map[string][]string)
|
||||||
|
bindings := make(map[string][]Flag[inner])
|
||||||
|
for _, prefix := range []string{"first", "second", "local"} {
|
||||||
|
for _, suffix := range []string{"a", "b"} {
|
||||||
|
bindings[prefix] = append(bindings[prefix], OccurrenceFlag(FlagMeta{Name: prefix + "-" + suffix}, func(s string) (string, error) { return s, nil }, func(i *inner, v Supplied[string]) {
|
||||||
|
if v.Set {
|
||||||
|
i.order = append(i.order, v.Value)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
capture := func(prefix string) []Flag[outer] {
|
||||||
|
return CaptureFlags(bindings[prefix], func(o *outer) *FlagValues[inner] { return &o.values })
|
||||||
|
}
|
||||||
|
apply := func(prefix string, o outer) {
|
||||||
|
var i inner
|
||||||
|
if err := o.values.ApplyTo(&i, bindings[prefix]...); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got[prefix] = i.order
|
||||||
|
}
|
||||||
|
feature := func(prefix string) InvocationFeature {
|
||||||
|
return NewInvocationFeature(InvocationFeatureSpec[outer]{Flags: capture(prefix), Start: func(inv Invocation, o outer) (context.Context, func() Report) { apply(prefix, o); return nil, nil }})
|
||||||
|
}
|
||||||
|
cmd := NewCommand(CommandSpec[outer]{Name: "run", Flags: capture("local"), Run: func(inv Invocation, o outer) Outcome { apply("local", o); return Success() }})
|
||||||
|
cmd = WithInvocationFeature(WithInvocationFeature(cmd, feature("first")), feature("second"))
|
||||||
|
cmd = WithInvocationFeature(cmd, NewInvocationFeature(InvocationFeatureSpec[struct{}]{Start: func(Invocation, struct{}) (context.Context, func() Report) { return nil, nil }}))
|
||||||
|
app, err := New(Identity{Name: "test"}, cmd, FlagAlias("--pick", "--first-b"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result := app.Execute(context.Background(), []string{"run", "--pick=B", "--local-b=L2", "--second-a=S", "--first-a=A", "--local-a=L1"}, Streams{})
|
||||||
|
if result.Status != 0 || !reflect.DeepEqual(got, map[string][]string{"first": {"B", "A"}, "second": {"S"}, "local": {"L2", "L1"}}) {
|
||||||
|
t.Fatalf("%#v %#v", result, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSharedInvocationSpellingsActivateAliasesAndPreserveRollback(t *testing.T) {
|
||||||
|
starts := 0
|
||||||
|
feature := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "observe", Short: "o"}, false, func(*struct{}, Supplied[bool]) {})}, Start: func(Invocation, struct{}) (context.Context, func() Report) { starts++; return nil, nil }})
|
||||||
|
run := NewCommand(CommandSpec[struct{}]{Name: "run", Run: func(Invocation, struct{}) Outcome { return Success() }})
|
||||||
|
app, err := New(Identity{Name: "test"}, run, Alias("deep run", "run"), FlagAlias("--watch", "--observe"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if r := app.Execute(context.Background(), []string{"run", "--watch"}, Streams{}); r.Kind != OutcomeUsage {
|
||||||
|
t.Fatalf("inactive alias: %#v", r)
|
||||||
|
}
|
||||||
|
if err := app.Register(WithInvocationFeature(Group("owner", ""), feature), FlagAliasFor("run", "--inspect", "--observe")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, args := range [][]string{{"run", "--watch"}, {"deep", "run", "--inspect"}, {"run", "-o"}} {
|
||||||
|
if r := app.Execute(context.Background(), args, Streams{}); r.Status != 0 {
|
||||||
|
t.Fatalf("%v: %#v", args, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if starts != 3 {
|
||||||
|
t.Fatalf("starts=%d", starts)
|
||||||
|
}
|
||||||
|
var out bytes.Buffer
|
||||||
|
if r := app.Execute(context.Background(), []string{"deep", "--watch", "--help"}, Streams{Out: &out}); r.Status != 0 || !strings.Contains(out.String(), "--observe") || starts != 3 {
|
||||||
|
t.Fatalf("discovery: %#v %q", r, out.String())
|
||||||
|
}
|
||||||
|
conflict := NewCommand(CommandSpec[struct{}]{Name: "conflict", Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "other", Short: "o"}, false, func(*struct{}, Supplied[bool]) {})}})
|
||||||
|
if err := app.Register(conflict); err == nil {
|
||||||
|
t.Fatal("short spelling collision accepted")
|
||||||
|
}
|
||||||
|
if err := app.Register(FlagAlias("--observe", "--verbose")); err == nil {
|
||||||
|
t.Fatal("canonical alias source collision accepted")
|
||||||
|
}
|
||||||
|
if r := app.Execute(context.Background(), []string{"deep", "run", "--watch"}, Streams{}); r.Status != 0 || starts != 4 {
|
||||||
|
t.Fatalf("rollback: %#v starts=%d", r, starts)
|
||||||
|
}
|
||||||
|
}
|
||||||
17
parser.go
17
parser.go
@@ -71,14 +71,17 @@ func (a *App) routeSnapshot() *routingSnapshot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) buildRoutingSnapshot() *routingSnapshot {
|
func (a *App) buildRoutingSnapshot() *routingSnapshot {
|
||||||
root := &commandmeta.Command{Name: a.identity.Name, CoreFlags: commandmeta.ReportingFlags()}
|
root := &commandmeta.Command{Name: a.identity.Name, CoreFlags: commandmeta.ReportingFlags(), InvocationFlags: a.featureFlags}
|
||||||
snapshot := &routingSnapshot{
|
snapshot := &routingSnapshot{
|
||||||
metadata: root,
|
metadata: root,
|
||||||
runners: make(map[commandmeta.Key]commandPayload),
|
runners: make(map[commandmeta.Key]commandPayload),
|
||||||
|
builtins: make(map[commandmeta.Key]bool),
|
||||||
aliases: a.aliases,
|
aliases: a.aliases,
|
||||||
canonical: buildCanonicalTree(a.commands),
|
canonical: buildCanonicalTree(a.commands),
|
||||||
flagAliases: a.flagAliases,
|
flagAliases: a.flagAliases,
|
||||||
discoveryFlags: a.discoveryFlags,
|
discoveryFlags: a.discoveryFlags,
|
||||||
|
features: a.features,
|
||||||
|
featureFlags: a.featureFlags,
|
||||||
}
|
}
|
||||||
if node := a.commands["completion"]; node != nil {
|
if node := a.commands["completion"]; node != nil {
|
||||||
snapshot.completion = node.command.record.completion
|
snapshot.completion = node.command.record.completion
|
||||||
@@ -111,13 +114,15 @@ func bridgeCommand(node *canonicalNode, snapshot *routingSnapshot, next *command
|
|||||||
record := node.command.record
|
record := node.command.record
|
||||||
*next = *next + 1
|
*next = *next + 1
|
||||||
declaration := &commandmeta.Command{
|
declaration := &commandmeta.Command{
|
||||||
Key: *next,
|
Key: *next,
|
||||||
Name: record.name,
|
Name: record.name,
|
||||||
Summary: record.summary,
|
Summary: record.summary,
|
||||||
Description: record.description,
|
Description: record.description,
|
||||||
CoreFlags: commandmeta.ReportingFlags(),
|
CoreFlags: commandmeta.ReportingFlags(),
|
||||||
|
InvocationFlags: snapshot.featureFlags,
|
||||||
}
|
}
|
||||||
node.metadata = declaration
|
node.metadata = declaration
|
||||||
|
snapshot.builtins[declaration.Key] = record.builtin
|
||||||
if record.payload != nil {
|
if record.payload != nil {
|
||||||
snapshot.runners[declaration.Key] = record.payload
|
snapshot.runners[declaration.Key] = record.payload
|
||||||
declaration.Runnable = record.payload.hasRun()
|
declaration.Runnable = record.payload.hasRun()
|
||||||
|
|||||||
75
registry.go
75
registry.go
@@ -28,6 +28,8 @@ type installationCandidate struct {
|
|||||||
aliases *internalalias.Resolver
|
aliases *internalalias.Resolver
|
||||||
flagAliases map[string]resolvedFlagAliases
|
flagAliases map[string]resolvedFlagAliases
|
||||||
discoveryFlags map[string]resolvedFlagAliases
|
discoveryFlags map[string]resolvedFlagAliases
|
||||||
|
features []*invocationFeatureRecord
|
||||||
|
featureFlags []commandmeta.Flag
|
||||||
changed bool
|
changed bool
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,6 +93,8 @@ func (a *App) installBatch(declarations ...Declaration) error {
|
|||||||
a.aliases = candidate.aliases
|
a.aliases = candidate.aliases
|
||||||
a.flagAliases = candidate.flagAliases
|
a.flagAliases = candidate.flagAliases
|
||||||
a.discoveryFlags = candidate.discoveryFlags
|
a.discoveryFlags = candidate.discoveryFlags
|
||||||
|
a.features = candidate.features
|
||||||
|
a.featureFlags = candidate.featureFlags
|
||||||
a.snapshot = nil
|
a.snapshot = nil
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -154,11 +158,18 @@ func (a *App) buildInstallationCandidate(commands []Command, addedRules []Routin
|
|||||||
}
|
}
|
||||||
candidate.aliases = resolver
|
candidate.aliases = resolver
|
||||||
|
|
||||||
|
candidate.features, candidate.featureFlags, err = collectInvocationFeatures(candidate.commands)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
tree := buildCanonicalTree(candidate.commands)
|
tree := buildCanonicalTree(candidate.commands)
|
||||||
|
if err := validateInvocationFlagCollisions(tree, candidate.featureFlags); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
if err := validateCommandAliases(rules, resolver, tree); err != nil {
|
if err := validateCommandAliases(rules, resolver, tree); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
flagAliases, discoveryFlags, err := compileFlagAliases(rules, tree, resolver)
|
flagAliases, discoveryFlags, err := compileFlagAliases(rules, tree, resolver, candidate.featureFlags)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -365,3 +376,65 @@ func acceptsOperandPrefix(command Command, count int) bool {
|
|||||||
}
|
}
|
||||||
return maximum < 0 || count <= maximum
|
return maximum < 0 || count <= maximum
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// collectInvocationFeatures walks declarations in stable root, child and attachment order.
|
||||||
|
func collectInvocationFeatures(commands map[string]*commandNode) ([]*invocationFeatureRecord, []commandmeta.Flag, error) {
|
||||||
|
names := make([]string, 0, len(commands))
|
||||||
|
for name := range commands {
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
sort.Strings(names)
|
||||||
|
seen := make(map[*invocationFeatureRecord]bool)
|
||||||
|
var features []*invocationFeatureRecord
|
||||||
|
var flags []commandmeta.Flag
|
||||||
|
var visit func(Command)
|
||||||
|
visit = func(command Command) {
|
||||||
|
if command.record == nil || command.record.absent {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, feature := range command.record.features {
|
||||||
|
if !seen[feature.record] {
|
||||||
|
seen[feature.record] = true
|
||||||
|
features = append(features, feature.record)
|
||||||
|
flags = append(flags, feature.record.payload.bridgeFlags()...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, child := range command.record.children {
|
||||||
|
visit(child)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, name := range names {
|
||||||
|
visit(commands[name].command)
|
||||||
|
}
|
||||||
|
seenFlags := helpFlagSpellings()
|
||||||
|
for _, flag := range flags {
|
||||||
|
for _, spelling := range featureSpellings(flag) {
|
||||||
|
key := flagSpellingKey(spelling)
|
||||||
|
if _, exists := seenFlags[key]; exists {
|
||||||
|
return nil, nil, fmt.Errorf("invocation feature flag %s conflicts with another flag", spelling.token())
|
||||||
|
}
|
||||||
|
seenFlags[key] = spelling
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return features, flags, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func featureSpellings(flag commandmeta.Flag) []capturedFlagSpelling {
|
||||||
|
spellings := []capturedFlagSpelling{{name: flag.Name}}
|
||||||
|
if flag.Short != "" {
|
||||||
|
spellings = append(spellings, capturedFlagSpelling{name: flag.Short, short: true})
|
||||||
|
}
|
||||||
|
return spellings
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateInvocationFlagCollisions(roots map[string]*canonicalNode, flags []commandmeta.Flag) error {
|
||||||
|
shared := invocationFlagSpellings(flags)
|
||||||
|
for _, node := range indexCanonicalNodes(roots) {
|
||||||
|
for key, spelling := range canonicalFlagSpellings(node.command) {
|
||||||
|
if _, exists := shared[key]; exists {
|
||||||
|
return fmt.Errorf("invocation feature flag %s conflicts with command %q", spelling.token(), node.path.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
34
reporter.go
34
reporter.go
@@ -203,6 +203,32 @@ func (r *Reporter) RenderOutput(write func(io.Writer) error) error {
|
|||||||
return finishRenderLocked(state, destinationOutput, renderErr, writer.writeError)
|
return finishRenderLocked(state, destinationOutput, renderErr, writer.writeError)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// renderDiagnosticReport uses the same delivery bookkeeping as output reports,
|
||||||
|
// while always rendering text and treating quiet as delivery suppression only.
|
||||||
|
func (r *Reporter) renderDiagnosticReport(report Report) error {
|
||||||
|
if r == nil || r.state == nil {
|
||||||
|
return ErrReporterClosed
|
||||||
|
}
|
||||||
|
state := r.state
|
||||||
|
state.mu.Lock()
|
||||||
|
defer state.mu.Unlock()
|
||||||
|
if state.closed {
|
||||||
|
return ErrReporterClosed
|
||||||
|
}
|
||||||
|
destination := state.destination(destinationDiagnostics)
|
||||||
|
destination.submitted = true
|
||||||
|
if state.mode == ReportingModeQuiet {
|
||||||
|
destination.suppressed = true
|
||||||
|
return finishRenderLocked(state, destinationDiagnostics, RenderReport(io.Discard, report, FormatText), nil)
|
||||||
|
}
|
||||||
|
writer := &coordinatedWriter{state: state, destination: destinationDiagnostics}
|
||||||
|
err := RenderReport(writer, report, FormatText)
|
||||||
|
if err == nil && writer.writeError == nil {
|
||||||
|
destination.delivered = true
|
||||||
|
}
|
||||||
|
return finishRenderLocked(state, destinationDiagnostics, err, writer.writeError)
|
||||||
|
}
|
||||||
|
|
||||||
// Info submits an informational message to the diagnostic destination. Its
|
// Info submits an informational message to the diagnostic destination. Its
|
||||||
// visibility follows the selected reporting mode.
|
// visibility follows the selected reporting mode.
|
||||||
func (r *Reporter) Info(message string, details ...Detail) error {
|
func (r *Reporter) Info(message string, details ...Detail) error {
|
||||||
@@ -287,7 +313,7 @@ func (r DeferredReporter) enqueue(category messageCategory, message string, deta
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Reporter) finalize(outcome Outcome, completion func(*Reporter)) Outcome {
|
func (r *Reporter) finalize(outcome Outcome, completion func(*Reporter), producers ...func() Report) Outcome {
|
||||||
if r == nil || r.state == nil {
|
if r == nil || r.state == nil {
|
||||||
return normalizeOutcome(outcome)
|
return normalizeOutcome(outcome)
|
||||||
}
|
}
|
||||||
@@ -314,6 +340,12 @@ func (r *Reporter) finalize(outcome Outcome, completion func(*Reporter)) Outcome
|
|||||||
completion(r)
|
completion(r)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for _, produce := range producers {
|
||||||
|
if produce != nil {
|
||||||
|
_ = r.renderDiagnosticReport(produce())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
state.mu.Lock()
|
state.mu.Lock()
|
||||||
if presentationFailedLocked(state) {
|
if presentationFailedLocked(state) {
|
||||||
if outcome.Status == 0 && !hasExplanation(outcome.Explanation) {
|
if outcome.Status == 0 && !hasExplanation(outcome.Explanation) {
|
||||||
|
|||||||
Reference in New Issue
Block a user