Compare commits

...

32 Commits

Author SHA1 Message Date
0b53a63648 Draft coordinated usage reporting release notes 2026-11-23 00:22:36 +00:00
ef92089125 Retire completed usage reporting plans and reviews 2026-11-23 00:20:32 +00:00
33f98db4f7 Clarify local core requirements for unreleased integrations 2026-11-22 22:24:43 +00:00
3e4309f084 Share invocation flag lookup across installation contexts 2026-11-22 22:24:06 +00:00
3415d9337d Partition flag occurrences once per invocation 2026-11-22 22:23:07 +00:00
98e3958dfb Honor help-only input checks before starting features 2026-11-22 22:21:32 +00:00
362afc79b6 Update the smoke report reference 2026-11-22 22:19:57 +00:00
611e66322d Record algorithmic audit findings 2026-11-22 22:04:51 +00:00
367d05b7d9 Record the configuration help integration gap 2026-11-22 21:42:05 +00:00
70cd68f960 Record the usage reporting review finding 2026-11-22 21:33:59 +00:00
b7467c59fa Verify native vLLM authentication findings 2026-11-22 21:07:34 +00:00
a0cdd3d7c5 Document and validate automatic usage reporting 2026-11-22 21:06:39 +00:00
a0608a53ee Demonstrate automatic usage in composed pipeline 2026-11-22 21:02:14 +00:00
07cc832f4a Report observed PromptKit invocation usage 2026-11-22 20:59:23 +00:00
0d5e13c7a9 Adopt PromptKit usage and backend evidence 2026-11-22 20:58:10 +00:00
ba6c9035b1 Verify invocation features through public assembly 2026-11-22 20:56:09 +00:00
d039efb11d Run invocation features and render final reports 2026-11-22 20:54:58 +00:00
b6cb183a71 Parse invocation flags across command discovery 2026-11-22 20:53:25 +00:00
ea3ce25001 Capture and validate invocation features 2026-11-22 20:52:04 +00:00
68515668de Plan automatic usage reporting implementation 2026-11-22 20:26:16 +00:00
f0b4108151 Clarify usage observation boundaries and plan review 2026-11-22 20:19:36 +00:00
e2ffe82324 Clarify usage reporting boundaries and core API design checkpoint 2026-11-22 20:00:43 +00:00
d9df7e2d6b Rewrite the usage reporting roadmap around the agreed target state 2026-11-22 19:39:24 +00:00
78e9c75dfe Record the agreed usage summary fields 2026-11-22 19:34:45 +00:00
d8f2f67671 Record empty usage summary and observation boundary decisions 2026-11-22 19:31:47 +00:00
b1193564e9 Record text-only usage summary decisions 2026-11-22 19:29:16 +00:00
fe4e8d756d Record usage summary reporting decisions 2026-11-22 19:28:02 +00:00
dc0ab74135 Record automatic usage installation decisions 2026-11-22 19:26:17 +00:00
91ef377bcd Record the token reporting flag decision 2026-11-22 19:24:35 +00:00
55e0f8c8b0 Update the usage reporting roadmap for PromptKit v0.25.0 2026-11-22 19:15:35 +00:00
a4aa76de33 Plan automatic PromptKit usage reporting 2026-11-22 09:55:13 +00:00
1138960e96 Retire the completed integration release records 2026-11-21 21:19:47 +00:00
47 changed files with 1710 additions and 919 deletions

5
app.go
View File

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

View File

@@ -58,6 +58,8 @@ func (a *App) builtinCommands() []Declaration {
return renderVersionOutcome(identity, invocation.Reporter())
},
})
help.record.builtin = true
version.record.builtin = true
return []Declaration{help, version}
}

View File

