Document and validate automatic usage reporting

This commit is contained in:
2026-11-22 21:06:39 +00:00
parent a0608a53ee
commit a0cdd3d7c5
13 changed files with 188 additions and 30 deletions

2
doc.go
View File

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

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 `api_key_env` value names an environment variable; it is not a credential
value or a claim that one is available. Neither report resolves references or value or a claim that one is available. Neither report resolves references or
performs a network probe. See the [PromptKit resource inspection performs a network probe. See the [PromptKit resource inspection
contracts](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/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 Omitting the ID is a usage error. Configuration loading follows the
[configuration failure classification](#configuration-failure-classification); [configuration failure classification](#configuration-failure-classification);
lookup failures and cancellation are operational. lookup failures and cancellation are operational.
@@ -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 application content in the report. It does not guarantee that a later model
call will succeed. Application loaders and callbacks may have their own call will succeed. Application loaders and callbacks may have their own
effects. The [PromptKit Prepare effects. The [PromptKit Prepare
API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/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 owns the prepared value and upstream preparation behavior. Configuration failures
follow the [configuration failure classification](#configuration-failure-classification); follow the [configuration failure classification](#configuration-failure-classification);
other preparation failures are operational. other preparation failures are operational.
@@ -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 namespace qualifies an explicitly supplied short profile ID; it does not
rewrite the prompt's stored default reference. Requirements inspection does rewrite the prompt's stored default reference. Requirements inspection does
not require the selected profile to be execution-ready. See the [PromptKit not require the selected profile to be execution-ready. See the [PromptKit
v0.24.0 consumer v0.25.0 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 configuration, selection, and requirements behavior. For built-in flags for configuration, selection, and requirements behavior. For built-in flags
other than `--llm-var`, repeating a flag uses its last value. other than `--llm-var`, repeating a flag uses its last value.
Application-defined flags follow their own repetition rules. Application-defined flags follow their own repetition rules.
@@ -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 snapshot. A successful report describes this preparation invocation; it does
not certify provider acceptance or guarantee later execution. See PromptKit's not certify provider acceptance or guarantee later execution. See PromptKit's
[`Engine.ValidateRequest` [`Engine.ValidateRequest`
API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/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 Configuration errors returned by request construction or engine loading follow
the [configuration failure classification](#configuration-failure-classification). 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. A catalog result is an inventory, not a readiness check or execution result.
The owning provider controls membership and order. Namespace filters are The owning provider controls membership and order. Namespace filters are
passed to PromptKit without local membership interpretation. See the passed to PromptKit without local membership interpretation. See the
[PromptKit v0.24.0 consumer [PromptKit v0.25.0 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 resource and selection definitions. Catalog loading failures follow the for resource and selection definitions. Catalog loading failures follow the
[configuration failure classification](#configuration-failure-classification). [configuration failure classification](#configuration-failure-classification).
## PromptKit usage reporting
A nonempty PromptKit integration makes `--show-tokens` available after the full
command path, including application commands. It defaults to false; repeat it
or use `--show-tokens=false` to select the final Boolean value. When requested,
the diagnostic stream receives observed PromptKit execution totals after deferred
messages and before any terminal explanation. The summary is visible in ordinary,
verbose, and debug modes; quiet suppresses it. Main output and its `--format` are
independent. Help, version, completion, routing/parsing failures and rejected
command input produce no summary.
The report distinguishes unknown and incomplete token counts, cost and terminal
coverage. Cache hit ratio is shown when available; known costs include native
source information when present. Empty groups report native zero totals, not
measurements of smoke tests. Smoke-test usage appears separately in its command
report. Smoke reports default to text; `--format yaml` or `--format json` selects
structured output.
## PromptKit smoke testing ## PromptKit smoke testing
`promptkit test KIND` runs a PromptKit smoke test using the application's `promptkit test KIND` runs a PromptKit smoke test using the application's
@@ -1116,9 +1134,9 @@ separately from delivery failures through the [reporting
API](consumers/guide.md#invocation-reporting). API](consumers/guide.md#invocation-reporting).
Native configuration, selection, and diagnostic meanings remain owned by Native configuration, selection, and diagnostic meanings remain owned by
PromptKit. See the [v0.24.0 consumer guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/docs/consumers/pkg-promptkit.md), PromptKit. See the [v0.25.0 consumer guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/docs/consumers/pkg-promptkit.md),
[smoke API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/smoke_diagnostics.go), [smoke API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/smoke_diagnostics.go),
and [engine API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/engine.go). and [engine API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/engine.go).
## Outcome status ## Outcome status

View File

@@ -46,11 +46,12 @@ loaders should use keyed struct literals when constructing them. ConfigKit's
release notes describe release notes describe
main-relative imports and overlay contexts. [ConfigKit v1.2.0 upgrade guidance](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.2.0/docs/releases/v1.2.0.md#upgrade-notes). main-relative imports and overlay contexts. [ConfigKit v1.2.0 upgrade guidance](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.2.0/docs/releases/v1.2.0.md#upgrade-notes).
The current checkout selects PromptKit v0.24.0. Complete documents put The current unreleased checkout selects PromptKit v0.25.0 and requires the local
core through the aligned workspace. Complete documents put
settings under `promptkit`; wrapperless fragments use `SettingsInput`, and settings under `promptkit`; wrapperless fragments use `SettingsInput`, and
collection fragments use `CollectionInput`. Consult the [upstream migration 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) 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.24.0/docs/formats.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. for the exact migration and schema rules.
Importing a module does not install its commands. Pass commands to Importing a module does not install its commands. Pass commands to
@@ -392,6 +393,24 @@ suite := ckprompt.WithRequestValidation(
validationCommand := ckprompt.Command(suite) validationCommand := ckprompt.Command(suite)
``` ```
### Automatic usage reporting
Installing a nonempty ckprompt family with either `Command` or `Declarations`
adds `--show-tokens` to application commands as well as PromptKit commands.
An empty suite adds nothing. The flag defaults to false; explicit false and
repeated selections use the ordinary Boolean rules. Applications pass
`Invocation.Context` into PromptKit and wait for their own work before returning.
The observer starts after command input construction and successful `CheckInput`,
before `Run`; validation or acquisition inside `Run` is included. Help, version,
completion, parse errors, and rejected command inputs do not start observation.
The requested summary is text on diagnostics after deferred messages and before
any failure explanation, independently of the main report's `--format`. Quiet
suppresses delivery. Counts and cost preserve unknown and incomplete states,
known zero, cost source, and terminal coverage; the cache ratio is shown only when
available. Smoke tests report their own usage separately. An empty ordinary
summary is not a measurement of smoke-test usage. See the [operator reference](../cli.md#promptkit-usage-reporting).
### Request builders and loading ### Request builders and loading
If the loader is nil, the returned suite retains a wiring issue for installation If the loader is nil, the returned suite retains a wiring issue for installation
@@ -436,7 +455,7 @@ and uses `Engine.ValidateRequest`.
Applications own engine construction and may build complete native requests in Applications own engine construction and may build complete native requests in
callbacks. Preparation and validation use the supplied context; execution owns callbacks. Preparation and validation use the supplied context; execution owns
prepared notifications and operation timeouts. See the [PromptKit consumer prepared notifications and operation timeouts. See the [PromptKit consumer
guide](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/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. for conversation and execution capabilities.
`ckprompt.WithRequestPreparation` adds a separate callback backed by `ckprompt.WithRequestPreparation` adds a separate callback backed by
@@ -499,7 +518,7 @@ These are independent defaults for unqualified caller-supplied prompt, profile,
and backend names; qualified IDs pass through. Stored references and configuration and backend names; qualified IDs pass through. Stored references and configuration
inspection are unchanged, while namespace and collection inventories remain global. inspection are unchanged, while namespace and collection inventories remain global.
Catalog `--namespace` filters are separate from these defaults. See the released Catalog `--namespace` filters are separate from these defaults. See the released
[namespace API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/namespaces.go). [namespace API](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/namespaces.go).
## Outcomes and ownership ## Outcomes and ownership
@@ -514,7 +533,7 @@ Go declarations and GoDoc own exact exported contracts. ConfigKit owns
configuration decoding, validation, and provenance. PromptKit owns prompt configuration decoding, validation, and provenance. PromptKit owns prompt
formats, profile resolution, and inspection details. See the formats, profile resolution, and inspection details. See the
[ConfigKit v1.4.0 source records](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3/records.go), [ConfigKit v1.4.0 source records](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3/records.go),
[PromptKit engine methods](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/engine.go), [PromptKit engine methods](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/engine.go),
[configuration inspection](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/configuration_inspection.go), [configuration inspection](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/configuration_inspection.go),
[smoke diagnostics](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/smoke_diagnostics.go), [smoke diagnostics](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/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). 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,13 @@ If a workspace already exists, ensure it includes these three modules. Preserve
the ignored `go.work` and `go.work.sum`; do not commit them. Use the ignored `go.work` and `go.work.sum`; do not commit them. Use
`GOWORK=off GOTOOLCHAIN=local` for dependency preparation `GOWORK=off GOTOOLCHAIN=local` for dependency preparation
and independent module suites. Both integrations select released core v0.7.0; and independent module suites. Both integrations select released core v0.7.0;
ckprompt selects released ckconfig v0.10.0. All three modules support independent ckprompt selects released ckconfig v0.10.0. Core and ckconfig build independently
builds against their published dependencies. Run each independent suite with against their published dependencies. Unreleased ckprompt uses newer local core
`GOWORK=off GOTOOLCHAIN=local go test ./...` from its module directory. APIs and needs the aligned workspace until downstream releases are prepared. For
an isolated source check, use a temporary modfile replacing core and ckconfig with
local sources. Before ckprompt publication, repeat its independent suite against
the newly published dependency versions. Run independent suites with
`GOWORK=off GOTOOLCHAIN=local go test ./...` from the module directory.
The aligned workspace exercises local sources together. From the root, The aligned workspace exercises local sources together. From the root,
all three modules can also run: 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 mode independently of the prepared application value. The invocation's mode
accessor reads the reporter's selection under its existing state mutex. accessor reads the reporter's selection under its existing state mutex.
Captured invocation features contribute application-wide flags through the same
parser and alias views. The installer deduplicates handles and validates the
prospective registry atomically. Each invocation prepares feature values, starts
features after successful command input checking, and retains returned report
producers only until finalization. Generated builtins do not start features.
The reporter owns invocation-scoped visibility, message formatting, managed The reporter owns invocation-scoped visibility, message formatting, managed
report rendering, delivery observations, and finalization. It presents queued report rendering, delivery observations, and finalization. It presents queued
messages after the handler returns, then a failed outcome's explanation, and messages after the handler returns, then feature reports, then a failed outcome's explanation, and
closes its handles before `Execute` returns. It records rendering and write closes its handles before `Execute` returns. It records rendering and write
errors separately for result and diagnostic destinations; the returned errors separately for result and diagnostic destinations; the returned
`Outcome.Presentation` exposes those observations independently from the `Outcome.Presentation` exposes those observations independently from the

View File

@@ -1,7 +1,7 @@
# Automatic PromptKit Usage Reporting # Automatic PromptKit Usage Reporting
Status: target state agreed; PromptKit v0.25.0 reviewed and available; Status: implemented; retained for review. See the implementation record for
implementation not started. validation and release follow-up.
## Purpose ## Purpose
@@ -17,7 +17,7 @@ final reporting callbacks. Audita review commands and Notarius pipelines
motivate the feature; their domain execution remains application-owned. motivate the feature; their domain execution remains application-owned.
This roadmap describes the agreed end state and the work needed to reach it. This roadmap describes the agreed end state and the work needed to reach it.
It does not describe implemented behavior. The [implementation plan](implementation.md) The [implementation plan](implementation.md)
owns the concrete API, wiring example, ordered stages, and validation steps. owns the concrete API, wiring example, ordered stages, and validation steps.
## Target Behavior ## Target Behavior

View File

@@ -1,6 +1,6 @@
# Automatic Usage Reporting Implementation Plan # Automatic Usage Reporting Implementation Plan
Status: ready for review; implementation not started. Status: implementation complete; retained for review.
## Scope and execution ## Scope and execution
@@ -378,6 +378,20 @@ no invocation summary. Record the focused integration and consumer suite results
## Stage 8: Finish documentation, validation, and sprint records ## Stage 8: Finish documentation, validation, and sprint records
**Complete.** Updated GoDoc, CLI and consumer guidance, internal inventory, and
workspace instructions. Go 1.27.4 passed the three workspace `go test` suites;
independent root and ckconfig suites passed with `GOWORK=off`. An isolated
ckprompt suite passed with a temporary modfile replacing core and ckconfig with
local sources and selecting published PromptKit v0.25.0. Offline pipeline text,
JSON, quiet and disabled runs passed; smoke separation passed using the injected
consumer fixture. Formatting, local links, dependency boundaries and diff checks
were reviewed. Final validation also fixed required invocation flags blocking
generated version or group help.
Release follow-up: publish core, align and publish ckconfig, then align ckprompt
with the published releases and run its independent suite against those versions
before publishing. No release versions or publication are selected here.
1. Update core and ckprompt GoDoc, CLI reference, consumer guide, and internal 1. Update core and ckprompt GoDoc, CLI reference, consumer guide, and internal
inventory. Explain automatic installation, observer context responsibilities, inventory. Explain automatic installation, observer context responsibilities,
exact CheckInput/Run boundary, empty-suite absence, Boolean selection, visibility, exact CheckInput/Run boundary, empty-suite absence, Boolean selection, visibility,

View File

@@ -43,9 +43,12 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco
var outcome Outcome var outcome Outcome
path := parsed.Path path := parsed.Path
handlerRan := false handlerRan := false
payload := routedSnapshot.runners[parsed.Key]
featureRequired := !parsed.HelpRequested && current.route.kind == routeCanonical &&
payload != nil && payload.hasRun() && !routedSnapshot.builtins[parsed.Key]
if parsed.Failure != nil { if parsed.Failure != nil {
outcome = Usage(parsed.Failure.Message) outcome = Usage(parsed.Failure.Message)
} else if err := current.prepareFeatures(parsed, !parsed.HelpRequested && current.route.kind == routeCanonical); err != nil { } else if err := current.prepareFeatures(parsed, featureRequired); err != nil {
outcome = classifyInputError(err) outcome = classifyInputError(err)
} else if current.route.kind == routeDiscovery { } else if current.route.kind == routeDiscovery {
if parsed.HelpRequested { if parsed.HelpRequested {

View File

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

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 Use Go 1.27.0 on `PATH`. An aligned workspace containing all three local modules
exercises their current sources; follow the [workspace setup](../../../../docs/development.md#documentation-validation) exercises their current sources; follow the [workspace setup](../../../../docs/development.md#documentation-validation)
from the repository root. The example also builds independently against its from the repository root. The current unreleased example requires the aligned workspace until core and
published dependencies with `GOWORK=off`. the integrations are released with aligned dependencies.
The [consumer guide](../../../../docs/consumers/guide.md#module-selection) owns The [consumer guide](../../../../docs/consumers/guide.md#module-selection) owns
version and compatibility details. version and compatibility details.
@@ -173,3 +173,14 @@ the complete application.
Run `GOWORK=auto GOTOOLCHAIN=local go test ./...` from this example directory Run `GOWORK=auto GOTOOLCHAIN=local go test ./...` from this example directory
for an aligned workspace check. Use for an aligned workspace check. Use
`GOWORK=off GOTOOLCHAIN=local go test ./...` to check the declared releases. `GOWORK=off GOTOOLCHAIN=local go test ./...` to check the declared releases.
## Observe a pipeline
```sh
go run . pipeline run --show-tokens
go run . pipeline run --show-tokens --format json
```
The application passes its invocation context to both prompt executions. The
injected client provides the example usage and cost; ckprompt reports their
aggregate on diagnostics without accounting code in the pipeline handler.

View File

@@ -1005,3 +1005,22 @@ func TestSmokeUsageIsSeparateAndAliasAware(t *testing.T) {
} }
} }
} }
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())
}
}

View File

@@ -15,6 +15,13 @@ type InvocationFeature struct{ record *invocationFeatureRecord }
// NewInput creates fresh input for each invocation; nil uses the zero value. // NewInput creates fresh input for each invocation; nil uses the zero value.
// Start receives the current invocation and may return a replacement context // Start receives the current invocation and may return a replacement context
// and a function producing a report at invocation finalization. Start is required. // 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 { type InvocationFeatureSpec[I any] struct {
NewInput func() I NewInput func() I
Flags []Flag[I] Flags []Flag[I]

View File

@@ -254,3 +254,52 @@ func TestInvocationFeatureDiagnosticFailures(t *testing.T) {
}) })
} }
} }
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())
}
}