@@ -17,6 +17,10 @@ import (
// before changing an App registry.
type Command struct{ record *commandRecord }
// ErrHelpRequested may be returned by CommandSpec.CheckInput to display command
// help without starting invocation features or enforcing their required flags.
var ErrHelpRequested = errors.New("command help requested")
// Declaration is a captured canonical command or application routing rule
// accepted by New and App.Register. Use []Declaration when collecting both
// kinds. Group and RootGroup children remain Commands; install routing rules
@@ -71,10 +75,12 @@ type commandRecord struct {
summary string
description string
children []Command
features []InvocationFeature
payload commandPayload
issues []error
rootOnly bool
completion bool
builtin bool
absent bool
invalid bool
}
@@ -187,7 +193,8 @@ type CommandSpec[I any] struct {
Flags []Flag[I]
// Arguments declares the command's positional inputs.
Arguments []Argument[I]
// CheckInput validates declared combinations of parsed inputs.
// CheckInput validates declared combinations of parsed inputs. Returning
// ErrHelpRequested displays help without running the command or its features.
CheckInput func(I) error
// Run handles an invocation. It may be nil for a command used as a group.
Run func(Invocation, I) Outcome
@@ -256,9 +263,16 @@ func (c typedCommand[I]) prepare(flagValues, flagSpellings [][]string, occurrenc
input := prepared.build()
if c.spec.CheckInput != nil {
if err := c.spec.CheckInput(input); err != nil {
if errors.Is(err, ErrHelpRequested) {
return current.renderHelp(current.route.canonicalPath)
}
return classifyInputError(err)
}
}
if current.featureEnabled && current.featureRequiredError != nil {
return classifyInputError(current.featureRequiredError)
}
current.startFeatures()
if c.privateRun != nil {
return c.privateRun(current.commandContext(), input)
}
@@ -467,6 +481,15 @@ func validateCommandPlacement(command Command) error {
issues = append(issues, issue)
}
}
for _, feature := range record.features {
if feature.record == nil {
issues = append(issues, fmt.Errorf("command %q: invalid zero invocation feature", record.name))
continue
}
for _, issue := range feature.record.issues {
issues = append(issues, fmt.Errorf("command %q invocation feature: %w", record.name, issue))
}
}
if record.rootOnly && !root {
issues = append(issues, fmt.Errorf("root-only command %q is nested beneath another command", label))
}

View File

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

View File

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

View File

@@ -35,7 +35,7 @@ type completionFlagState struct {
func completionFlags(context completionContext) []commandmeta.Flag {
flags := make([]commandmeta.Flag, 0, len(context.command.Flags)+len(context.command.CoreFlags)+1)
flags = append(flags, commandmeta.HelpFlag())
flags = append(flags, 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
}

2
doc.go
View File

@@ -5,6 +5,8 @@
//
// App.Execute runs a command and returns an Outcome; the application decides
// when to exit. Handlers use Invocation.Reporter for output and messages.
// Invocation features can add application-wide flags, decorate the invocation
// context after CheckInput succeeds, and produce diagnostic reports at finalization.
// Optional ckconfig and ckprompt modules add inspection and testing commands;
// applications install those commands explicitly.
package commandkit

View File

@@ -674,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
value or a claim that one is available. Neither report resolves references or
performs a network probe. See the [PromptKit resource inspection
contracts](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/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
[configuration failure classification](#configuration-failure-classification);
lookup failures and cancellation are operational.
@@ -730,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
call will succeed. Application loaders and callbacks may have their own
effects. The [PromptKit Prepare
API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/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
follow the [configuration failure classification](#configuration-failure-classification);
other preparation failures are operational.
@@ -766,8 +766,8 @@ identity rather than changing the discovered requirements. An enabled profile
namespace qualifies an explicitly supplied short profile ID; it does not
rewrite the prompt's stored default reference. Requirements inspection does
not require the selected profile to be execution-ready. See the [PromptKit
v0.24.0 consumer
guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/docs/consumers/pkg-promptkit.md)
v0.25.0 consumer
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
other than `--llm-var`, repeating a flag uses its last value.
Application-defined flags follow their own repetition rules.
@@ -878,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
not certify provider acceptance or guarantee later execution. See PromptKit's
[`Engine.ValidateRequest`
API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/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
the [configuration failure classification](#configuration-failure-classification).
@@ -944,11 +944,29 @@ The entries are:
A catalog result is an inventory, not a readiness check or execution result.
The owning provider controls membership and order. Namespace filters are
passed to PromptKit without local membership interpretation. See the
[PromptKit v0.24.0 consumer
guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/docs/consumers/pkg-promptkit.md)
[PromptKit v0.25.0 consumer
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
[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 test KIND` runs a PromptKit smoke test using the application's
@@ -1009,7 +1027,7 @@ conflicting namespace flags use status `2`.
| `--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-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
`--llm-api-key-env` value is a variable name, not a credential value. The
@@ -1031,7 +1049,11 @@ The report includes `kind`, `supported`, `applicable`, `completed`, `reason`,
contains selected IDs, selection source, endpoint, effective settings, and
settings-presence flags. Attempt entries retain their own facts, timing,
failure, and token-usage evidence. Durations use Go duration strings; token
counts preserve `value`, `known`, and `complete`.
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:
@@ -1088,6 +1110,8 @@ attempts: []
usage:
prompt_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}
cached_tokens: {value: 0, known: true, complete: true}
cache_write_tokens: {value: 0, known: true, complete: true}
@@ -1116,9 +1140,9 @@ separately from delivery failures through the [reporting
API](consumers/guide.md#invocation-reporting).
Native configuration, selection, and diagnostic meanings remain owned by
PromptKit. See the [v0.24.0 consumer guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/docs/consumers/pkg-promptkit.md),
[smoke API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/smoke_diagnostics.go),
and [engine API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/engine.go).
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/207677e9948dc5699073a4d6620d21139033c72d/smoke_diagnostics.go),
and [engine API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/engine.go).
## Outcome status

View File

@@ -46,11 +46,14 @@ loaders should use keyed struct literals when constructing them. ConfigKit's
release notes describe
main-relative imports and overlay contexts. [ConfigKit v1.2.0 upgrade guidance](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.2.0/docs/releases/v1.2.0.md#upgrade-notes).
The current checkout selects PromptKit v0.24.0. Complete documents put
The current unreleased checkout selects PromptKit v0.25.0 and requires the local
core through the aligned workspace. Unreleased ckconfig also requires local core
for its help-only preflight signal; dependency releases remain follow-up work.
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.24.0/docs/consumers/configuration-migration.md)
and [format reference](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.24.0/docs/formats.md)
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
@@ -392,6 +395,28 @@ suite := ckprompt.WithRequestValidation(
validationCommand := ckprompt.Command(suite)
```
### Automatic usage reporting
Installing a nonempty ckprompt family with either `Command` or `Declarations`
adds `--show-tokens` to application commands as well as PromptKit commands.
An empty suite adds nothing. The flag defaults to false; explicit false and
repeated selections use the ordinary Boolean rules. Applications pass
`Invocation.Context` into PromptKit and wait for their own work before returning.
The observer starts after command input construction and successful `CheckInput`,
before `Run`; validation or acquisition inside `Run` is included.
`CommandSpec.CheckInput` may return `commandkit.ErrHelpRequested` for a
help-only preflight result; core renders help without starting features or
requiring execution-only invocation flags. ckconfig uses this for bare
`config explain`. Help, version,
completion, parse errors, and rejected command inputs do not start observation.
The requested summary is text on diagnostics after deferred messages and before
any failure explanation, independently of the main report's `--format`. Quiet
suppresses delivery. Counts and cost preserve unknown and incomplete states,
known zero, cost source, and terminal coverage; the cache ratio is shown only when
available. Smoke tests report their own usage separately. An empty ordinary
summary is not a measurement of smoke-test usage. See the [operator reference](../cli.md#promptkit-usage-reporting).
### Request builders and loading
If the loader is nil, the returned suite retains a wiring issue for installation
@@ -436,7 +461,7 @@ and uses `Engine.ValidateRequest`.
Applications own engine construction and may build complete native requests in
callbacks. Preparation and validation use the supplied context; execution owns
prepared notifications and operation timeouts. See the [PromptKit consumer
guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/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.
`ckprompt.WithRequestPreparation` adds a separate callback backed by
@@ -499,7 +524,7 @@ These are independent defaults for unqualified caller-supplied prompt, profile,
and backend names; qualified IDs pass through. Stored references and configuration
inspection are unchanged, while namespace and collection inventories remain global.
Catalog `--namespace` filters are separate from these defaults. See the released
[namespace API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/namespaces.go).
[namespace API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/namespaces.go).
## Outcomes and ownership
@@ -514,7 +539,7 @@ Go declarations and GoDoc own exact exported contracts. ConfigKit owns
configuration decoding, validation, and provenance. PromptKit owns prompt
formats, profile resolution, and inspection details. See the
[ConfigKit v1.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/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/engine.go),
[configuration inspection](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/configuration_inspection.go),
[smoke diagnostics](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/smoke_diagnostics.go),
and [PromptKit v0.24.0 consumer guidance](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/docs/consumers/pkg-promptkit.md).
[PromptKit engine methods](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/engine.go),
[configuration inspection](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/configuration_inspection.go),
[smoke diagnostics](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/smoke_diagnostics.go),
and [PromptKit v0.25.0 consumer guidance](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/docs/consumers/pkg-promptkit.md).

View File

@@ -119,9 +119,14 @@ If a workspace already exists, ensure it includes these three modules. Preserve
the ignored `go.work` and `go.work.sum`; do not commit them. Use
`GOWORK=off GOTOOLCHAIN=local` for dependency preparation
and independent module suites. Both integrations select released core v0.7.0;
ckprompt selects released ckconfig v0.10.0. All three modules support independent
builds against their published dependencies. Run each independent suite with
`GOWORK=off GOTOOLCHAIN=local go test ./...` from its module directory.
ckprompt selects released ckconfig v0.10.0. Core builds independently against its published dependencies. Both unreleased
integrations now use newer local core APIs (including ckconfig's help-only
preflight signal) and need the aligned workspace until downstream releases are
prepared. For an isolated source check, use a temporary modfile replacing core
with local sources; ckprompt also needs a local ckconfig replacement. Before
integration publication, repeat the independent suites 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:

View File

@@ -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
accessor reads the reporter's selection under its existing state mutex.
Captured invocation features contribute application-wide flags through the same
parser and alias views. The installer deduplicates handles and validates the
prospective registry atomically. Each invocation prepares feature values, starts
features after successful command input checking, and retains returned report
producers only until finalization. Generated builtins do not start features.
The reporter owns invocation-scoped visibility, message formatting, managed
report rendering, delivery observations, and finalization. It presents queued
messages after the handler returns, then a failed outcome's explanation, and
messages after the handler returns, then feature reports, then a failed outcome's explanation, and
closes its handles before `Execute` returns. It records rendering and write
errors separately for result and diagnostic destinations; the returned
`Outcome.Presentation` exposes those observations independently from the

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

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

View File

@@ -1,280 +0,0 @@
# ConfigKit v1.4.0 and PromptKit v0.24.0 adoption
Status: implementation complete; coordinated releases pending. Prepared 2026-11-21.
This document defines the desired target and accepted scope, not implemented
behavior or authorization to publish releases. The
[implementation plan](implementation.md) owns execution stages and completion
evidence.
## Purpose and ownership
Adopt the released upstream capabilities through the existing operator command
suite. `ckprompt` should neutrally expose PromptKit's public APIs, using the
implementation with the lowest conceptual complexity and the least
CommandKit-owned domain machinery. ConfigKit and PromptKit continue to own
loading, resolution, validation, preparation, inspection, and comparison.
Applications own construction, startup, credentials, and execution workflows.
Core owns shared CLI parsing, reporting, and delivery.
For this adoption, minimize complexity borne by applications first, then
complexity maintained by ckconfig. These priorities take precedence over a more
tailored operator experience. Prefer native paths, whole-load evidence, and
existing outcome handling to extra machinery for more polished subtree reports.
The [architecture policy](../policy/architecture.md) and
[integration ADR](../adr/0004-optional-integration-modules.md) govern these
boundaries. Native delegation preserves upstream meaning; it does not require
removing useful existing CLI projections, filters, or outcome handling.
This adoption introduces no additional ordering, copying, concurrency,
serialization-stability, or isolation guarantees.
## Baseline and upstream targets
Reviewed repository revision: `b1c7962f51eb9e81104a291bc1966a90b4e772a3`.
| Component | Baseline | Adoption target |
| --- | --- | --- |
| CommandKit core | v0.7.0 | No core change required by this scope |
| ckconfig | v0.9.0; ConfigKit v1.2.1 | ConfigKit v1.4.0, native scoped path enumeration, and a public native-inspection adapter |
| ckprompt | v0.10.0; PromptKit v0.23.2, ConfigKit v1.2.1, ckconfig v0.9.0 | PromptKit v0.24.0, ConfigKit v1.4.0, and the resulting released ckconfig |
| Go | Consumer minimum 1.27.0; release toolchain 1.27.4 | No change required by these upstream releases |
Adoption covers the intervening ConfigKit v1.3.0 and PromptKit v0.23.3 changes.
Use the released versions, not unreleased upstream work. The reviewed release
commits are ConfigKit `4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3` and PromptKit
`5ea60e9b96651fd7dfcbc7d05b6f43d131df358f`.
Upstream sources:
- [ConfigKit v1.3.0: configured secrets bootstrap](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.3.0/docs/releases/v1.3.0.md).
- [ConfigKit v1.4.0: typed value access and focused inspection](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/docs/releases/v1.4.0.md).
- [PromptKit v0.23.3: timeout and cancellation identities](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.23.3/docs/releases/v0.23.3.md).
- [PromptKit v0.24.0: shared loading, schemas, and preparation](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.24.0/docs/releases/v0.24.0.md).
- [PromptKit configuration migration](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.24.0/docs/consumers/configuration-migration.md)
and [format reference](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.24.0/docs/formats.md).
The pre-adoption review used a temporary copy with only dependency declarations
and checksums updated. The ckconfig package and simple-example suites passed.
The ckprompt production packages built, but its test package failed to compile
because `constructor_outcomes_test.go` uses removed `WithSchemaFile`; seven
top-level composed-example tests failed with the old configuration layout.
An offline shared-load probe confirmed both automatic reporting of the new
prepared hash and repair budget, and the path-listing mismatch described below.
These observations establish migration work; they are not final acceptance
evidence for the implementation.
## Targeted end state
### One application-owned load, existing integration callbacks
The maintained composed example demonstrates an application configuration with
`promptkit.Settings` under `promptkit`, rules composed with `promptkit.Configure`,
and a completed ConfigKit result passed directly to `promptkit.NewFromConfig`.
The application result serves configuration inspection and the engine serves
PromptKit commands through the existing loader callbacks and shared invocation
state. This removes the example's separate reconstruction and loading of
PromptKit configuration where the shared result supplies that information.
The example should make source selection, campaign-derived settings, and
comparison sides understandable. Any reused result must correspond to the
requested selection and relevant application inputs; left and right comparisons
still receive their independently selected configurations. Reuse remains an
application choice, not a CommandKit cache or a new promise about load counts.
Preserve the meaningful selector and lifecycle demonstrations when restructuring
the example.
Select `BundledOpenRouterUnderlay` before the application-owned load when the
example intends to include that catalog. `NewFromConfig` does not add it or
rerun configuration callbacks. `NewEngine` remains a supported standalone
construction path. No CommandKit constructor wrapper is needed for either path.
`Result.Value` supplies trusted current Go values, potentially including resolved
secrets and shared references. It is not a replacement for safe inspection in
CLI reports. Continue to use upstream frozen, redacted evidence for configuration
output; the application's handoff follows upstream ownership semantics.
### Native scoped inspection
PromptKit's configuration inspection now focuses on `/promptkit`. Its
`HistoricalPaths()` enumerates that focus, while `Metadata()`, source evidence,
and explicit path queries retain whole-load context. For example, a load with
`app_name` and `promptkit` should not acquire `/app_name` in the PromptKit path
list merely because that path exists in the original load's metadata.
Currently, [ckconfig's explanation handler](../../integrations/ckconfig/explain.go)
enumerates `View.Metadata.HistoricalPaths()`. The
[PromptKit adapter](../../integrations/ckprompt/adapters.go) supplies full metadata,
so this bypasses upstream's new focused enumeration.
Provide the narrow capability needed for the shared handler to enumerate native
inspection paths. `ckprompt` supplies PromptKit's `HistoricalPaths()` directly;
ckconfig uses metadata to describe the returned paths' presence and explicitness.
Ordinary whole-result scopes continue to enumerate their native metadata paths.
The [implementation plan](implementation.md#stage-2-separate-native-path-enumeration-from-metadata-lookup)
selects the narrow provider extension and preserves existing custom-provider
behavior. This capability is not a parallel inspection model.
Retain the existing CLI filters (`--under`, `--historical`, and `--explicit`) on
the supplied enumeration. Preserve native application paths, such as
`/promptkit/profiles/0/model`, without rebasing or adding compatibility aliases
for the former document layout. Explicit `--path` queries use upstream semantics,
including queries outside the focus where upstream supports them. Selecting a
scope is not an access-control boundary.
Continue native comparison and source reporting. Do not filter away upstream
ancestor differences or trim the source catalog to manufacture isolation.
Focused rendering reports the selected subtree; explicit root queries retain
their native whole-document meaning. An absent effective subtree and explicit
null retain their upstream distinction and errors through the existing report
delivery mechanism. Do not invent an empty configuration to hide absence.
### Public native-inspection adapter
Include a reusable ckconfig adapter in this adoption and the next ckconfig
release. It registers a named configuration scope backed by ConfigKit's native
subtree inspection, reducing application wiring for effective settings, path
discovery, explanations, source evidence, and comparison. Applications retain
configuration acquisition and selection; the adapter supplies standard CLI
integration and delegates domain operations to ConfigKit.
The adapter shares the native path-enumeration capability. The maintained
composed example demonstrates one application section, such as storage settings.
The section name is illustrative, not a new reserved scope.
Preserve load diagnostics and error evidence through existing reporting and
outcome conventions. A focused inspection does not independently validate a
subtree or make whole-load evidence local to it.
Use a small sibling of `FromConfigKit`, with `FromConfigKitSubtree` as the planned
helper name. The application supplies a scope name and summary, an explicit
`configkit.Path`, and its existing typed loader returning
`(*configkit.Result[T], error)` with the same context, selection, input, and state
parameters as `FromConfigKit`. The helper returns the existing `Scope[I, S]`.
Applications need not assemble diagnostic bundles, translate errors, or create
an intermediate inspection representation.
The adapter obtains source and diagnostic evidence from the result and selects
the native view with `InspectSubtree(path)`. For comparison, it acquires each
side's result, selects the same subtree, and calls native `Inspection.Diff`.
Share existing acquisition and diagnostic/error handling where useful without
introducing a general framework solely to remove repeated lines.
Retain whole-load diagnostics and validation outcomes. Successful loads with
warnings remain usable; detailed validation retains native findings and sources
through the existing presentation conventions. On failed loading, preserve
available ConfigKit load-error evidence and supported error identity. Other
application errors remain errors without invented ConfigKit findings. Reuse
existing classification and duplicate-presentation handling; do not silently
filter evidence to the selected subtree, ignore failures elsewhere in the load,
or create an independent subtree-validation result.
This release targets exposing a section from an ordinary typed application
result. An additional entry point for already selected inspection views and
accommodation of different root Go types across comparison sides are outside
this adoption. An options framework is unnecessary for the single path argument.
PromptKit uses the shared inspection capability directly. It need not pass
through this new helper if that would require converting its public inspection
type merely to fit the helper. The accepted API and evidence direction is recorded
in OD-2 below; the [implementation plan](implementation.md) owns the exact
declaration and internal factoring within that direction.
### Existing commands expose the new upstream evidence
| Operator task | Existing command | Adoption behavior |
| --- | --- | --- |
| Inspect a prompt's output contract | `promptkit show prompt ID` | Report native inline schema or schema references and resolved repair budget, including zero |
| Preview the completed request | `promptkit show prepared ID` | Report native `message_content_hash`, resolved contract, and prepared schema evidence without model execution |
| Discover inputs or validate a request | `promptkit requirements show ID`, `promptkit requirements validate ID` | Preserve upstream effective requirements, including application defaults, and current preparation/error semantics |
| Inspect configuration and provenance | `config show`, `sources`, `explain`, `diff`, `validate` with `--scope promptkit` | Use native focused inspection and retain supporting whole-load evidence |
| Exercise native smoke checks | `promptkit test ...` | Continue forwarding selected requests and presenting native evidence and errors |
Prompt and prepared reports already hand native values to the core reporter.
Keep that path so new fields appear without a second renderer or a local hash
implementation. Existing projections, such as requirements reports, should retain
the meaning of the updated native results. Hash semantics, schema resolution,
repair behavior, and error identities remain upstream-owned.
## Compatibility and delivery
The adopted configuration uses native `/promptkit` locations for complete
settings documents and inspection paths; resource IDs retain their names.
Wrapperless fragments and collection fragments use the corresponding upstream
input helpers. Removed schema options are replaced by supported inline,
source-relative, or explicit-root selection. The upstream migration and format
references above own their exact rules. Successful construction alone is not
migration evidence: old root-level resources can become application data while
disappearing from PromptKit catalogs.
Request builders use the upstream input contract for validation replacements,
including optional repair budgets. Native resolved repair budgets, including
zero, and schema/hash evidence reach reports without a local substitute.
The upstream enabled repair default may add a generation call, latency, and
usage to application execution. Applications retain resource-version policy and
sensitivity decisions for their extension fields. The adoption also retains the
intervening PromptKit timeout and cancellation identity corrections.
Canonical GoDoc, CLI, consumer, developer, internal, and candidate release
guidance should agree with the completed integration. The maintained composed
example demonstrates shared loading and the native subtree adapter. Validation
protects CommandKit's acquisition, selection, adaptation, reporting, and outcomes;
upstream libraries own validation of their domain algorithms. Tests remain
offline and credential-independent.
The independently versioned integration releases explain the changed provider
API and breaking PromptKit migration under the [release policy](../policy/release.md).
The coordinated target is released ckconfig followed by ckprompt selecting that
release, with the downstream integration advancing at least its minor version.
The [release runbook](../release.md) owns preparation and publication operations.
Local workspace validation and isolated checks with a local dependency are
identified separately from independent validation against released requirements.
Any remaining release coordination stays recorded until completed.
No core release is needed solely for this adoption. Unrelated core work,
including the optional Scriptorium proposal, is not a prerequisite. The
[implementation plan](implementation.md) owns dependency migration, focused
coverage, candidate preparation, validation commands, and completion records.
## Scope retained outside this adoption
The existing [future work record](future.md) retains output-contract override
flags, appended-message flags, secrets-bootstrap commands, and other deferred
capabilities. ConfigKit v1.3.0's configured bootstrap and overwrite options remain
available to application startup code without a new CommandKit command.
This roadmap selects no new commands, engine-construction convenience API,
automatic configuration migration, core cache, or application execution workflow.
These are scope decisions for this adoption, not additional permanent prohibitions.
## Resolved decisions
### OD-1: Include the native-inspection adapter in this adoption — closed
Include the helper in the next ckconfig release, as part of this roadmap.
Its implementation overlaps the required native enumeration work; designing both
together provides a concrete second use of the shared boundary and avoids
revisiting that boundary immediately after release. Keep the adapter focused on
standard CLI scopes and direct upstream inspection. Preserve native comparison
semantics for the views accepted by the selected API.
The previous deferral recommendation is superseded.
### OD-2: Typed result loader, subtree path, and existing evidence handling — closed
Adopt the result-loader-plus-path approach described under
[public native-inspection adapter](#public-native-inspection-adapter).
Prioritize application simplicity, then ckconfig implementation simplicity, over
tailoring the inspection command's presentation. The complete result already
supplies source and diagnostic evidence; accepting the application's ordinary
loader avoids a new handoff envelope or application-owned adaptation layer.
Use native paths and comparison, retain whole-load diagnostics and failures,
and reuse existing reporting and outcome conventions. Keep the helper focused
on the selected task; do not add an options framework or another entry point for
arbitrary inspection views in this adoption. Supporting preselected views and
different root types would require a broader acquisition handoff and is not
needed for the selected application workflow.
## Execution status
The [staged implementation plan](implementation.md) records the completed local
work and validation evidence. The coordinated integration releases remain pending
as recorded in [future work](future.md#pending-integration-release-coordination).

View File

@@ -1,12 +1,38 @@
# Future work
Status — integration release coordination, optional shell validation, and future
capability proposals.
Status — pending release coordination, optional verification, and future capability proposals.
No delivery dates are selected here.
## Pending release coordination
Draft notes are prepared for [core v0.8.0](../releases/v0.8.0.md),
[ckconfig v0.11.0](../../integrations/ckconfig/docs/releases/v0.11.0.md), and
[ckprompt v0.12.0](../../integrations/ckprompt/docs/releases/v0.12.0.md).
These versions were unused locally and on origin when drafted. Finalize the
integration drafts while aligning their module requirements after dependency
publication; the notes do not identify already prepared integration candidates.
Automatic usage reporting and R1–R4 remediation are implemented. Publication is
separate follow-up work: release core, align and release ckconfig, then align and
release ckprompt with both published CommandKit dependencies under the
[release procedure](../release.md#scope-and-release-order). Integration module
requirements still select the earlier published versions. Update them during
release preparation and run independent integration suites against the new
published versions. Until then, unreleased integrations use the aligned workspace
or temporary local-source modfiles as described in the developer guide.
## 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
Earlier completed roadmaps, implementation plans, and review findings have been retired.
The completed automatic usage roadmap, implementation plan, and R1–R4 review
records remain available in their
[retirement snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/33f98db4f78f0b45ea89b0618203b1d947a89374/docs/roadmap).
This document preserves unfinished work and unselected ideas under the
[release policy](../policy/release.md#release-documentation-and-preparation).
The completed shared debug binding and reporting-mode implementation is recorded
@@ -38,22 +64,11 @@ govern any future implementation. The [CLI reference](../cli.md), public GoDoc,
and [consumer guide](../consumers/guide.md) own implemented behavior. Retaining
an idea here does not select its syntax, API, priority, or delivery date.
## Pending integration release coordination
The ConfigKit v1.4.0 and PromptKit v0.24.0 adoption is implemented locally;
publication remains separate. Follow the [release procedure](../release.md)
and obtain the required publication authorization. Prepare and release ckconfig
v0.10.0 first. Then select that actual release in ckprompt, tidy with real
checksums, update matching-version attribution, and run ckprompt's independent
default suite before preparing its v0.11.0 release. Core remains v0.7.0 for this
adoption. Candidate notes and planned versions must be checked again at release
time. Hosted delivery is separately authorized.
The current ckprompt checkout still requires published ckconfig v0.9.0, which
lacks the new path-reader API. Its aligned workspace and isolated local-replace
tests passed; those checks do not establish an independent build against the
published requirement. See the [implementation record](implementation.md) for
the validation evidence and upstream missing-file error-identity limitation.
The completed ConfigKit v1.4.0 and PromptKit v0.24.0 adoption, audit remediation,
and coordinated integration releases are preserved in the
[release snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/54e951e38a404b4338c7967ac39c6c01159bf76d/docs/roadmap).
ckconfig v0.10.0 and ckprompt v0.11.0 were published with hosted release pages;
ckprompt passed its independent suite against released ckconfig v0.10.0.
## Optional verification
@@ -138,6 +153,16 @@ remain unselected. Whole-run buffering to make failed runs show only errors
was also outside that scope. Any later extension needs a deliberate API and
presentation decision rather than assuming those behaviors are already provided.
### Usage reporting extensions
Machine-readable invocation usage output remains deferred pending a concrete
consumer need. Select its destination, framing, and format explicitly when that
work is undertaken; the current main result stream remains application-owned.
A separate usage-only installation API for applications without a nonempty
ckprompt suite, per-model breakdowns, event traces, and persistent usage history
also remain future proposals. None is required for the delivered aggregate usage
summary through normal installation.
### Release workflow extensions
Historical hosted-page backfilling and automated CI delivery remain separate

View File

@@ -1,444 +0,0 @@
# ConfigKit and PromptKit adoption implementation plan
Status: implementation complete; coordinated releases pending. Prepared 2026-11-21.
Implementation baseline: `320526d3fc92fac7795b4b5e65c623181680452d`.
## Authority and execution
Implement the accepted [feature roadmap](configkit-v1.4.0-promptkit-v0.24.0.md)
in the numbered order below. That document owns intent, scope, upstream targets,
and resolved decisions. This plan selects the API shape, implementation steps,
and completion evidence for a Luna coding agent.
Read [development guidance](../development.md), the applicable policies in its
reading guide, and ADRs [0003](../adr/0003-configuration-scopes.md) and
[0004](../adr/0004-optional-integration-modules.md). Prefer the codebase knowledge
graph for code discovery. Inspect the actual worktree before editing and preserve
unrelated work, ignored workspace files, and local credentials.
This is one end-to-end implementation sprint. Continue through all stages without
intermediate approval or compilation gates. Earlier stages may temporarily fail
to build while later migrations are pending. Resolve failures before declaring
the implementation complete. After a focused unit is complete, record its actual
evidence here and commit it under the [agent policy](../policy/agents.md).
Do not create empty commits or claim checks that have not run.
Implementation approval authorizes the implementation and local commits. Source
publication and hosted delivery follow the [release procedure](../release.md)
when separately authorized. Publication is follow-up coordination, not an internal
gate in this sprint. Stage 7 defines honest pre-publication validation when
ckprompt needs the new, still-unpublished ckconfig API.
Use the existing command families, reporters, classification, and provider
lifetimes. Keep domain resolution, schemas, validation, preparation, redaction,
and comparison upstream. Do not add a core cache, new commands, constructor
wrapper, arbitrary-view adapter, cross-root-type loader API, or options framework
for this adoption. The roadmap's scope choices do not establish permanent bans.
## Stage 1: Select the released upstream dependencies
Status: complete.
Evidence: With Go 1.27.4 and the workspace disabled, selected the specified
versions using `go get`, ran `go mod tidy` and `go mod download` in both
integrations, and reviewed the module graphs, checksums, and selected upstream
copyright and license material. The upstream license texts match the previously
selected versions; the remaining selected transitive versions are unchanged.
Updated both integration attribution entries. The existing workspace includes
all three modules. The independent ckconfig suite passed. The ckprompt suite
currently fails on removed `WithSchemaFile` and unmigrated composed-example
resources; those migrations are assigned to Stages 4 and 5.
1. With Go 1.27.4 on `PATH`, update ConfigKit to v1.4.0 in both integration
modules and PromptKit to v0.24.0 in ckprompt. Keep core v0.7.0, the root
module's requirements, and the consumer minimum of Go 1.27.0 unless an actual
dependency requirement demonstrates a necessary change.
2. Prepare dependencies from each integration directory using `GOWORK=off
GOTOOLCHAIN=local go get` for these exact versions, then download/tidy actual
dependencies and review the resulting requirements and checksums. Leave
ckprompt's ckconfig requirement at published v0.9.0 until the new ckconfig
is published. Do not record a fictitious future checksum or commit a local
replacement to make the new API appear published. Repeat tidy after source
migration if temporary compilation errors prevent it now.
3. Use the existing ignored workspace containing the root and both integrations
for development. Preserve it, or create it following the developer guide if
absent. Do not depend on sibling upstream checkouts.
4. Review the selected upstream license and notice material and update affected
module-local and root attribution entries under the [OSS policy](../policy/oss.md).
ConfigKit's selected source is `4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3`;
PromptKit's is `5ea60e9b96651fd7dfcbc7d05b6f43d131df358f`. Update changed
transitive entries only where the selected graphs warrant it. Finalize graph
and notice review after the migrations; no unrelated dependency sweep.
Completion evidence: reviewed integration module diffs and genuine sums selecting
the two target releases. Record any temporary test/build failures as migration
work for subsequent stages, not reasons to stop.
## Stage 2: Separate native path enumeration from metadata lookup
Status: complete.
Evidence: Added the optional native path reader and metadata fallback, populated
whole-result views, and exercised selected candidates, empty readers, the legacy
fallback, and discovery filters alongside existing missing-metadata coverage.
`GOWORK=off GOTOOLCHAIN=local go test ./...` passed in ckconfig with Go 1.27.4.
Primary files: [contracts.go](../../integrations/ckconfig/contracts.go),
[explain.go](../../integrations/ckconfig/explain.go), and
[configkit_adapter.go](../../integrations/ckconfig/configkit_adapter.go).
1. Add this narrow public capability alongside the existing reader interfaces:
```go
type PathReader interface {
HistoricalPaths() []configkit.Path
}
```
Add `Paths PathReader` to `View`. It supplies the native discovery candidates.
`Metadata` continues to supply presence, explicitness, and history. Update
GoDoc for `View`, `PathReader`, and `ScopeFeatures.PathDiscovery` together.
2. In `runConfigExplanation` listing mode, retain the metadata requirement.
Enumerate `View.Paths.HistoricalPaths()` when `Paths` is nonnil; otherwise
enumerate `View.Metadata.HistoricalPaths()` for existing custom providers.
A nonnil reader returning nil or an empty slice means an empty native list,
and must not trigger the fallback. Apply the existing `--under`,
`--historical`, and `--explicit` filters to those candidates using metadata.
Keep explicit-path handling on `ExplanationReader`.
3. Populate whole-result `FromConfigKit` views with their metadata as the path
reader. Keep native paths and existing report projection. This change does
not require new sorting, deduplication, path rebasing, or metadata copying.
4. Extend existing discovery tests with a reader whose candidates exclude a
real metadata sibling, a valid empty reader, and the legacy nil-reader
fallback. Exercise the existing filter meanings on supplied candidates.
Retain missing-metadata failure coverage instead of creating a second path
metadata model.
Completion evidence: focused ckconfig discovery coverage proves that enumeration
comes from the supplied capability while metadata still describes each path.
Existing whole-result discovery remains supported.
## Stage 3: Add the typed-result subtree scope adapter
Status: complete.
Evidence: Added the typed loader and native subtree adapter, sharing acquisition
and comparison coordination with the whole-result adapter. Offline scope and CLI
tests cover focused output and paths, explicit outside-focus explanations,
whole-load warnings and failures, error identity, absence and null, unavailable
inspection, and native comparison including an atomic ancestor. The independent
ckconfig suite passed with Go 1.27.4 and `GOWORK=off GOTOOLCHAIN=local`.
Add the following public sibling of `FromConfigKit` in the ckconfig package:
```go
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]
```
1. Declare the same operations and path features as `FromConfigKit`. Retain its
application-owned loader, input/state, selection, and operation-list
customization conventions. Attach a nil-loader construction error with
`WithScopeError`; declaration/help/discovery must not invoke loading.
2. Share ordinary result acquisition and diagnostic adaptation with
`FromConfigKit` through a small private helper. Preserve the existing
handling of `LoadError`, nonnil results accompanying other errors, nil-result
failures, findings, sources, and terminal explanations. A successful result
remains the source of whole-load diagnostics. Do not expose a new envelope
or callback framework to applications.
3. After successful loading, call `result.InspectSubtree(path)`. Use the returned
inspection for `Effective`, `Explanation`, and `Paths`, and its whole-load
metadata and sources for the corresponding fields. Keep `Findings` from the
result. If selection returns `false`, return a contextual operational error
with the already acquired source/diagnostic evidence. This covers invalid
paths and results without captured inspection. Do not classify an unavailable
view as invalid user configuration without supporting native evidence.
4. A valid absent scope is a successful acquisition, not an unavailable view.
Let its native writer report an unavailable effective value through existing
show/render delivery handling. Preserve explicit null. Explicit queries,
including root and paths outside the focus, continue to use native semantics.
5. Reuse `loadComparisonSide` and the existing pair-loading cancellation and
diagnostic accumulation conventions. Extract the common pair-acquisition
portion privately if needed to avoid duplicating that coordination. Select
the same path from both successful results and call `leftView.Diff(rightView)`.
Preserve existing left/right selection inputs, shared state, warnings,
explanations, cause wrapping, and checks before the next acquisition or diff.
Do not filter native ancestor differences or compare rendered YAML.
Keep ordinary `FromConfigKit` on its existing same-type `configkit.Diff`.
6. Add focused public-scope/CLI coverage, using real offline ConfigKit results:
focused show/list/explain with a sibling outside the focus; native diff with
distinct selections; whole-load warnings and failed-load findings outside
the focus; and error identity/outcomes for loader failure. Reuse existing
evidence and delivery tests where they already protect the shared path.
Cover valid absence versus null and unavailable inspection without building
an upstream inspection conformance suite. Compare representative diff values
to native results, including a retained atomic ancestor where applicable.
Completion evidence: standard scope commands expose a native subtree using only
the ordinary typed loader and path. Whole-load failures remain failures and
available evidence survives adaptation. Exported GoDoc describes this handoff.
## Stage 4: Migrate ckprompt adapters, fixtures, and boundary coverage
Status: complete.
Evidence: Migrated discovered settings fragments to `/promptkit`, exposed native
inspection paths, and added shared-load, requirements, schema, prepared-hash,
and request-replacement coverage. `GOTOOLCHAIN=local go test
./integrations/ckprompt` passed in the aligned workspace with Go 1.27.4. The
missing-main-file constructor retains PromptKit's invalid-config identity and
produces an operational outcome with native load diagnostics. ConfigKit's
`LoadError` explicitly does not unwrap underlying filesystem errors, so this
native error cannot also match `os.ErrNotExist` as originally anticipated;
the separate joined-error case verifies forwarding of that identity when supplied.
The composed example migration remains in Stage 5.
Primary files: [adapters.go](../../integrations/ckprompt/adapters.go), the
integration's existing configuration/comparison/preparation/requirements tests,
and [constructor outcomes](../../integrations/ckprompt/constructor_outcomes_test.go).
1. Set successful `ConfigScope` views' `Paths` directly to PromptKit's native
`ConfigurationInspection`. Retain its native effective writer, explanation,
full metadata, sources, diagnostics, and native comparison. Do not convert
it into a ConfigKit result to route it through the new adapter.
2. Migrate complete-document test/configuration mappings beneath `promptkit`.
Mount wrapperless fragments through `SettingsInput`, and collection fragments
through `CollectionInput`. Discovery-produced fragments require an explicit
destination when they are not whole documents. Update override paths,
explanation assertions, and comparison paths to native locations such as
`/promptkit/profiles/0/model`; resource IDs and references retain their names.
Review inline maps, byte strings, embedded files, and filesystem fixtures,
not just YAML files. In particular review composition and comparison fixtures.
3. Replace any `Config.SchemaDir`, `WithSchemaFS`, or `WithSchemaFile` uses with
the selected release's supported schema configuration/resource contexts.
In `TestPromptConstructorFailurePrecedence`, replace the missing-schema
constructor with a missing main configuration file passed to `NewEngine`.
Retain the intended operational outcome and `os.ErrNotExist`/PromptKit cause
identity checks, plus joined-error and cancellation precedence. Retain the
real malformed companion-YAML regression and its structured load evidence.
Schema-file failures now belong to preparation, so exercise their forwarding
there only where needed to protect a distinct adapter path.
4. Migrate request-builder replacements to `*promptkit.OutputContractInput`
wherever used. Forward the whole replacement with pointer-valued repair
budgets; omitted stays omitted and explicit zero stays zero. Do not insert
the former repair default. Keep ordinary `OutputContract` uses for resolved
prepared results where that is the upstream type.
5. Keep prompt and prepared values on the existing native reporting path.
Extend focused report tests to compare native returned inline/reference
schema fields, repair-budget zero, and `message_content_hash` with CLI report
values. Preserve text/JSON/YAML behavior through shared serialization tests
and a small representative format selection, not an exhaustive cross-product
of fields and formats. Do not calculate expected hashes locally.
6. Verify requirements projections preserve the native result, including input
metadata supplied by application defaults. Keep preparation, validation,
namespace, smoke, cancellation, diagnostic, and outcome adaptation semantics.
Use existing boundary tests for supported error identities; PromptKit owns
tests of its v0.23.3 HTTP timeout/cancellation algorithms.
7. Add a shared-load fixture with a genuine application sibling outside
`/promptkit`. Through `ConfigScope`, prove list candidates follow native
`HistoricalPaths`, filters still apply, explicit outside-focus paths retain
native behavior, and full source/diagnostic evidence remains available.
Expected values come from native inspection rather than a local scope filter.
Completion evidence: migrated ckprompt package coverage passes in the aligned
workspace and resource-selection assertions detect silently unmigrated catalogs.
The composed example is completed in Stage 5.
## Stage 5: Demonstrate shared loading and the subtree adapter
Status: complete.
Evidence: The composed example loads application defaults, bundled and local
resources, campaign-derived settings, and storage in one ConfigKit result;
the engine consumes that result and the storage scope uses the subtree adapter.
Updated fixtures and tests exercise native paths, shared inspection and reuse,
storage show/explain/diff and overrides, whole-load failure evidence, and the
existing campaign, comparison, catalog, and lifecycle cases. With Go 1.27.4,
`GOTOOLCHAIN=local go test ./integrations/ckprompt/examples/composed` passed in
the aligned workspace.
Update the maintained [composed example](../../integrations/ckprompt/examples/composed/main.go),
its fixtures, and its existing tests. A separate consumer example is unnecessary.
1. Add `PromptKit promptkit.Settings` with `yaml:"promptkit"` to
`appConfiguration`, plus an illustrative typed `storage` section. Keep the
existing campaign data, selector presence, request-builder, session outcome,
alias, completion, and injected-client demonstrations.
2. Move the example's generated resources into the application load. Compose
its definition using `promptkit.Configure` with the settings selector.
Supply the existing local collection and common prompt resources as an
application-owned mapping underlay beneath `promptkit`, so selecting a main
fixture retains the example resources. Keep application defaults in the
application definition. Retain the example's bundled OpenRouter catalog
by selecting `BundledOpenRouterUnderlay()` before this load, once in its input
composition. Engine construction must not perform a second configuration load.
3. Derive campaign-specific profiles and prompt defaults during the application
definition's resolve callback, before PromptKit's composed resolve callback.
Use ConfigKit's resolution recording helpers for changes, with native
`/promptkit/...` paths and relevant campaign dependencies. This keeps frozen
inspection and engine settings consistent. Do not mutate the completed
result's settings to inject a campaign before handing it to the engine.
Preserve existing campaign selection and override precedence, including
explicit empty selections and native conflicting-override errors.
4. Keep `loadApplicationConfig` as the ordinary result loader, retaining its
application-owned successful-result reuse keyed by the full selection and
campaign presence/value. Keep failed loads out of that reuse. In
`loadPromptEngine`, pass that result directly to `promptkit.NewFromConfig`
with `RuntimeConfig` and the existing injected LLM client. Remove the separate
PromptKit source reconstruction and `NewEngine` call from this shared path.
Keep standalone `NewEngine` fixtures elsewhere as supported usage.
5. Register a `storage` scope with `FromConfigKitSubtree`, the existing result
loader, and `configkit.Keys("storage")`. Enable overrides for this scope
because that loader supports them. Apply the existing campaign selector and
its comparison counterpart to this scope as well; retain the app-only limit
selector and input checks. Keep PromptKit scope capability declarations at
their existing supported settings; shared loading itself does not require
expanding its advertised override modes.
6. Give before/after fixtures distinct storage values while retaining campaign
differences. Extend existing tests to demonstrate subtree show/explanation
and comparison through the standard commands and available failed-load
diagnostics. Use package-level adapter tests for the fuller evidence matrix.
Update `--scope all` expectations to include the new application scope and
the fact that the `app` whole-result view now includes PromptKit settings.
7. Retain tests distinguishing left/right configuration, campaigns, overrides,
and repeated invocation state. Confirm help/completion do not acquire an
engine, catalogs still contain selected IDs, and preparation does not call
the LLM client. Smoke examples use the existing local injected client.
Test successful reuse as example behavior, without creating a library-wide
exact-load-count contract or redesigning its small cache.
Completion evidence: existing composed-example coverage plus focused subtree
cases passes offline. Both scope adapters consume the same application-owned
result for corresponding selections, and comparison sides remain independent.
## Stage 6: Update canonical guidance and candidate release notes
Status: complete.
Evidence: Updated GoDoc, CLI, consumer, development, internal, and composed
example guidance, plus candidate notes for ckconfig v0.10.0 and ckprompt
v0.11.0. Neither candidate tag exists locally or on `origin`. Reviewed selected
module graphs and upstream license material; affected attribution was updated
in Stage 1 and no transitive version changed. Local Markdown links and fragments
passed a repository link check, `git diff --check` passed, and the ckprompt
workspace suite including the example passed with Go 1.27.4. Publication and
the ckprompt released-dependency update remain pending.
1. Finish exported GoDoc and package guidance in both integrations. Document
`View.Paths` precedence and metadata fallback, the subtree helper signature,
typed loader ownership, whole-load validation/evidence, and native path/diff
behavior. Keep exact upstream format rules linked to the selected releases.
2. Update [CLI guidance](../cli.md) for native scoped listings and explicit paths,
focused rendering, source evidence, and comparison. Update the
[consumer guide](../consumers/guide.md) with the maintained shared-load and
storage-scope example, upstream migration links, and request-builder changes.
Update [development guidance](../development.md) and internal documentation
where the changed mechanics affect them. Describe the local development
dependency state accurately until release coordination is finished.
3. Write candidate notes for ckconfig v0.10.0 and ckprompt v0.11.0. These are the
next minor targets from the reviewed v0.9.0/v0.10.0 baselines. Check existing
notes/tags before creating them; if another release has consumed either
target, use the next appropriate fresh minor and adjust candidate references.
The release command performs authoritative publication guards later.
4. The ckconfig note covers the new adapter and optional reader. Adding a public
`View` field can require migration of positional struct literals; recommend
keyed fields and explain the metadata fallback for existing custom scopes.
The ckprompt note covers the upstream breaking configuration/API migration,
native path changes, removed schema options and explicit schema roots,
`OutputContractInput`, resolved repair-budget zero/defaults, new prepared
evidence, and whole-load context. Mention possible extra generation latency
and usage from upstream's enabled repair default. Include positional
`PreparedRun` literal migration and older JSON's missing-hash behavior where
relevant, linking upstream for its exact contract.
5. Preserve upstream ownership of resource-version policy and extension-field
sensitivity. Keep unrelated deferred CLI capabilities in `future.md`.
Add the required module-specific immutable release footer to each candidate
note. Do not rewrite previously published notes or tags.
6. Finalize affected attribution against the selected module graphs. Review prose
diffs, local links/fragments, copied notices, commands, examples, and future
tag URL paths under the documentation/OSS policies. Published compatibility
tables must distinguish available releases from these candidates.
Completion evidence: canonical guidance and candidate notes agree with the
implemented APIs and examples, have valid local navigation, and describe the
remaining dependency release coordination without claiming publication.
## Stage 7: Validate the result and record release coordination
Status: complete.
Evidence: With Go 1.27.4, `GOWORK=off GOTOOLCHAIN=local go test ./...`
passed separately in core and ckconfig; ckconfig `go mod tidy` and `go mod
download` completed without further changes. From the root, the aligned
workspace commands `GOTOOLCHAIN=local go test ./...`, `go test
./integrations/ckconfig/...`, and `go test ./integrations/ckprompt/...` all
passed. For isolated ckprompt validation, copied its module files to a temporary
directory, replaced ckconfig with the local module only in that temporary
modfile, ran tidy and `GOWORK=off GOTOOLCHAIN=local go test -modfile=... ./...`,
and removed the temporary files; both package and example passed. This is not
independent validation against the published ckconfig v0.9.0 requirement.
Reviewed the module and attribution diffs, focused evidence, prose whitespace,
and local links and fragments. No core optional dependencies were introduced.
The remaining release order and dependency validation are recorded in
[future work](future.md#pending-integration-release-coordination). The Stage 4
record explains the upstream missing-file error-identity limitation.
1. Format changed Go files, finish tidy/download with the workspace disabled
where the module can resolve its selected APIs, and inspect all module and
attribution diffs. Keep downloaded checksum evidence real. Root should not
acquire optional integration dependencies.
2. With Go 1.27.4 selected, run the complete affected independent/default suites
and the aligned workspace suites. From the root, use these commands:
```sh
(cd integrations/ckconfig && GOWORK=off GOTOOLCHAIN=local go test ./...)
GOTOOLCHAIN=local go test ./...
GOTOOLCHAIN=local go test ./integrations/ckconfig/...
GOTOOLCHAIN=local go test ./integrations/ckprompt/...
```
Run ckprompt's ordinary independent suite once its required ckconfig release
is selected. Before publication, that suite cannot resolve the new API from
its v0.9.0 requirement. For isolated development validation, copy
ckprompt's `go.mod` and matching `go.sum` to a temporary directory, add a
temporary `replace go.maximumdirect.net/ckconfig => ABSOLUTE_LOCAL_CKCONFIG`
with `go mod edit -modfile=...`, and run tidy and `GOWORK=off GOTOOLCHAIN=local
go test -modfile=... ./...` from the ckprompt directory. Remove the temporary
files afterward. Label this result as isolated validation against local
ckconfig, not independent validation against its published requirements.
Do not block subsequent sprint work on the publication dependency.
3. Review focused evidence from Stages 2–5 against the roadmap's targeted end
state. Reuse successful checks for unchanged content. No performance
benchmarks, live provider calls, new CI gates, or mandatory expanded matrices
are needed for this adoption. Investigate concrete failures and rerun the
affected checks after fixes.
4. Run prose whitespace checks and validate affected local links/fragments,
including new notes. Review intended new files as well as tracked diffs.
Record actual commands, outcomes, and any remaining independent-dependency
limitation here; do not mark unrun checks passed.
5. Record pending release coordination in `future.md` before retiring any
completed planning records. Keep this plan's implementation completion
separate from publication status. The follow-up order is ckconfig first,
then ckprompt with that actual released ckconfig selected, real sums/tidy,
updated matching-version attribution, and its independent default suite.
Core remains v0.7.0 for this scope. Follow the runbook for candidate commits,
authorized pushes/tags, and separately authorized hosted delivery. The release
command runs candidate validation itself; no duplicate mandatory preflight.
6. Review and commit the completed implementation units and records under the
agent policy. Report changed APIs and migration requirements, tests and their
limits, commit identifiers, and the pending coordinated integration releases.
Do not pause midway for an approval already covered by implementation scope.
Completion evidence: all implementation-stage work is finished, focused and
workspace checks pass, ckconfig passes independently, documentation is validated,
and any ckprompt published-dependency validation still awaiting release is
explicitly recorded. Eventual adoption completion includes both coordinated
releases; this sprint does not claim that follow-up has occurred.
## Open Questions
None. The feature roadmap resolves product scope and adapter direction; this
plan selects the remaining API, migration, example, and validation approach.

View File

@@ -1,100 +0,0 @@
# ConfigKit and PromptKit adoption review
Reviewed revision: `e70a0ef301a3d34f64a6cba86dd68b728436534d`.
Status: all findings addressed. Reviewed and remediated 2026-11-21.
## Scope and results
Reviewed all seven stages of the [implementation plan](implementation.md)
against the accepted [feature roadmap](configkit-v1.4.0-promptkit-v0.24.0.md),
the implementation, changed tests, and documentation.
| Stage | Review result |
| --- | --- |
| 1 — Dependencies | Both integrations select ConfigKit v1.4.0; ckprompt selects PromptKit v0.24.0. Core and the Go minimum remain at the planned versions. Changed attribution identifies the selected upstream commits. |
| 2 — Native path enumeration | Optional `View.Paths` and the metadata fallback preserve the distinction between an unavailable reader and an empty native list. Existing metadata-backed filters remain in use. |
| 3 — Subtree adapter | The typed loader/path API shares acquisition and diagnostics, delegates focused inspection and comparison, and retains whole-load evidence and native ancestor differences. |
| 4 — PromptKit migration | Native inspection supplies the new path capability; fixtures use the new destinations. Native schema, repair-budget, hash, requirements, and supported error evidence pass through the existing adapters. |
| 5 — Shared-load example | Shared loading and storage scope wiring are present. The campaign prompt-ID defect identified in R1 has been corrected. |
| 6 — Documentation | Current guidance and candidate notes describe the new APIs and migration, distinguishing candidates from published dependencies. |
| 7 — Validation and coordination | Workspace and isolated-local-dependency checks pass. The ckprompt released-dependency limitation and coordinated releases are explicitly pending as planned. |
No additional strengthened contract, prohibition, or guarantee requiring
remediation was identified. The recorded ConfigKit filesystem-error identity
limitation follows the upstream error contract and is not an integration defect.
## R1 — Campaign prompt-ID changes fail configuration resolution
Priority: P2. Status: completed 2026-11-21.
Completion: the resolver now records prompt-ID normalization at the collection
path, retaining the existing reason and campaign dependencies. Added
`TestComposedCampaignPromptID` for a main configuration selecting `custom`;
it verifies successful loading, matching application/engine inspection values,
and the selected ID in the CLI catalog. The test failed before the fix and
passed afterward. The original override reproduction also now succeeds.
Relevant code: the application resolve callback in
[`loadApplicationConfig`](../../integrations/ckprompt/examples/composed/main.go),
particularly the prompt-ID assignment and resolution record at lines 136–138.
This is maintained example code; the generic scope adapters are not the cause.
When the selected campaign's `prompt_id` differs from `briefing`, the callback
renames the example's default prompt. It records normalization only at
`/promptkit/prompts/<index>/id`. `promptkit.Configure` registers this list as an
identified sequence. Changing an identity changes collection membership, which
requires a record covering the list or an ancestor under ConfigKit's
[resolution contract](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3/docs/config.md).
The leaf record does not cover that change.
Reproduced from `integrations/ckprompt/examples/composed` with Go 1.27.4 and the
aligned workspace:
```sh
GOTOOLCHAIN=local go run . config validate --scope app \
--set '/campaigns/spring/prompt_id="custom"' --format json
```
Actual behavior: loading fails with `resolve.unrecorded_change` at
`/promptkit/prompts`, the report marks the app scope failed, and the application
exits with status 1. The same failure occurs when a main configuration selects
that campaign prompt ID. Because resolution is shared, it also prevents engine
construction and inspection through other scopes for that configuration.
Expected behavior: the application result and engine expose the selected valid
campaign prompt ID, with a correctly recorded derivation. The earlier example
constructed the prompt with `chosen.PromptID`; Stage 5 requires preservation of
campaign selection while moving its derivation into the shared load. Neither
the campaign configuration nor the roadmap restricts the ID to `briefing`.
Remediation: record the membership change at `promptPath`
(`/promptkit/prompts`) when renaming the prompt, retaining the campaign
dependencies and reason. Alternatively, restructure campaign prompt derivation
to create/select the intended entry and record any collection membership change
at that same native collection boundary. Keep ConfigKit's audit enabled and
preserve application selection; restricting IDs to the hard-coded default would
hide the regression.
Extend the existing composed-example coverage with a non-default campaign
prompt ID. Verify successful loading, the selected resource in the catalog, and
agreement between shared inspection and engine inspection. Existing fixtures
all select `briefing`, so their passing results do not exercise this branch.
## Verification
With Go 1.27.4, the core and ckconfig independent default suites passed. All
three aligned workspace suites passed, including maintained examples. ckprompt's
isolated default suite also passed with an external temporary modfile replacing
only ckconfig with the local module; the repository module files were unchanged.
That result does not establish an independent build against the still-selected
published ckconfig v0.9.0, as already recorded in
[release coordination](future.md#pending-integration-release-coordination).
At review time the R1 reproduction failed despite those passing suites; the
review itself changed no production code or tests.
After remediation, `GOTOOLCHAIN=local go test ./integrations/ckprompt/...
-count=1` passed with Go 1.27.4, including the composed example and regression.
The isolated ckprompt suite with a temporary local ckconfig replacement also
passed. The original override command now reports a valid app scope and exits
successfully. The published-dependency release coordination remains unchanged.

View File

@@ -43,8 +43,13 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco
var outcome Outcome
path := parsed.Path
handlerRan := false
payload := routedSnapshot.runners[parsed.Key]
featureRequired := !parsed.HelpRequested && current.route.kind == routeCanonical &&
payload != nil && payload.hasRun() && !routedSnapshot.builtins[parsed.Key]
if parsed.Failure != nil {
outcome = Usage(parsed.Failure.Message)
} else if err := current.prepareFeatures(&parsed, featureRequired); err != nil {
outcome = classifyInputError(err)
} else if current.route.kind == routeDiscovery {
if parsed.HelpRequested {
outcome = current.renderHelp(parsed.Path)
@@ -70,6 +75,7 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco
outcome = classifyInputError(err)
} else {
handlerRan = true
current.featureEnabled = !routedSnapshot.builtins[parsed.Key]
outcome = run(current)
}
}
@@ -77,16 +83,75 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco
return current.finalize(outcome, path, handlerRan)
}
func (current *execution) prepareFeatures(parsed *commandmeta.Result, required bool) error {
if current.snapshot == nil {
return nil
}
// Partition the canonical occurrence stream once. Positions within each owner
// remain dense and preserve alias/interleaved binding order.
owners := make(map[string]int, len(current.snapshot.featureFlags))
counts := make([]int, len(current.snapshot.features))
for i, feature := range current.snapshot.features {
flags := feature.payload.bridgeFlags()
counts[i] = len(flags)
for _, flag := range flags {
owners[flag.Name] = i + 1
}
}
occurrences := make([][]commandmeta.FlagOccurrence, len(counts)+1)
for _, occurrence := range parsed.FlagOccurrences {
owner := owners[occurrence.Name]
occurrences[owner] = append(occurrences[owner], occurrence)
}
parsed.FlagOccurrences = occurrences[0]
offset := 0
for i, feature := range current.snapshot.features {
count := counts[i]
if offset+count > len(parsed.InvocationFlagValues) || offset+count > len(parsed.InvocationFlagSpellings) {
return fmt.Errorf("missing invocation feature flag values")
}
start, err := feature.payload.prepare(parsed.InvocationFlagValues[offset:offset+count], parsed.InvocationFlagSpellings[offset:offset+count], occurrences[i+1], false)
if err != nil {
return err
}
if required && current.featureRequiredError == nil {
current.featureRequiredError = feature.payload.requiredError(parsed.InvocationFlagValues[offset : offset+count])
}
current.featureStarts = append(current.featureStarts, start)
offset += count
}
return nil
}
type execution struct {
app *App
ctx context.Context
reporter *Reporter
featureStarts []func(Invocation) (context.Context, func() Report)
featureRequiredError error
featureEnabled bool
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 {
invocation Invocation
renderHelpTargetsFunc func([]string) Outcome
@@ -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))
}
}
return current.reporter.finalize(outcome, completion)
return current.reporter.finalize(outcome, completion, current.featureReports...)
}
func (current *execution) usageText(path []string) string {

View File

@@ -26,6 +26,7 @@ type flagAliasMapping struct {
type flagAliasContext struct {
path commandpath.Path
canonical map[string]capturedFlagSpelling
invocation map[string]capturedFlagSpelling
discovery bool
}
@@ -64,10 +65,28 @@ func (spelling capturedFlagSpelling) token() string {
return "--" + spelling.name
}
func (context flagAliasContext) canonicalSpelling(key string) (capturedFlagSpelling, bool) {
if value, ok := context.canonical[key]; ok {
return value, true
}
value, ok := context.invocation[key]
return value, ok
}
func invocationFlagSpellings(flags []commandmeta.Flag) map[string]capturedFlagSpelling {
result := make(map[string]capturedFlagSpelling, len(flags))
for _, flag := range flags {
for _, spelling := range featureSpellings(flag) {
result[flagSpellingKey(spelling)] = spelling
}
}
return result
}
func compileFlagAliases(rules []RoutingRule, roots map[string]*canonicalNode, aliases interface {
Resolve(commandpath.Path) commandpath.Path
ProperSourcePrefixes() []commandpath.Path
}) (map[string]resolvedFlagAliases, map[string]resolvedFlagAliases, error) {
}, features []commandmeta.Flag) (map[string]resolvedFlagAliases, map[string]resolvedFlagAliases, error) {
canonicalNodes := indexCanonicalNodes(roots)
global := make(map[string]flagAliasMapping)
scoped := make(map[string]map[string]flagAliasMapping)
@@ -97,6 +116,13 @@ func compileFlagAliases(rules []RoutingRule, roots map[string]*canonicalNode, al
canonicalContexts[key] = flagAliasContext{path: node.path.Clone(), canonical: canonicalFlagSpellings(node.command)}
}
discoveryContexts := discoverFlagContexts(rules, roots, aliases, canonicalNodes)
shared := invocationFlagSpellings(features)
for _, contexts := range []map[string]flagAliasContext{canonicalContexts, discoveryContexts} {
for key, context := range contexts {
context.invocation = shared
contexts[key] = context
}
}
canonicalKeys := sortedContextKeys(canonicalContexts)
resolvedCanonical := make(map[string]resolvedFlagAliases, len(canonicalContexts))
@@ -236,7 +262,7 @@ func resolveFlagAliases(context flagAliasContext, mappings map[string]flagAliasM
var resolve func(capturedFlagSpelling) (terminal, error)
resolve = func(current capturedFlagSpelling) (terminal, error) {
key := flagSpellingKey(current)
if endpoint, exists := context.canonical[key]; exists {
if endpoint, exists := context.canonicalSpelling(key); exists {
return terminal{spelling: endpoint, active: true}, nil
}
if result, exists := resolved[key]; exists {
@@ -279,7 +305,7 @@ func resolveFlagAliases(context flagAliasContext, mappings map[string]flagAliasM
}
continue
}
if _, collision := context.canonical[sourceKey]; collision {
if _, collision := context.canonicalSpelling(sourceKey); collision {
return resolvedFlagAliases{}, fmt.Errorf("flag alias %s conflicts with a canonical spelling in %s", source.token(), flagContextDescription(context))
}
result.bySpelling[sourceKey] = resolvedFlagAlias{source: source, target: terminal.spelling}

View File

@@ -17,6 +17,7 @@ func (a *App) helpView(route routeResult, snapshot *routingSnapshot) commandmeta
if snapshot == nil {
return view
}
view.CoreFlags = append(append([]commandmeta.Flag(nil), snapshot.featureFlags...), view.CoreFlags...)
view.CommandAliases = routeHelpAliases(snapshot, route)
if view.Discovery {
view.FlagAliases = snapshot.discoveryFlags[route.discoveryPath.Key()].neutralRecords()

View File

@@ -0,0 +1,28 @@
# 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
The coordinated release targets 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.
Draft preparation: after core v0.8.0 is published, align this module's core
requirement and run its independent suite with the workspace disabled before
publication. The current checkout still selects the prior published core.
ckprompt v0.12.0 follows this release under the dependency-alignment policy.
See the [consumer guide](../../../../docs/consumers/guide.md#configkit-scopes).
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.11.0/integrations/ckconfig/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.11.0/integrations/ckconfig/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckconfig/v0.11.0/integrations/ckconfig/docs/oss/attribution.md)

View File

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

View File

@@ -150,7 +150,13 @@ func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operatio
if input == nil {
return fmt.Errorf("configuration input must not be nil")
}
return prepareConfigOperation(prepared, operation, input)
if err := prepareConfigOperation(prepared, operation, input); err != nil {
return err
}
if input.plan.help {
return commandkit.ErrHelpRequested
}
return nil
},
Run: func(invocation commandkit.Invocation, input *configCommandInput[I, S]) commandkit.Outcome {
return runConfigOperation(invocation, operation, input)

View File

@@ -41,3 +41,10 @@ This module is licensed under the [GNU Lesser General Public License v3.0 or
later](COPYRIGHT). The accompanying [LICENSE](LICENSE) contains the full LGPL
v3 and GPL v3 texts. See [third-party attribution](docs/oss/attribution.md)
for incorporated and dependency notices.
Smoke-test reports default to text; use `--format yaml` or `--format json` for
structured output. Reports preserve native reasoning-token and cache-hit evidence.
Backend provider conventions are selected explicitly in PromptKit configuration;
for example, application-defined OpenRouter backends need `provider: openrouter`.
See the [PromptKit backend format](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/formats.md#backend-definitions)
for provider and zero-cost settings.

View File

@@ -129,7 +129,7 @@ func buildCommand[I, S any](suite Suite[I, S], aliases *[]commandkit.Declaration
for _, issue := range suite.issues {
command = commandkit.WithError(command, issue)
}
return command
return commandkit.WithInvocationFeature(command, usageFeature())
}
func newCatalogListCommand[I, S any](suite Suite[I, S], name string) commandkit.Command {

View File

@@ -7,6 +7,12 @@
// family; Declarations also includes its convenience flag aliases. Install
// these with commandkit.New or App.Register.
//
// A nonempty family installs --show-tokens for application commands as well as
// PromptKit commands. When requested, it observes PromptKit calls using the
// invocation context and reports usage on diagnostics after execution. Applications
// must pass that context to their work and wait for their own work before returning.
// Empty suites install no flag. Smoke-test usage remains in the command report.
//
// ConfigScope separately exposes engine configuration through ckconfig.
// ConfigScope preserves PromptKit focused discovery and whole-load evidence.
// Applications can compose PromptKit settings into an application-owned load

View File

@@ -2,16 +2,16 @@
## PromptKit
Selected module: `go.maximumdirect.net/promptkit` at `v0.24.0`.
Selected module: `go.maximumdirect.net/promptkit` at `v0.25.0`.
Copyright (C) 2026 Eric Rakestraw
SPDX-License-Identifier: LGPL-3.0-or-later
License and notices: [LGPL v3.0](../../LICENSE) |
[LICENSE](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/LICENSE).
[LICENSE](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/LICENSE).
[Source](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f).
[Source](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d).
## ConfigKit

View 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)

View File

@@ -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
exercises their current sources; follow the [workspace setup](../../../../docs/development.md#documentation-validation)
from the repository root. The example also builds independently against its
published dependencies with `GOWORK=off`.
from the repository root. The current unreleased example requires the aligned workspace until core and
the integrations are released with aligned dependencies.
The [consumer guide](../../../../docs/consumers/guide.md#module-selection) owns
version and compatibility details.
@@ -173,3 +173,14 @@ the complete application.
Run `GOWORK=auto GOTOOLCHAIN=local go test ./...` from this example directory
for an aligned workspace check. Use
`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.

View File

@@ -60,7 +60,8 @@ func (client *exampleLLMClient) Generate(context.Context, promptkit.GenerateRequ
if client.calls != nil {
(*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 {
@@ -338,8 +339,25 @@ func newAppWithEngineLoader(
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{
configCommand,
commandkit.Group("pipeline", "Run an application pipeline.", pipeline),
commandkit.Completion("composed-example"),
commandkit.Group("session", "Manage saved sessions.", restore),
commandkit.Group("request", "Inspect application-owned request inputs.", requestInspect),

View File

@@ -865,3 +865,176 @@ func TestComposedCampaignPromptID(t *testing.T) {
}
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())
}
}
}

View File

@@ -6,7 +6,7 @@ require (
go.maximumdirect.net/ckconfig v0.10.0
go.maximumdirect.net/commandkit v0.7.0
go.maximumdirect.net/configkit v1.4.0
go.maximumdirect.net/promptkit v0.24.0
go.maximumdirect.net/promptkit v0.25.0
go.yaml.in/yaml/v4 v4.0.0
)

View File

@@ -19,6 +19,8 @@ go.maximumdirect.net/configkit v1.4.0 h1:TfOupZbQ23/ZMs+xt5lmyukCF11ekqKep8KbmFQ
go.maximumdirect.net/configkit v1.4.0/go.mod h1:ewu6blSokUDCMovy8JBXAdXRikGmlHXAQpFghnPWRfs=
go.maximumdirect.net/promptkit v0.24.0 h1:C6UFY8WgW10PIEuXQN2Z0qi0at5mD3/GQoPul6alYHo=
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/v4 v4.0.0 h1:/LG1pNO84Z4l603j/xMn69CcS5OYhMQ/f7l2LoQUGuw=
go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=

View File

@@ -38,7 +38,8 @@ func TestResourceInspectionsForwardNativeReports(t *testing.T) {
extra := map[string]any{}
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}
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
calls := 0
suite := Suite[struct{}, struct{}]{

View File

@@ -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)
}
_ = invocation.Reporter().Report(commandkit.Report{Value: smokeReportFromNative(acquired.Value)})
_ = invocation.Reporter().Report(commandkit.Report{Value: smokeReportFromNative(acquired.Value), TextTemplate: smokeTextTemplate})
if operationErr != nil {
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 {
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 {
return definitionFailure(invocation.Context, "One or more PromptKit smoke tests failed.", combineSmokeExplanations(explanations), errors.Join(operationErrors...))
}

View File

@@ -1,6 +1,10 @@
package ckprompt
import (
"bytes"
"text/template"
commandkit "go.maximumdirect.net/commandkit"
"time"
promptkit "go.maximumdirect.net/promptkit"
@@ -88,6 +92,8 @@ type smokeAttemptDTO struct {
type smokeUsageDTO struct {
PromptTokens smokeTokenCount `json:"prompt_tokens"`
CompletionTokens smokeTokenCount `json:"completion_tokens"`
ReasoningTokens smokeTokenCount `json:"reasoning_tokens"`
CacheHitRatio *float64 `json:"cache_hit_ratio"`
TotalTokens smokeTokenCount `json:"total_tokens"`
CachedTokens smokeTokenCount `json:"cached_tokens"`
CacheWriteTokens smokeTokenCount `json:"cache_write_tokens"`
@@ -222,11 +228,33 @@ func durationString(duration *time.Duration) *string {
}
func smokeUsageFromNative(usage promptkit.ObservedTokenUsage) smokeUsageDTO {
var ratio *float64
if value, ok := usage.CacheHitRatio(); ok {
ratio = &value
}
return smokeUsageDTO{
PromptTokens: smokeTokenCount(usage.PromptTokens),
CompletionTokens: smokeTokenCount(usage.CompletionTokens),
ReasoningTokens: smokeTokenCount(usage.ReasoningTokens),
CacheHitRatio: ratio,
TotalTokens: smokeTokenCount(usage.TotalTokens),
CachedTokens: smokeTokenCount(usage.CachedTokens),
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))

View File

@@ -1,8 +1,12 @@
package ckprompt
import (
"bytes"
"errors"
commandkit "go.maximumdirect.net/commandkit"
"strings"
"testing"
"text/template"
"time"
promptkit "go.maximumdirect.net/promptkit"
@@ -215,3 +219,51 @@ func containsSmokeKey(value any, want string) bool {
}
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)
}
}
})
}
}

View 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 }}))

View 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())
}
}
})
}
}

View 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())
}
}

View File

@@ -77,7 +77,7 @@ func (session *Session) Parse(argv []string) commandmeta.Result {
}
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
if session.flagAliasesForPath != nil {
aliases = session.flagAliasesForPath(result.Path)
@@ -115,6 +115,15 @@ func (session *Session) Parse(argv []string) commandmeta.Result {
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 {
helpRequested, err := helpFlag.Value.(*rawValue).lastBool()
if err != nil {
@@ -271,7 +280,7 @@ func (session *Session) UsageLine(path []string) (string, *commandmeta.Failure)
if flag.Name != "debug" || !flag.Boolean {
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" {
spelling := "--debug"
if effective.Short != "" {
@@ -330,7 +339,7 @@ func buildTree(root *commandmeta.Command) (*spfcobra.Command, map[*spfcobra.Comm
helpFlag := backend.Flags().Lookup("help")
helpFlag.NoOptDefVal = "true"
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}
backend.Flags().VarP(value, declarationFlag.Name, declarationFlag.Short, flagUsage(declarationFlag))
backendFlag := backend.Flags().Lookup(declarationFlag.Name)

View File

@@ -17,6 +17,7 @@ type Command struct {
Flags []Flag
// CoreFlags are parsed by CommandKit but do not occupy consumer binding indexes.
CoreFlags []Flag
InvocationFlags []Flag
Arguments []Argument
Children []*Command
}
@@ -201,6 +202,8 @@ type Result struct {
HelpRequested bool
FlagValues [][]string
FlagSpellings [][]string
InvocationFlagValues [][]string
InvocationFlagSpellings [][]string
FlagOccurrences []FlagOccurrence
Reporting ReportingSelection
Operands []string

98
invocation_feature.go Normal file
View 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}
}

View 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
View 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)
}
}

View File

@@ -71,14 +71,17 @@ func (a *App) routeSnapshot() *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{
metadata: root,
runners: make(map[commandmeta.Key]commandPayload),
builtins: make(map[commandmeta.Key]bool),
aliases: a.aliases,
canonical: buildCanonicalTree(a.commands),
flagAliases: a.flagAliases,
discoveryFlags: a.discoveryFlags,
features: a.features,
featureFlags: a.featureFlags,
}
if node := a.commands["completion"]; node != nil {
snapshot.completion = node.command.record.completion
@@ -116,8 +119,10 @@ func bridgeCommand(node *canonicalNode, snapshot *routingSnapshot, next *command
Summary: record.summary,
Description: record.description,
CoreFlags: commandmeta.ReportingFlags(),
InvocationFlags: snapshot.featureFlags,
}
node.metadata = declaration
snapshot.builtins[declaration.Key] = record.builtin
if record.payload != nil {
snapshot.runners[declaration.Key] = record.payload
declaration.Runnable = record.payload.hasRun()

View File

@@ -28,6 +28,8 @@ type installationCandidate struct {
aliases *internalalias.Resolver
flagAliases map[string]resolvedFlagAliases
discoveryFlags map[string]resolvedFlagAliases
features []*invocationFeatureRecord
featureFlags []commandmeta.Flag
changed bool
}
@@ -91,6 +93,8 @@ func (a *App) installBatch(declarations ...Declaration) error {
a.aliases = candidate.aliases
a.flagAliases = candidate.flagAliases
a.discoveryFlags = candidate.discoveryFlags
a.features = candidate.features
a.featureFlags = candidate.featureFlags
a.snapshot = nil
return nil
}
@@ -154,11 +158,18 @@ func (a *App) buildInstallationCandidate(commands []Command, addedRules []Routin
}
candidate.aliases = resolver
candidate.features, candidate.featureFlags, err = collectInvocationFeatures(candidate.commands)
if err != nil {
return nil, err
}
tree := buildCanonicalTree(candidate.commands)
if err := validateInvocationFlagCollisions(tree, candidate.featureFlags); err != nil {
return nil, err
}
if err := validateCommandAliases(rules, resolver, tree); err != nil {
return nil, err
}
flagAliases, discoveryFlags, err := compileFlagAliases(rules, tree, resolver)
flagAliases, discoveryFlags, err := compileFlagAliases(rules, tree, resolver, candidate.featureFlags)
if err != nil {
return nil, err
}
@@ -365,3 +376,65 @@ func acceptsOperandPrefix(command Command, count int) bool {
}
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
}

View File

@@ -203,6 +203,32 @@ func (r *Reporter) RenderOutput(write func(io.Writer) error) error {
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
// visibility follows the selected reporting mode.
func (r *Reporter) Info(message string, details ...Detail) error {
@@ -287,7 +313,7 @@ func (r DeferredReporter) enqueue(category messageCategory, message string, deta
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 {
return normalizeOutcome(outcome)
}
@@ -314,6 +340,12 @@ func (r *Reporter) finalize(outcome Outcome, completion func(*Reporter)) Outcome
completion(r)
}
for _, produce := range producers {
if produce != nil {
_ = r.renderDiagnosticReport(produce())
}
}
state.mu.Lock()
if presentationFailedLocked(state) {
if outcome.Status == 0 && !hasExplanation(outcome.Explanation) {